From 83dad0d6b3151af976430d8d6603e2580b453c06 Mon Sep 17 00:00:00 2001 From: kjubybot Date: Tue, 17 May 2022 14:52:36 +0300 Subject: [PATCH 01/51] added golang in depcheck pipeline --- Jenkinsfile-sast | 16 +++++++--------- 1 file changed, 7 insertions(+), 9 deletions(-) diff --git a/Jenkinsfile-sast b/Jenkinsfile-sast index 5a2cd93..76b4ebe 100644 --- a/Jenkinsfile-sast +++ b/Jenkinsfile-sast @@ -20,15 +20,13 @@ spec: DEPCHECKDB = credentials('depcheck-postgres') } steps { - container('alpine') { - sh 'apk update && apk add openjdk11 java-postgresql-jdbc' - dependencyCheck additionalArguments: '-f JSON -f HTML -n --enableExperimental\ - --dbDriverName org.postgresql.Driver \ - --dbDriverPath /usr/share/java/postgresql-jdbc.jar \ - --dbUser $DEPCHECKDB_USR \ - --dbPassword $DEPCHECKDB_PSW \ - --connectionString jdbc:postgresql://postgres-postgresql.postgres/depcheck', odcInstallation: 'depcheck' - } + sh 'apk update && apk add openjdk11 java-postgresql-jdbc go' + dependencyCheck additionalArguments: '-f JSON -f HTML -n --enableExperimental\ + --dbDriverName org.postgresql.Driver \ + --dbDriverPath /usr/share/java/postgresql-jdbc.jar \ + --dbUser $DEPCHECKDB_USR \ + --dbPassword $DEPCHECKDB_PSW \ + --connectionString jdbc:postgresql://postgres-postgresql.postgres/depcheck', odcInstallation: 'depcheck' } } stage('SonarQube analysis') { From d35fa26eb8ac340648d86f3aec2de85e7e20f9cf Mon Sep 17 00:00:00 2001 From: kjubybot Date: Tue, 17 May 2022 14:58:40 +0300 Subject: [PATCH 02/51] increased depcheck logging verbosity --- Jenkinsfile-sast | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/Jenkinsfile-sast b/Jenkinsfile-sast index 76b4ebe..b71393a 100644 --- a/Jenkinsfile-sast +++ b/Jenkinsfile-sast @@ -21,12 +21,14 @@ spec: } steps { sh 'apk update && apk add openjdk11 java-postgresql-jdbc go' - dependencyCheck additionalArguments: '-f JSON -f HTML -n --enableExperimental\ + dependencyCheck additionalArguments: '-f JSON -f HTML -n --enableExperimental \ + -l deplog \ --dbDriverName org.postgresql.Driver \ --dbDriverPath /usr/share/java/postgresql-jdbc.jar \ --dbUser $DEPCHECKDB_USR \ --dbPassword $DEPCHECKDB_PSW \ --connectionString jdbc:postgresql://postgres-postgresql.postgres/depcheck', odcInstallation: 'depcheck' + sh 'cat deplog' } } stage('SonarQube analysis') { From 2797a10fcb78d23077127c41e5c348b7c32f0bfc Mon Sep 17 00:00:00 2001 From: kjubybot Date: Tue, 17 May 2022 15:00:51 +0300 Subject: [PATCH 03/51] fixed pipeline --- Jenkinsfile-sast | 20 +++++++++++--------- 1 file changed, 11 insertions(+), 9 deletions(-) diff --git a/Jenkinsfile-sast b/Jenkinsfile-sast index b71393a..8e6ae2a 100644 --- a/Jenkinsfile-sast +++ b/Jenkinsfile-sast @@ -20,15 +20,17 @@ spec: DEPCHECKDB = credentials('depcheck-postgres') } steps { - sh 'apk update && apk add openjdk11 java-postgresql-jdbc go' - dependencyCheck additionalArguments: '-f JSON -f HTML -n --enableExperimental \ - -l deplog \ - --dbDriverName org.postgresql.Driver \ - --dbDriverPath /usr/share/java/postgresql-jdbc.jar \ - --dbUser $DEPCHECKDB_USR \ - --dbPassword $DEPCHECKDB_PSW \ - --connectionString jdbc:postgresql://postgres-postgresql.postgres/depcheck', odcInstallation: 'depcheck' - sh 'cat deplog' + container('alpine') { + sh 'apk update && apk add openjdk11 java-postgresql-jdbc go' + dependencyCheck additionalArguments: '-f JSON -f HTML -n --enableExperimental \ + -l deplog \ + --dbDriverName org.postgresql.Driver \ + --dbDriverPath /usr/share/java/postgresql-jdbc.jar \ + --dbUser $DEPCHECKDB_USR \ + --dbPassword $DEPCHECKDB_PSW \ + --connectionString jdbc:postgresql://postgres-postgresql.postgres/depcheck', odcInstallation: 'depcheck' + sh 'cat deplog' + } } } stage('SonarQube analysis') { From b849521780413e44efd8b5f23403b6506a8f71ae Mon Sep 17 00:00:00 2001 From: stSolo Date: Wed, 18 May 2022 10:25:40 +0300 Subject: [PATCH 04/51] Add disk-list --- decort/data_source_disk_list.go | 391 ++++++++++++++++++++++++++++++++ decort/models_api.go | 85 ++++--- decort/provider.go | 1 + decort/utility_disk_list.go | 68 ++++++ samples/README.md | 1 + samples/data_disk_list/main.tf | 54 +++++ 6 files changed, 566 insertions(+), 34 deletions(-) create mode 100644 decort/data_source_disk_list.go create mode 100644 decort/utility_disk_list.go create mode 100644 samples/data_disk_list/main.tf diff --git a/decort/data_source_disk_list.go b/decort/data_source_disk_list.go new file mode 100644 index 0000000..fa118aa --- /dev/null +++ b/decort/data_source_disk_list.go @@ -0,0 +1,391 @@ +/* +Copyright (c) 2019-2021 Digital Energy Cloud Solutions LLC. All Rights Reserved. +Author: Sergey Shubin, , + +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. +*/ + +/* +This file is part of Terraform (by Hashicorp) provider for Digital Energy Cloud Orchestration +Technology platfom. + +Visit https://github.com/rudecs/terraform-provider-decort for full source code package and updates. +*/ + +package decort + +import ( + "encoding/json" + + "github.com/google/uuid" + "github.com/hashicorp/terraform-plugin-sdk/helper/schema" +) + +func flattenDiskList(dl DisksListResp) []map[string]interface{} { + res := make([]map[string]interface{}, 0) + for _, disk := range dl { + diskAcl, _ := json.Marshal(disk.Acl) + diskIotune, _ := json.Marshal(disk.IOTune) + temp := map[string]interface{}{ + "account_id": disk.AccountID, + "account_name": disk.AccountName, + "acl": string(diskAcl), + "boot_partition": disk.BootPartition, + "compute_id": disk.ComputeID, + "compute_name": disk.ComputeName, + "created_time": disk.CreatedTime, + "deleted_time": disk.DeletedTime, + "desc": disk.Desc, + "destruction_time": disk.DestructionTime, + "devicename": disk.DeviceName, + "disk_path": disk.DiskPath, + "gid": disk.GridID, + "guid": disk.GUID, + "disk_id": disk.ID, + "image_id": disk.ImageID, + "images": disk.Images, + "iotune": string(diskIotune), + "iqn": disk.IQN, + "login": disk.Login, + "machine_id": disk.MachineId, + "machine_name": disk.MachineName, + "milestones": disk.Milestones, + "name": disk.Name, + "order": disk.Order, + "params": disk.Params, + "parent_id": disk.ParentId, + "passwd": disk.Passwd, + "pci_slot": disk.PciSlot, + "pool": disk.Pool, + "purge_attempts": disk.PurgeAttempts, + "purge_time": disk.PurgeTime, + "reality_device_number": disk.RealityDeviceNumber, + "reference_id": disk.ReferenceId, + "res_id": disk.ResID, + "res_name": disk.ResName, + "role": disk.Role, + "sep_id": disk.SepID, + "sep_type": disk.SepType, + "size_max": disk.SizeMax, + "size_used": disk.SizeUsed, + "snapshots": flattendDiskSnapshotList(disk.Snapshots), + "status": disk.Status, + "tech_status": disk.TechStatus, + "type": disk.Type, + "vmid": disk.VMID, + "update_by": disk.UpdateBy, + } + res = append(res, temp) + } + return res + +} + +func flattendDiskSnapshotList(sl SnapshotRecordList) []interface{} { + res := make([]interface{}, 0) + for _, snapshot := range sl { + temp := map[string]interface{}{ + "guid": snapshot.Guid, + "label": snapshot.Label, + "res_id": snapshot.ResId, + "snap_set_guid": snapshot.SnapSetGuid, + "snap_set_time": snapshot.SnapSetTime, + "timestamp": snapshot.TimeStamp, + } + res = append(res, temp) + } + + return res + +} + +func dataSourceDiskListRead(d *schema.ResourceData, m interface{}) error { + diskList, err := utilityDiskListCheckPresence(d, m) + if err != nil { + return err + } + + id := uuid.New() + d.SetId(id.String()) + d.Set("items", flattenDiskList(diskList)) + + return nil +} + +func dataSourceDiskListSchemaMake() map[string]*schema.Schema { + res := map[string]*schema.Schema{ + "account_id": { + Type: schema.TypeInt, + Optional: true, + Description: "ID of the account the disks belong to", + }, + "type": { + Type: schema.TypeString, + Optional: true, + Description: "type of the disks", + }, + "page": { + Type: schema.TypeInt, + Optional: true, + Description: "Page number", + }, + "size": { + Type: schema.TypeInt, + Optional: true, + Description: "Page size", + }, + "items": { + Type: schema.TypeList, + Computed: true, + Elem: &schema.Resource{ + Schema: map[string]*schema.Schema{ + "account_id": { + Type: schema.TypeInt, + Computed: true, + }, + "account_name": { + Type: schema.TypeString, + Computed: true, + }, + "acl": { + Type: schema.TypeString, + Computed: true, + }, + "boot_partition": { + Type: schema.TypeInt, + Computed: true, + }, + "compute_id": { + Type: schema.TypeInt, + Computed: true, + }, + "compute_name": { + Type: schema.TypeString, + Computed: true, + }, + "created_time": { + Type: schema.TypeInt, + Computed: true, + }, + "deleted_time": { + Type: schema.TypeInt, + Computed: true, + }, + "desc": { + Type: schema.TypeString, + Computed: true, + }, + "destruction_time": { + Type: schema.TypeInt, + Computed: true, + }, + "devicename": { + Type: schema.TypeString, + Computed: true, + }, + "disk_path": { + Type: schema.TypeString, + Computed: true, + }, + "gid": { + Type: schema.TypeInt, + Computed: true, + }, + "guid": { + Type: schema.TypeInt, + Computed: true, + }, + "disk_id": { + Type: schema.TypeInt, + Computed: true, + }, + "image_id": { + Type: schema.TypeInt, + Computed: true, + }, + "images": { + Type: schema.TypeList, + Computed: true, + Elem: &schema.Schema{ + Type: schema.TypeString, + }, + }, + "iotune": { + Type: schema.TypeString, + Computed: true, + }, + "iqn": { + Type: schema.TypeString, + Computed: true, + }, + "login": { + Type: schema.TypeString, + Computed: true, + }, + "machine_id": { + Type: schema.TypeInt, + Computed: true, + }, + "machine_name": { + Type: schema.TypeString, + Computed: true, + }, + "milestones": { + Type: schema.TypeInt, + Computed: true, + }, + "name": { + Type: schema.TypeString, + Computed: true, + }, + "order": { + Type: schema.TypeInt, + Computed: true, + }, + "params": { + Type: schema.TypeString, + Computed: true, + }, + "parent_id": { + Type: schema.TypeInt, + Computed: true, + }, + "passwd": { + Type: schema.TypeString, + Computed: true, + }, + "pci_slot": { + Type: schema.TypeInt, + Computed: true, + }, + "pool": { + Type: schema.TypeString, + Computed: true, + }, + "purge_attempts": { + Type: schema.TypeInt, + Computed: true, + }, + "purge_time": { + Type: schema.TypeInt, + Computed: true, + }, + "reality_device_number": { + Type: schema.TypeInt, + Computed: true, + }, + "reference_id": { + Type: schema.TypeString, + Computed: true, + }, + "res_id": { + Type: schema.TypeString, + Computed: true, + }, + "res_name": { + Type: schema.TypeString, + Computed: true, + }, + "role": { + Type: schema.TypeString, + Computed: true, + }, + "sep_id": { + Type: schema.TypeInt, + Computed: true, + }, + "sep_type": { + Type: schema.TypeString, + Computed: true, + }, + "size_max": { + Type: schema.TypeInt, + Computed: true, + }, + "size_used": { + Type: schema.TypeInt, + Computed: true, + }, + "snapshots": { + Type: schema.TypeList, + Computed: true, + Elem: &schema.Resource{ + Schema: map[string]*schema.Schema{ + "guid": { + Type: schema.TypeString, + Computed: true, + }, + "label": { + Type: schema.TypeString, + Computed: true, + }, + "res_id": { + Type: schema.TypeString, + Computed: true, + }, + "snap_set_guid": { + Type: schema.TypeString, + Computed: true, + }, + "snap_set_time": { + Type: schema.TypeInt, + Computed: true, + }, + "timestamp": { + Type: schema.TypeInt, + Computed: true, + }, + }, + }, + }, + "status": { + Type: schema.TypeString, + Computed: true, + }, + "tech_status": { + Type: schema.TypeString, + Computed: true, + }, + "type": { + Type: schema.TypeString, + Computed: true, + }, + "vmid": { + Type: schema.TypeInt, + Computed: true, + }, + "update_by": { + Type: schema.TypeInt, + Computed: true, + }, + }, + }, + }, + } + return res +} + +func dataSourceDiskList() *schema.Resource { + return &schema.Resource{ + SchemaVersion: 1, + + Read: dataSourceDiskListRead, + + Timeouts: &schema.ResourceTimeout{ + Read: &Timeout30s, + Default: &Timeout60s, + }, + + Schema: dataSourceDiskListSchemaMake(), + } +} diff --git a/decort/models_api.go b/decort/models_api.go index ee1e5e3..034cb17 100644 --- a/decort/models_api.go +++ b/decort/models_api.go @@ -298,46 +298,62 @@ const ComputeResizeAPI = "/restmachine/cloudapi/compute/resize" type SnapshotRecord struct { Guid string `json:"guid"` Label string `json:"label"` + ResId string `json:"resId"` SnapSetGuid string `json:"snapSetGuid"` SnapSetTime uint64 `json:"snapSetTime"` TimeStamp uint64 `json:"timestamp"` } +type SnapshotRecordList []SnapshotRecord + type DiskRecord struct { - // ACLs `json:"ACL"` - it is a dictionary, special parsing required - // was - Acl map[string]string `json:"acl"` - AccountID int `json:"accountId"` - AccountName string `json:"accountName"` // NOTE: absent from compute/get output - BootPartition int `json:"bootPartition"` - CreatedTime uint64 `json:"creationTime"` - DeletedTime uint64 `json:"deletionTime"` - Desc string `json:"desc"` - DestructionTime uint64 `json:"destructionTime"` - DiskPath string `json:"diskPath"` - GridID int `json:"gid"` - ID uint `json:"id"` - ImageID int `json:"imageId"` - Images []int `json:"images"` - // IOTune 'json:"iotune" - it is a dictionary - Name string `json:"name"` - // Order `json:"order"` - ParentId int `json:"parentId"` - PciSlot int `json:"pciSlot"` - // ResID string `json:"resId"` - // ResName string `json:"resName"` - // Params string `json:"params"` - Pool string `json:"pool"` - PurgeTime uint64 `json:"purgeTime"` - // Role string `json:"role"` - SepType string `json:"sepType"` - SepID int `json:"sepId"` // NOTE: absent from compute/get output - SizeMax int `json:"sizeMax"` - SizeUsed int `json:"sizeUsed"` // sum over all snapshots of this disk to report total consumed space - Snapshots []SnapshotRecord `json:"snapshots"` - Status string `json:"status"` - TechStatus string `json:"techStatus"` - Type string `json:"type"` - ComputeID int `json:"vmid"` + Acl map[string]interface{} `json:"acl"` + AccountID int `json:"accountId"` + AccountName string `json:"accountName"` + BootPartition int `json:"bootPartition"` + CreatedTime uint64 `json:"creationTime"` + ComputeID int `json:"computeId"` + ComputeName string `json:"computeName"` + DeletedTime uint64 `json:"deletionTime"` + DeviceName string `json:"devicename"` + Desc string `json:"desc"` + DestructionTime uint64 `json:"destructionTime"` + DiskPath string `json:"diskPath"` + GridID int `json:"gid"` + GUID int `json:"guid"` + ID uint `json:"id"` + ImageID int `json:"imageId"` + Images []int `json:"images"` + IOTune map[string]interface{} `json:"iotune"` + IQN string `json:"iqn"` + Login string `json:"login"` + Name string `json:"name"` + MachineId int `json:"machineId"` + MachineName string `json:"machineName"` + Milestones uint64 `json:"milestones"` + Order int `json:"order"` + Params string `json:"params"` + Passwd string `json:"passwd"` + ParentId int `json:"parentId"` + PciSlot int `json:"pciSlot"` + Pool string `json:"pool"` + PurgeTime uint64 `json:"purgeTime"` + PurgeAttempts uint64 `json:"purgeAttempts"` + RealityDeviceNumber int `json:"realityDeviceNumber"` + ReferenceId string `json:"referenceId"` + ResID string `json:"resId"` + ResName string `json:"resName"` + Role string `json:"role"` + SepType string `json:"sepType"` + SepID int `json:"sepId"` // NOTE: absent from compute/get output + SizeMax int `json:"sizeMax"` + SizeUsed int `json:"sizeUsed"` // sum over all snapshots of this disk to report total consumed space + Snapshots []SnapshotRecord `json:"snapshots"` + Status string `json:"status"` + TechStatus string `json:"techStatus"` + Type string `json:"type"` + UpdateBy uint64 `json:"updateBy"` + VMID int `json:"vmid"` } type OsUserRecord struct { @@ -502,6 +518,7 @@ const DisksCreateAPI = "/restmachine/cloudapi/disks/create" const DisksGetAPI = "/restmachine/cloudapi/disks/get" // Returns single DiskRecord on success const DisksListAPI = "/restmachine/cloudapi/disks/list" // Returns list of DiskRecord on success + type DisksListResp []DiskRecord // diff --git a/decort/provider.go b/decort/provider.go index c2a4aa1..2d9e3a9 100644 --- a/decort/provider.go +++ b/decort/provider.go @@ -137,6 +137,7 @@ func Provider() *schema.Provider { "decort_sep_disk_list": dataSourceSepDiskList(), "decort_sep_config": dataSourceSepConfig(), "decort_sep_pool": dataSourceSepPool(), + "decort_disk_list": dataSourceDiskList(), // "decort_pfw": dataSourcePfw(), }, diff --git a/decort/utility_disk_list.go b/decort/utility_disk_list.go new file mode 100644 index 0000000..447f92c --- /dev/null +++ b/decort/utility_disk_list.go @@ -0,0 +1,68 @@ +/* +Copyright (c) 2019-2022 Digital Energy Cloud Solutions LLC. All Rights Reserved. +Author: Stanislav Solovev, , + +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. +*/ + +/* +This file is part of Terraform (by Hashicorp) provider for Digital Energy Cloud Orchestration +Technology platfom. + +Visit https://github.com/rudecs/terraform-provider-decort for full source code package and updates. +*/ + +package decort + +import ( + "encoding/json" + "net/url" + "strconv" + "strings" + + log "github.com/sirupsen/logrus" + + "github.com/hashicorp/terraform-plugin-sdk/helper/schema" +) + +func utilityDiskListCheckPresence(d *schema.ResourceData, m interface{}) (DisksListResp, error) { + diskList := DisksListResp{} + controller := m.(*ControllerCfg) + urlValues := &url.Values{} + + if page, ok := d.GetOk("page"); ok { + urlValues.Add("page", strconv.Itoa(page.(int))) + } + if size, ok := d.GetOk("size"); ok { + urlValues.Add("size", strconv.Itoa(size.(int))) + } + if diskType, ok := d.GetOk("type"); ok { + urlValues.Add("type", strings.ToUpper(diskType.(string))) + } + if accountId, ok := d.GetOk("accountId"); ok { + urlValues.Add("accountId", strconv.Itoa(accountId.(int))) + } + + log.Debugf("utilityDiskListCheckPresence: load grid list") + diskListRaw, err := controller.decortAPICall("POST", DisksListAPI, urlValues) + if err != nil { + return nil, err + } + + err = json.Unmarshal([]byte(diskListRaw), &diskList) + if err != nil { + return nil, err + } + + return diskList, nil +} diff --git a/samples/README.md b/samples/README.md index 3a20964..d2e8e05 100644 --- a/samples/README.md +++ b/samples/README.md @@ -18,6 +18,7 @@ - sep_pool - sep_consumption - vgpu + - disk_list - resources: - image - virtual_image diff --git a/samples/data_disk_list/main.tf b/samples/data_disk_list/main.tf new file mode 100644 index 0000000..1074f83 --- /dev/null +++ b/samples/data_disk_list/main.tf @@ -0,0 +1,54 @@ +/* +Пример использования +Получение списка доступных дисков +*/ +#Расскомментируйте этот код, +#и внесите необходимые правки в версию и путь, +#чтобы работать с установленным вручную (не через hashicorp provider registry) провайдером +/* +terraform { + required_providers { + decort = { + version = "1.1" + source = "digitalenergy.online/decort/decort" + } + } +} +*/ + + +provider "decort" { + authenticator = "oauth2" + #controller_url = + controller_url = "https://ds1.digitalenergy.online" + #oauth2_url = + oauth2_url = "https://sso.digitalenergy.online" + allow_unverified_ssl = true +} + +data "decort_disk_list" "dl" { + #id аккаунта для получения списка дисков + #опциональный параметр + #тип - число + #account_id = 11111 + + #тип диска + #опциональный параметр + #тип - строка + #возможные типы: "b" - boot_disk, "d" - data_disk + #type = "d" + + #кол-во страниц для вывода + #опицональный параметр + #тип - число + #page = 1 + + #размер страницы + #опицональный параметр + #тип - число + #size = 1 +} + +output "test" { + value = data.decort_disk_list.dl +} From 5e867706c09002ade16c252a9f347bc4c458d9ae Mon Sep 17 00:00:00 2001 From: kjubybot Date: Thu, 19 May 2022 12:33:10 +0300 Subject: [PATCH 05/51] added force parameter to compute resize call --- decort/resource_compute.go | 1 + 1 file changed, 1 insertion(+) diff --git a/decort/resource_compute.go b/decort/resource_compute.go index 0631108..365e621 100644 --- a/decort/resource_compute.go +++ b/decort/resource_compute.go @@ -246,6 +246,7 @@ func resourceComputeUpdate(d *schema.ResourceData, m interface{}) error { log.Debugf("resourceComputeUpdate: changing CPU %d -> %d and/or RAM %d -> %d", oldCpu.(int), newCpu.(int), oldRam.(int), newRam.(int)) + params.Add("force", "true") _, err := controller.decortAPICall("POST", ComputeResizeAPI, params) if err != nil { return err From 8112f328a2882cfb1936610458f2e4c9d615aefe Mon Sep 17 00:00:00 2001 From: kjubybot Date: Thu, 19 May 2022 12:51:51 +0300 Subject: [PATCH 06/51] fixed pfw recreation in case public_port_end was not set --- decort/resource_pfw.go | 1 + 1 file changed, 1 insertion(+) diff --git a/decort/resource_pfw.go b/decort/resource_pfw.go index 3c2cb6e..314bc1a 100644 --- a/decort/resource_pfw.go +++ b/decort/resource_pfw.go @@ -145,6 +145,7 @@ func resourcePfwSchemaMake() map[string]*schema.Schema { "public_port_end": { Type: schema.TypeInt, Optional: true, + Computed: true, ForceNew: true, ValidateFunc: validation.IntBetween(1, 65535), Description: "End port number (inclusive) for the ranged rule.", From 424cdcd2b378475141c078bd480a02a9c570a5d4 Mon Sep 17 00:00:00 2001 From: kjubybot Date: Thu, 19 May 2022 17:29:00 +0300 Subject: [PATCH 07/51] fixed boot disk resize --- decort/resource_compute.go | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/decort/resource_compute.go b/decort/resource_compute.go index 365e621..b61d8b6 100644 --- a/decort/resource_compute.go +++ b/decort/resource_compute.go @@ -263,7 +263,7 @@ func resourceComputeUpdate(d *schema.ResourceData, m interface{}) error { bdsParams.Add("size", fmt.Sprintf("%d", newSize.(int))) log.Debugf("resourceComputeUpdate: compute ID %s, boot disk ID %d resize %d -> %d", d.Id(), d.Get("boot_disk_id").(int), oldSize.(int), newSize.(int)) - _, err := controller.decortAPICall("POST", DisksResizeAPI, params) + _, err := controller.decortAPICall("POST", DisksResizeAPI, bdsParams) if err != nil { return err } From 9a806a8e2c05b64bd932baceb8da0344500f4f72 Mon Sep 17 00:00:00 2001 From: kjubybot Date: Mon, 23 May 2022 12:46:46 +0300 Subject: [PATCH 08/51] made pool and sep_id optional and account_id required --- decort/resource_disk.go | 84 ++++++++++++++++++++++------------------- 1 file changed, 45 insertions(+), 39 deletions(-) diff --git a/decort/resource_disk.go b/decort/resource_disk.go index a19bf08..8cba11f 100644 --- a/decort/resource_disk.go +++ b/decort/resource_disk.go @@ -47,13 +47,19 @@ func resourceDiskCreate(d *schema.ResourceData, m interface{}) error { urlValues.Add("name", d.Get("name").(string)) urlValues.Add("size", fmt.Sprintf("%d", d.Get("size").(int))) urlValues.Add("type", "D") // NOTE: only disks of Data type are managed via plugin - urlValues.Add("sep_id", fmt.Sprintf("%d", d.Get("sep_id").(int))) - urlValues.Add("pool", d.Get("pool").(string)) - + + if sepId, ok := d.GetOk("sep_id"); ok { + urlValues.Add("sep_id", strconv.Itoa(sepId.(int))) + } + + if poolName, ok := d.GetOk("pool"); ok { + urlValues.Add("pool", poolName.(string)) + } + argVal, argSet := d.GetOk("description") if argSet { urlValues.Add("description", argVal.(string)) - } + } apiResp, err := controller.decortAPICall("POST", DisksCreateAPI, urlValues) if err != nil { @@ -65,9 +71,9 @@ func resourceDiskCreate(d *schema.ResourceData, m interface{}) error { log.Debugf("resourceDiskCreate: new Disk ID / name %d / %s creation sequence complete", diskId, d.Get("name").(string)) - // We may reuse dataSourceDiskRead here as we maintain similarity + // We may reuse dataSourceDiskRead here as we maintain similarity // between Disk resource and Disk data source schemas - // Disk resource read function will also update resource ID on success, so that Terraform + // Disk resource read function will also update resource ID on success, so that Terraform // will know the resource exists (however, we already did it a few lines before) return dataSourceDiskRead(d, m) } @@ -100,8 +106,8 @@ func resourceDiskUpdate(d *schema.ResourceData, m interface{}) error { oldSize, newSize := d.GetChange("size") if oldSize.(int) < newSize.(int) { - log.Debugf("resourceDiskUpdate: resizing disk ID %s - %d GB -> %d GB", - d.Id(), oldSize.(int), newSize.(int)) + log.Debugf("resourceDiskUpdate: resizing disk ID %s - %d GB -> %d GB", + d.Id(), oldSize.(int), newSize.(int)) sizeParams := &url.Values{} sizeParams.Add("diskId", d.Id()) sizeParams.Add("size", fmt.Sprintf("%d", newSize.(int))) @@ -116,8 +122,8 @@ func resourceDiskUpdate(d *schema.ResourceData, m interface{}) error { oldName, newName := d.GetChange("name") if oldName.(string) != newName.(string) { - log.Debugf("resourceDiskUpdate: renaming disk ID %d - %s -> %s", - d.Get("disk_id").(int), oldName.(string), newName.(string)) + log.Debugf("resourceDiskUpdate: renaming disk ID %d - %s -> %s", + d.Get("disk_id").(int), oldName.(string), newName.(string)) renameParams := &url.Values{} renameParams.Add("diskId", d.Id()) renameParams.Add("name", newName.(string)) @@ -129,24 +135,24 @@ func resourceDiskUpdate(d *schema.ResourceData, m interface{}) error { } /* - NOTE: plugin will manage disks of type "Data" only, and type cannot be changed once disk is created + NOTE: plugin will manage disks of type "Data" only, and type cannot be changed once disk is created - oldType, newType := d.GetChange("type") - if oldType.(string) != newType.(string) { - return fmt.Errorf("resourceDiskUpdate: Disk ID %s - changing type of existing disk not allowed", d.Id()) - } + oldType, newType := d.GetChange("type") + if oldType.(string) != newType.(string) { + return fmt.Errorf("resourceDiskUpdate: Disk ID %s - changing type of existing disk not allowed", d.Id()) + } */ d.Partial(false) - // we may reuse dataSourceDiskRead here as we maintain similarity + // we may reuse dataSourceDiskRead here as we maintain similarity // between Compute resource and Compute data source schemas - return dataSourceDiskRead(d, m) + return dataSourceDiskRead(d, m) } func resourceDiskDelete(d *schema.ResourceData, m interface{}) error { - // NOTE: this function tries to detach and destroy target Disk "permanently", so - // there is no way to restore it. + // NOTE: this function tries to detach and destroy target Disk "permanently", so + // there is no way to restore it. // If, however, the disk is attached to a compute, the method will // fail (by failing the underpinning DECORt API call, which is issued with detach=false) log.Debugf("resourceDiskDelete: called for Disk ID / name %d / %s, Account ID %d", @@ -166,8 +172,8 @@ func resourceDiskDelete(d *schema.ResourceData, m interface{}) error { // However, this may change in the future, as TF state management logic may want // to delete disk resource BEFORE it is detached from compute instance, and, while // perfectly OK from data preservation viewpoint, this is breaking expected TF workflow - // in the eyes of an experienced TF user - params.Add("detach", "0") + // in the eyes of an experienced TF user + params.Add("detach", "0") params.Add("permanently", "1") controller := m.(*ControllerCfg) @@ -198,7 +204,7 @@ func resourceDiskSchemaMake() map[string]*schema.Schema { rets := map[string]*schema.Schema{ "name": { Type: schema.TypeString, - Optional: true, + Required: true, Description: "Name of this disk. NOTE: disk names are NOT unique within an account. If disk ID is specified, disk name is ignored.", }, @@ -210,34 +216,34 @@ func resourceDiskSchemaMake() map[string]*schema.Schema { "account_id": { Type: schema.TypeInt, - Optional: true, + Required: true, Description: "ID of the account this disk belongs to.", }, "sep_id": { Type: schema.TypeInt, - Required: true, + Optional: true, + Computed: true, ForceNew: true, - ValidateFunc: validation.IntAtLeast(1), Description: "Storage end-point provider serving this disk. Cannot be changed for existing disk.", }, "pool": { Type: schema.TypeString, - Required: true, + Optional: true, + Computed: true, ForceNew: true, - ValidateFunc: validation.StringIsNotEmpty, Description: "Pool where this disk is located. Cannot be changed for existing disk.", }, "size": { - Type: schema.TypeInt, - Required: true, + Type: schema.TypeInt, + Required: true, ValidateFunc: validation.IntAtLeast(1), - Description: "Size of the disk in GB. Note, that existing disks can only be grown in size.", + Description: "Size of the disk in GB. Note, that existing disks can only be grown in size.", }, - /* We moved "type" attribute to computed attributes section, as plugin manages disks of only + /* We moved "type" attribute to computed attributes section, as plugin manages disks of only one type - "D", e.g. data disks. "type": { Type: schema.TypeString, @@ -256,7 +262,7 @@ func resourceDiskSchemaMake() map[string]*schema.Schema { Description: "Optional user-defined text description of this disk.", }, - // The rest of the attributes are all computed + // The rest of the attributes are all computed "account_name": { Type: schema.TypeString, Computed: true, @@ -282,14 +288,14 @@ func resourceDiskSchemaMake() map[string]*schema.Schema { }, /* - "snapshots": { - Type: schema.TypeList, - Computed: true, - Elem: &schema.Resource { - Schema: snapshotSubresourceSchemaMake(), + "snapshots": { + Type: schema.TypeList, + Computed: true, + Elem: &schema.Resource { + Schema: snapshotSubresourceSchemaMake(), + }, + Description: "List of user-created snapshots for this disk." }, - Description: "List of user-created snapshots for this disk." - }, */ } From 103038c0a38e92f7b57666d4805e660ce3b8463a Mon Sep 17 00:00:00 2001 From: stSolo Date: Mon, 23 May 2022 14:14:30 +0300 Subject: [PATCH 09/51] Add a data source rg_list --- decort/data_source_rg_list.go | 314 ++++++++++++++++++++++++++++++++++ decort/models_api.go | 51 ++++-- decort/provider.go | 1 + decort/utility_rg_list.go | 65 +++++++ samples/README.md | 1 + samples/data_rg_list/main.tf | 49 ++++++ 6 files changed, 463 insertions(+), 18 deletions(-) create mode 100644 decort/data_source_rg_list.go create mode 100644 decort/utility_rg_list.go create mode 100644 samples/data_rg_list/main.tf diff --git a/decort/data_source_rg_list.go b/decort/data_source_rg_list.go new file mode 100644 index 0000000..9220693 --- /dev/null +++ b/decort/data_source_rg_list.go @@ -0,0 +1,314 @@ +/* +Copyright (c) 2019-2021 Digital Energy Cloud Solutions LLC. All Rights Reserved. +Author: Sergey Shubin, , + +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. +*/ + +/* +This file is part of Terraform (by Hashicorp) provider for Digital Energy Cloud Orchestration +Technology platfom. + +Visit https://github.com/rudecs/terraform-provider-decort for full source code package and updates. +*/ + +package decort + +import ( + "github.com/google/uuid" + "github.com/hashicorp/terraform-plugin-sdk/helper/schema" +) + +func flattenRgList(rgl ResgroupListResp) []map[string]interface{} { + res := make([]map[string]interface{}, 0) + for _, rg := range rgl { + temp := map[string]interface{}{ + "account_id": rg.AccountID, + "account_name": rg.AccountName, + "acl": flattenRgAcl(rg.ACLs), + "created_by": rg.CreatedBy, + "created_time": rg.CreatedTime, + "def_net_id": rg.DefaultNetID, + "def_net_type": rg.DefaultNetType, + "deleted_by": rg.DeletedBy, + "deleted_time": rg.DeletedTime, + "desc": rg.Decsription, + "gid": rg.GridID, + "guid": rg.GUID, + "rg_id": rg.ID, + "lock_status": rg.LockStatus, + "milestones": rg.Milestones, + "name": rg.Name, + "register_computes": rg.RegisterComputes, + "resource_limits": flattenRgResourceLimits(rg.ResourceLimits), + "secret": rg.Secret, + "status": rg.Status, + "updated_by": rg.UpdatedBy, + "updated_time": rg.UpdatedTime, + "vins": rg.Vins, + "vms": rg.Computes, + } + res = append(res, temp) + } + return res + +} + +func flattenRgAcl(rgAcls []AccountAclRecord) []map[string]interface{} { + res := make([]map[string]interface{}, 0) + for _, rgAcl := range rgAcls { + temp := map[string]interface{}{ + "explicit": rgAcl.IsExplicit, + "guid": rgAcl.Guid, + "right": rgAcl.Rights, + "status": rgAcl.Status, + "type": rgAcl.Type, + "user_group_id": rgAcl.UgroupID, + } + res = append(res, temp) + } + return res +} + +func flattenRgResourceLimits(rl ResourceLimits) []map[string]interface{} { + res := make([]map[string]interface{}, 0) + temp := map[string]interface{}{ + "cu_c": rl.CUC, + "cu_d": rl.CUD, + "cu_i": rl.CUI, + "cu_m": rl.CUM, + "cu_np": rl.CUNP, + "gpu_units": rl.GpuUnits, + } + res = append(res, temp) + + return res + +} + +func dataSourceRgListRead(d *schema.ResourceData, m interface{}) error { + rgList, err := utilityRgListCheckPresence(d, m) + if err != nil { + return err + } + + id := uuid.New() + d.SetId(id.String()) + d.Set("items", flattenRgList(rgList)) + + return nil +} + +func dataSourceRgListSchemaMake() map[string]*schema.Schema { + res := map[string]*schema.Schema{ + "includedeleted": { + Type: schema.TypeBool, + Optional: true, + Default: false, + Description: "included deleted resource groups", + }, + "page": { + Type: schema.TypeInt, + Optional: true, + Description: "Page number", + }, + "size": { + Type: schema.TypeInt, + Optional: true, + Description: "Page size", + }, + "items": { + Type: schema.TypeList, + Computed: true, + Elem: &schema.Resource{ + Schema: map[string]*schema.Schema{ + "account_id": { + Type: schema.TypeInt, + Computed: true, + }, + "account_name": { + Type: schema.TypeString, + Computed: true, + }, + "acl": { + Type: schema.TypeList, + Computed: true, + Elem: &schema.Resource{ + Schema: map[string]*schema.Schema{ + "explicit": { + Type: schema.TypeBool, + Computed: true, + }, + "guid": { + Type: schema.TypeString, + Computed: true, + }, + "right": { + Type: schema.TypeString, + Computed: true, + }, + "status": { + Type: schema.TypeString, + Computed: true, + }, + "type": { + Type: schema.TypeString, + Computed: true, + }, + "user_group_id": { + Type: schema.TypeString, + Computed: true, + }, + }, + }, + }, + "created_by": { + Type: schema.TypeString, + Computed: true, + }, + "created_time": { + Type: schema.TypeInt, + Computed: true, + }, + "def_net_id": { + Type: schema.TypeInt, + Computed: true, + }, + "def_net_type": { + Type: schema.TypeString, + Computed: true, + }, + "deleted_by": { + Type: schema.TypeString, + Computed: true, + }, + "deleted_time": { + Type: schema.TypeInt, + Computed: true, + }, + "desc": { + Type: schema.TypeString, + Computed: true, + }, + "gid": { + Type: schema.TypeInt, + Computed: true, + }, + "guid": { + Type: schema.TypeInt, + Computed: true, + }, + "rg_id": { + Type: schema.TypeInt, + Computed: true, + }, + "lock_status": { + Type: schema.TypeString, + Computed: true, + }, + "milestones": { + Type: schema.TypeInt, + Computed: true, + }, + "name": { + Type: schema.TypeString, + Computed: true, + }, + "register_computes": { + Type: schema.TypeBool, + Computed: true, + }, + "resource_limits": { + Type: schema.TypeList, + Computed: true, + MaxItems: 1, + Elem: &schema.Resource{ + Schema: map[string]*schema.Schema{ + "cu_c": { + Type: schema.TypeFloat, + Computed: true, + }, + "cu_d": { + Type: schema.TypeFloat, + Computed: true, + }, + "cu_i": { + Type: schema.TypeFloat, + Computed: true, + }, + "cu_m": { + Type: schema.TypeFloat, + Computed: true, + }, + "cu_np": { + Type: schema.TypeFloat, + Computed: true, + }, + "gpu_units": { + Type: schema.TypeFloat, + Computed: true, + }, + }, + }, + }, + "secret": { + Type: schema.TypeString, + Computed: true, + }, + "status": { + Type: schema.TypeString, + Computed: true, + }, + "updated_by": { + Type: schema.TypeString, + Computed: true, + }, + "updated_time": { + Type: schema.TypeInt, + Computed: true, + }, + "vins": { + Type: schema.TypeList, + Computed: true, + Elem: &schema.Schema{ + Type: schema.TypeInt, + }, + }, + "vms": { + Type: schema.TypeList, + Computed: true, + Elem: &schema.Schema{ + Type: schema.TypeInt, + }, + }, + }, + }, + }, + } + return res +} + +func dataSourceRgList() *schema.Resource { + return &schema.Resource{ + SchemaVersion: 1, + + Read: dataSourceRgListRead, + + Timeouts: &schema.ResourceTimeout{ + Read: &Timeout30s, + Default: &Timeout60s, + }, + + Schema: dataSourceRgListSchemaMake(), + } +} diff --git a/decort/models_api.go b/decort/models_api.go index 034cb17..b3e6f86 100644 --- a/decort/models_api.go +++ b/decort/models_api.go @@ -59,25 +59,40 @@ type AccountAclRecord struct { UgroupID string `json:"userGroupId"` } +type ResourceLimits struct { + CUC float64 `json:"CU_C"` + CUD float64 `json:"CU_D"` + CUI float64 `json:"CU_I"` + CUM float64 `json:"CU_M"` + CUNP float64 `json:"CU_NP"` + GpuUnits float64 `json:"gpu_units"` +} + type ResgroupRecord struct { - ACLs []UserAclRecord `json:"acl"` - Owner AccountAclRecord `json:"accountAcl"` - AccountID int `json:"accountId"` - AccountName string `json:"accountName"` - CreatedBy string `json:"createdBy"` - CreatedTime uint64 `json:"createdTime"` - DefaultNetID int `json:"def_net_id"` - DefaultNetType string `json:"def_net_type"` - Decsription string `json:"desc"` - GridID int `json:"gid"` - ID uint `json:"id"` - LockStatus string `json:"lockStatus"` - Name string `json:"name"` - Status string `json:"status"` - UpdatedBy string `json:"updatedBy"` - UpdatedTime uint64 `json:"updatedTime"` - Vins []int `json:"vins"` - Computes []int `json:"vms"` + ACLs []AccountAclRecord `json:"acl"` + AccountID int `json:"accountId"` + AccountName string `json:"accountName"` + CreatedBy string `json:"createdBy"` + CreatedTime uint64 `json:"createdTime"` + DefaultNetID int `json:"def_net_id"` + DefaultNetType string `json:"def_net_type"` + DeletedBy string `json:"deletedBy"` + DeletedTime int `json:"deletedTime"` + Decsription string `json:"desc"` + GridID int `json:"gid"` + GUID int `json:"guid"` + ID uint `json:"id"` + LockStatus string `json:"lockStatus"` + Milestones int `json:"milestones"` + Name string `json:"name"` + RegisterComputes bool `json:"registerComputes"` + ResourceLimits ResourceLimits `json:"resourceLimits"` + Secret string `json:"secret"` + Status string `json:"status"` + UpdatedBy string `json:"updatedBy"` + UpdatedTime uint64 `json:"updatedTime"` + Vins []int `json:"vins"` + Computes []int `json:"vms"` } const ResgroupListAPI = "/restmachine/cloudapi/rg/list" diff --git a/decort/provider.go b/decort/provider.go index 2d9e3a9..00af955 100644 --- a/decort/provider.go +++ b/decort/provider.go @@ -138,6 +138,7 @@ func Provider() *schema.Provider { "decort_sep_config": dataSourceSepConfig(), "decort_sep_pool": dataSourceSepPool(), "decort_disk_list": dataSourceDiskList(), + "decort_rg_list": dataSourceRgList(), // "decort_pfw": dataSourcePfw(), }, diff --git a/decort/utility_rg_list.go b/decort/utility_rg_list.go new file mode 100644 index 0000000..78892f3 --- /dev/null +++ b/decort/utility_rg_list.go @@ -0,0 +1,65 @@ +/* +Copyright (c) 2019-2022 Digital Energy Cloud Solutions LLC. All Rights Reserved. +Author: Stanislav Solovev, , + +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. +*/ + +/* +This file is part of Terraform (by Hashicorp) provider for Digital Energy Cloud Orchestration +Technology platfom. + +Visit https://github.com/rudecs/terraform-provider-decort for full source code package and updates. +*/ + +package decort + +import ( + "encoding/json" + "net/url" + "strconv" + + log "github.com/sirupsen/logrus" + + "github.com/hashicorp/terraform-plugin-sdk/helper/schema" +) + +func utilityRgListCheckPresence(d *schema.ResourceData, m interface{}) (ResgroupListResp, error) { + controller := m.(*ControllerCfg) + urlValues := &url.Values{} + + rgList := ResgroupListResp{} + + if size, ok := d.GetOk("size"); ok { + urlValues.Add("size", strconv.Itoa(size.(int))) + } + if page, ok := d.GetOk("page"); ok { + urlValues.Add("page", strconv.Itoa(page.(int))) + } + if includedeleted, ok := d.GetOk("includedeleted"); ok { + urlValues.Add("includedeleted", strconv.FormatBool(includedeleted.(bool))) + } + + log.Debugf("utilityRgListCheckPresence: load rg list") + rgListRaw, err := controller.decortAPICall("POST", ResgroupListAPI, urlValues) + if err != nil { + return nil, err + } + + err = json.Unmarshal([]byte(rgListRaw), &rgList) + if err != nil { + return nil, err + } + + return rgList, nil +} diff --git a/samples/README.md b/samples/README.md index d2e8e05..6761a86 100644 --- a/samples/README.md +++ b/samples/README.md @@ -19,6 +19,7 @@ - sep_consumption - vgpu - disk_list + - rg_list - resources: - image - virtual_image diff --git a/samples/data_rg_list/main.tf b/samples/data_rg_list/main.tf new file mode 100644 index 0000000..4b92e76 --- /dev/null +++ b/samples/data_rg_list/main.tf @@ -0,0 +1,49 @@ +/* +Пример использования +Получение списка всех resource groups + +*/ +#Расскомментируйте этот код, +#и внесите необходимые правки в версию и путь, +#чтобы работать с установленным вручную (не через hashicorp provider registry) провайдером +/* +terraform { + required_providers { + decort = { + version = "1.1" + source = "digitalenergy.online/decort/decort" + } + } +} +*/ +provider "decort" { + authenticator = "oauth2" + #controller_url = + controller_url = "https://ds1.digitalenergy.online" + #oauth2_url = + oauth2_url = "https://sso.digitalenergy.online" + allow_unverified_ssl = true +} + +data "decort_rg_list" "rl" { + #включение удаленных rg в результат поиска + #опциональный параметр + #тип - булев тип + #по-умолчанию - false + #includedeleted = true + + #номер страницы для отображения + #опциональный параметр, тип - число + #если не задан - выводятся все доступные данные + #page = 2 + + #размер страницы + #опциональный параметр, тип - число + #если не задан - выводятся все доступные данные + #size = 3 + +} + +output "test" { + value = data.decort_rg_list.rl +} From c5e35b19f9c036db02def99e0f93445bbbb4b533 Mon Sep 17 00:00:00 2001 From: stSolo Date: Mon, 23 May 2022 19:19:48 +0300 Subject: [PATCH 10/51] Add data source function for account list --- decort/data_source_account_list.go | 266 +++++++++++++++++++++++++++++ decort/models_api.go | 83 +++++++++ decort/provider.go | 1 + decort/utility_account_list.go | 61 +++++++ samples/README.md | 1 + samples/data_account_list/main.tf | 45 +++++ 6 files changed, 457 insertions(+) create mode 100644 decort/data_source_account_list.go create mode 100644 decort/utility_account_list.go create mode 100644 samples/data_account_list/main.tf diff --git a/decort/data_source_account_list.go b/decort/data_source_account_list.go new file mode 100644 index 0000000..c6f6919 --- /dev/null +++ b/decort/data_source_account_list.go @@ -0,0 +1,266 @@ +/* +Copyright (c) 2019-2021 Digital Energy Cloud Solutions LLC. All Rights Reserved. +Author: Sergey Shubin, , + +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. +*/ + +/* +This file is part of Terraform (by Hashicorp) provider for Digital Energy Cloud Orchestration +Technology platfom. + +Visit https://github.com/rudecs/terraform-provider-decort for full source code package and updates. +*/ + +package decort + +import ( + "github.com/google/uuid" + "github.com/hashicorp/terraform-plugin-sdk/helper/schema" +) + +func flattenAccountList(al AccountList) []map[string]interface{} { + res := make([]map[string]interface{}, 0) + for _, acc := range al { + temp := map[string]interface{}{ + "dc_location": acc.DCLocation, + "ckey": acc.CKey, + "meta": flattenMeta(acc.Meta), + "acl": flattenRgAcl(acc.Acl), + "company": acc.Company, + "companyurl": acc.CompanyUrl, + "created_by": acc.CreatedBy, + "created_time": acc.CreatedTime, + "deactivation_time": acc.DeactiovationTime, + "deleted_by": acc.DeletedBy, + "deleted_time": acc.DeletedTime, + "displayname": acc.DisplayName, + "guid": acc.GUID, + "account_id": acc.ID, + "account_name": acc.Name, + "resource_limits": flattenRgResourceLimits(acc.ResourceLimits), + "send_access_emails": acc.SendAccessEmails, + "service_account": acc.ServiceAccount, + "status": acc.Status, + "updated_time": acc.UpdatedTime, + "version": acc.Version, + "vins": acc.Vins, + } + res = append(res, temp) + } + return res + +} + +func dataSourceAccountListRead(d *schema.ResourceData, m interface{}) error { + accountList, err := utilityAccountListCheckPresence(d, m) + if err != nil { + return err + } + + id := uuid.New() + d.SetId(id.String()) + d.Set("items", flattenAccountList(accountList)) + + return nil +} + +func dataSourceAccountListSchemaMake() map[string]*schema.Schema { + res := map[string]*schema.Schema{ + "page": { + Type: schema.TypeInt, + Optional: true, + Description: "Page number", + }, + "size": { + Type: schema.TypeInt, + Optional: true, + Description: "Page size", + }, + "items": { + Type: schema.TypeList, + Computed: true, + Elem: &schema.Resource{ + Schema: map[string]*schema.Schema{ + "dc_location": { + Type: schema.TypeString, + Computed: true, + }, + "ckey": { + Type: schema.TypeString, + Computed: true, + }, + "meta": { + Type: schema.TypeList, + Computed: true, + Elem: &schema.Schema{ + Type: schema.TypeString, + }, + }, + "acl": { + Type: schema.TypeList, + Computed: true, + Elem: &schema.Resource{ + Schema: map[string]*schema.Schema{ + "explicit": { + Type: schema.TypeBool, + Computed: true, + }, + "guid": { + Type: schema.TypeString, + Computed: true, + }, + "right": { + Type: schema.TypeString, + Computed: true, + }, + "status": { + Type: schema.TypeString, + Computed: true, + }, + "type": { + Type: schema.TypeString, + Computed: true, + }, + "user_group_id": { + Type: schema.TypeString, + Computed: true, + }, + }, + }, + }, + "company": { + Type: schema.TypeString, + Computed: true, + }, + "companyurl": { + Type: schema.TypeString, + Computed: true, + }, + "created_by": { + Type: schema.TypeString, + Computed: true, + }, + "created_time": { + Type: schema.TypeInt, + Computed: true, + }, + "deactivation_time": { + Type: schema.TypeFloat, + Computed: true, + }, + "deleted_by": { + Type: schema.TypeString, + Computed: true, + }, + "deleted_time": { + Type: schema.TypeInt, + Computed: true, + }, + "displayname": { + Type: schema.TypeString, + Computed: true, + }, + "guid": { + Type: schema.TypeInt, + Computed: true, + }, + "account_id": { + Type: schema.TypeInt, + Computed: true, + }, + "account_name": { + Type: schema.TypeString, + Computed: true, + }, + "resource_limits": { + Type: schema.TypeList, + Computed: true, + MaxItems: 1, + Elem: &schema.Resource{ + Schema: map[string]*schema.Schema{ + "cu_c": { + Type: schema.TypeFloat, + Computed: true, + }, + "cu_d": { + Type: schema.TypeFloat, + Computed: true, + }, + "cu_i": { + Type: schema.TypeFloat, + Computed: true, + }, + "cu_m": { + Type: schema.TypeFloat, + Computed: true, + }, + "cu_np": { + Type: schema.TypeFloat, + Computed: true, + }, + "gpu_units": { + Type: schema.TypeFloat, + Computed: true, + }, + }, + }, + }, + "send_access_emails": { + Type: schema.TypeBool, + Computed: true, + }, + "service_account": { + Type: schema.TypeBool, + Computed: true, + }, + "status": { + Type: schema.TypeString, + Computed: true, + }, + "updated_time": { + Type: schema.TypeInt, + Computed: true, + }, + "version": { + Type: schema.TypeInt, + Computed: true, + }, + "vins": { + Type: schema.TypeList, + Computed: true, + Elem: &schema.Schema{ + Type: schema.TypeInt, + }, + }, + }, + }, + }, + } + return res +} + +func dataSourceAccountList() *schema.Resource { + return &schema.Resource{ + SchemaVersion: 1, + + Read: dataSourceAccountListRead, + + Timeouts: &schema.ResourceTimeout{ + Read: &Timeout30s, + Default: &Timeout60s, + }, + + Schema: dataSourceAccountListSchemaMake(), + } +} diff --git a/decort/models_api.go b/decort/models_api.go index b3e6f86..ea9dff4 100644 --- a/decort/models_api.go +++ b/decort/models_api.go @@ -987,3 +987,86 @@ type SepConfig map[string]interface{} type SepList []Sep type SepPool map[string]interface{} + +/////////////////////// +///// ACCOUNTS //// +/////////////////////// + +const accountAddUserAPI = "/cloudapi/account/addUser" +const accountAuditsAPI = "/cloudapi/account/audits" +const accountCreateAPI = "/cloudapi/account/create" +const accountDeleteAPI = "/cloudapi/account/delete" +const accountDeleteAccountsAPI = "/cloudapi/account/deleteAccounts" +const accountDeleteUserAPI = "/cloudapi/account/deleteUser" +const accountDisableAPI = "/cloudapi/account/disable" +const accountEnableAPI = "/cloudapi/account/enable" +const accountGetAPI = "/cloudapi/account/get" +const accountGetConsumedAccountUnitsAPI = "/cloudapi/account/getConsumedAccountUnits" +const accountGetConsumedCloudUnitsByTypeAPI = "/cloudapi/account/getConsumedCloudUnitsByType" +const accountGetConsumptionGetAPI = "/cloudapi/account/getConsumption" +const accountGetConsumptionPostAPI = "/cloudapi/account/getConsumption" +const accountGetReservedAccountUnitsAPI = "/cloudapi/account/getReservedAccountUnits" +const accountGetStatsAPI = "/cloudapi/account/getStats" + +//const accountListAPI = "/cloudapi/account/list" +const accountListAPI = "/restmachine/cloudbroker/account/list" +const accountListComputesAPI = "/cloudapi/account/listComputes" +const accountListCSAPI = "/cloudapi/account/listCS" +const accountListDeletedAPI = "/cloudapi/account/listDeleted" +const accountListDisksAPI = "/cloudapi/account/listDisks" +const accountListFlipGroupsAPI = "/cloudapi/account/listFlipGroups" +const accountListRGAPI = "/cloudapi/account/listRG" +const accountListTemplatesAPI = "/cloudapi/account/listTemplates" +const accountListVinsAPI = "/cloudapi/account/listVins" +const accountListVMsAPI = "/cloudapi/account/listVMs" +const accountRestoreAPI = "/cloudapi/account/restore" +const accountUpdateAPI = "/cloudapi/account/update" +const accountUpdateUserAPI = "/cloudapi/account/updateUser" + +////Structs + +type Account struct { + DCLocation string `json:"DCLocation"` + CKey string `jspn:"_ckey"` + Meta []interface{} `json:"_meta"` + Acl []AccountAclRecord `json:"acl"` + Company string `json:"company"` + CompanyUrl string `json:"companyurl"` + CreatedBy string `jspn:"createdBy"` + CreatedTime int `json:"createdTime"` + DeactiovationTime float64 `json:"deactivationTime"` + DeletedBy string `json:"deletedBy"` + DeletedTime int `json:"deletedTime"` + DisplayName string `json:"displayname"` + GUID int `json:"guid"` + ID int `json:"id"` + Name string `json:"name"` + ResourceLimits ResourceLimits `json:"resourceLimits"` + SendAccessEmails bool `json:"sendAccessEmails"` + ServiceAccount bool `json:"serviceAccount"` + Status string `json:"status"` + UpdatedTime int `json:"updatedTime"` + Version int `json:"version"` + Vins []int `json:"vins"` +} + +type AccountList []Account + +type Resource struct { + CPU int `json:"cpu"` + Disksize int `json:"disksize"` + Extips int `json:"extips"` + Exttraffic int `json:"exttraffic"` + GPU int `json:"gpu"` + RAM int `json:"ram"` +} + +type Resources struct { + Current Resource `json:"Current"` + Reserved Resource `json:"Reserved"` +} + +type AccountWithResources struct { + Account + Resources Resources `json:"Resources"` +} diff --git a/decort/provider.go b/decort/provider.go index 00af955..7c7887e 100644 --- a/decort/provider.go +++ b/decort/provider.go @@ -139,6 +139,7 @@ func Provider() *schema.Provider { "decort_sep_pool": dataSourceSepPool(), "decort_disk_list": dataSourceDiskList(), "decort_rg_list": dataSourceRgList(), + "decort_account_list": dataSourceAccountList(), // "decort_pfw": dataSourcePfw(), }, diff --git a/decort/utility_account_list.go b/decort/utility_account_list.go new file mode 100644 index 0000000..828ecf9 --- /dev/null +++ b/decort/utility_account_list.go @@ -0,0 +1,61 @@ +/* +Copyright (c) 2019-2022 Digital Energy Cloud Solutions LLC. All Rights Reserved. +Author: Stanislav Solovev, , + +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. +*/ + +/* +This file is part of Terraform (by Hashicorp) provider for Digital Energy Cloud Orchestration +Technology platfom. + +Visit https://github.com/rudecs/terraform-provider-decort for full source code package and updates. +*/ + +package decort + +import ( + "encoding/json" + "net/url" + "strconv" + + log "github.com/sirupsen/logrus" + + "github.com/hashicorp/terraform-plugin-sdk/helper/schema" +) + +func utilityAccountListCheckPresence(d *schema.ResourceData, m interface{}) (AccountList, error) { + accountList := AccountList{} + controller := m.(*ControllerCfg) + urlValues := &url.Values{} + + if page, ok := d.GetOk("page"); ok { + urlValues.Add("page", strconv.Itoa(page.(int))) + } + if size, ok := d.GetOk("size"); ok { + urlValues.Add("size", strconv.Itoa(size.(int))) + } + + log.Debugf("utilityAccountListCheckPresence: load account list") + accountListRaw, err := controller.decortAPICall("POST", accountListAPI, urlValues) + if err != nil { + return nil, err + } + + err = json.Unmarshal([]byte(accountListRaw), &accountList) + if err != nil { + return nil, err + } + + return accountList, nil +} diff --git a/samples/README.md b/samples/README.md index 6761a86..c4ff93c 100644 --- a/samples/README.md +++ b/samples/README.md @@ -20,6 +20,7 @@ - vgpu - disk_list - rg_list + - account_list - resources: - image - virtual_image diff --git a/samples/data_account_list/main.tf b/samples/data_account_list/main.tf new file mode 100644 index 0000000..722077a --- /dev/null +++ b/samples/data_account_list/main.tf @@ -0,0 +1,45 @@ +/* +Пример использования +Получение списка доступных аккаунтов + +*/ +#Расскомментируйте этот код, +#и внесите необходимые правки в версию и путь, +#чтобы работать с установленным вручную (не через hashicorp provider registry) провайдером +/* +terraform { + required_providers { + decort = { + version = "1.1" + source = "digitalenergy.online/decort/decort" + } + } +} +*/ + +provider "decort" { + authenticator = "oauth2" + #controller_url = + controller_url = "https://ds1.digitalenergy.online" + #oauth2_url = + oauth2_url = "https://sso.digitalenergy.online" + allow_unverified_ssl = true +} + +data "decort_account_list" "al" { + #номер страницы для отображения + #опциональный параметр + #тип - число + #если не задан - выводятся все доступные данные + #page = 2 + + #размер страницы + #опциональный параметр + #тип - число + #если не задан - выводятся все доступные данные + #size = 3 +} + +output "test" { + value = data.decort_account_list.al +} From fa748f6e5dec7cc1f743d75e0150cfa77f480868 Mon Sep 17 00:00:00 2001 From: stSolo Date: Tue, 24 May 2022 14:02:03 +0300 Subject: [PATCH 11/51] Add account computes list --- decort/data_source_account_computes_list.go | 189 ++++++++++++++++++++ decort/models_api.go | 31 +++- decort/provider.go | 47 ++--- decort/utility_account.go | 4 +- decort/utility_accout_computes_list.go | 56 ++++++ samples/account_computes_list/main.tf | 39 ++++ 6 files changed, 339 insertions(+), 27 deletions(-) create mode 100644 decort/data_source_account_computes_list.go create mode 100644 decort/utility_accout_computes_list.go create mode 100644 samples/account_computes_list/main.tf diff --git a/decort/data_source_account_computes_list.go b/decort/data_source_account_computes_list.go new file mode 100644 index 0000000..b4b99ad --- /dev/null +++ b/decort/data_source_account_computes_list.go @@ -0,0 +1,189 @@ +/* +Copyright (c) 2019-2021 Digital Energy Cloud Solutions LLC. All Rights Reserved. +Author: Sergey Shubin, , + +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. +*/ + +/* +This file is part of Terraform (by Hashicorp) provider for Digital Energy Cloud Orchestration +Technology platfom. + +Visit https://github.com/rudecs/terraform-provider-decort for full source code package and updates. +*/ + +package decort + +import ( + "github.com/google/uuid" + "github.com/hashicorp/terraform-plugin-sdk/helper/schema" +) + +func flattenAccountComputesList(acl AccountComputesList) []map[string]interface{} { + res := make([]map[string]interface{}, 0) + for _, acc := range acl { + temp := map[string]interface{}{ + "account_id": acc.AccountId, + "account_name": acc.AccountName, + "cpus": acc.CPUs, + "created_by": acc.CreatedBy, + "created_time": acc.CreatedTime, + "deleted_by": acc.DeletedBy, + "deleted_time": acc.DeletedTime, + "compute_id": acc.ComputeId, + "compute_name": acc.ComputeName, + "ram": acc.RAM, + "registered": acc.Registered, + "rg_id": acc.RgId, + "rg_name": acc.RgName, + "status": acc.Status, + "tech_status": acc.TechStatus, + "total_disks_size": acc.TotalDisksSize, + "updated_by": acc.UpdatedBy, + "updated_time": acc.UpdatedTime, + "user_managed": acc.UserManaged, + "vins_connected": acc.VinsConnected, + } + res = append(res, temp) + } + return res + +} + +func dataSourceAccountComputesListRead(d *schema.ResourceData, m interface{}) error { + accountComputesList, err := utilityAccountComputesListCheckPresence(d, m) + if err != nil { + return err + } + + id := uuid.New() + d.SetId(id.String()) + d.Set("items", flattenAccountComputesList(accountComputesList)) + + return nil +} + +func dataSourceAccountComputesListSchemaMake() map[string]*schema.Schema { + res := map[string]*schema.Schema{ + "account_id": { + Type: schema.TypeInt, + Required: true, + Description: "ID of the account", + }, + "items": { + Type: schema.TypeList, + Computed: true, + Description: "Search Result", + Elem: &schema.Resource{ + Schema: map[string]*schema.Schema{ + "account_id": { + Type: schema.TypeInt, + Computed: true, + }, + "account_name": { + Type: schema.TypeString, + Computed: true, + }, + "cpus": { + Type: schema.TypeInt, + Computed: true, + }, + "created_by": { + Type: schema.TypeString, + Computed: true, + }, + "created_time": { + Type: schema.TypeInt, + Computed: true, + }, + "deleted_by": { + Type: schema.TypeString, + Computed: true, + }, + "deleted_time": { + Type: schema.TypeInt, + Computed: true, + }, + "compute_id": { + Type: schema.TypeInt, + Computed: true, + }, + "compute_name": { + Type: schema.TypeString, + Computed: true, + }, + "ram": { + Type: schema.TypeInt, + Computed: true, + }, + "registered": { + Type: schema.TypeBool, + Computed: true, + }, + "rg_id": { + Type: schema.TypeInt, + Computed: true, + }, + "rg_name": { + Type: schema.TypeString, + Computed: true, + }, + "status": { + Type: schema.TypeString, + Computed: true, + }, + "tech_status": { + Type: schema.TypeString, + Computed: true, + }, + "total_disks_size": { + Type: schema.TypeInt, + Computed: true, + }, + "updated_by": { + Type: schema.TypeString, + Computed: true, + }, + "updated_time": { + Type: schema.TypeInt, + Computed: true, + }, + "user_managed": { + Type: schema.TypeBool, + Computed: true, + }, + "vins_connected": { + Type: schema.TypeInt, + Computed: true, + }, + }, + }, + }, + } + return res +} + +func dataSourceAccountComputesList() *schema.Resource { + return &schema.Resource{ + SchemaVersion: 1, + + Read: dataSourceAccountComputesListRead, + + Timeouts: &schema.ResourceTimeout{ + Read: &Timeout30s, + Default: &Timeout60s, + }, + + Schema: dataSourceAccountComputesListSchemaMake(), + } +} diff --git a/decort/models_api.go b/decort/models_api.go index ea9dff4..e02ed2c 100644 --- a/decort/models_api.go +++ b/decort/models_api.go @@ -1008,9 +1008,11 @@ const accountGetConsumptionPostAPI = "/cloudapi/account/getConsumption" const accountGetReservedAccountUnitsAPI = "/cloudapi/account/getReservedAccountUnits" const accountGetStatsAPI = "/cloudapi/account/getStats" -//const accountListAPI = "/cloudapi/account/list" +//const accountListAPI = "/restmachine/cloudapi/account/list" const accountListAPI = "/restmachine/cloudbroker/account/list" -const accountListComputesAPI = "/cloudapi/account/listComputes" + +//const accountListComputesAPI = "/restmachine/cloudapi/account/listComputes" +const accountListComputesAPI = "/restmachine/cloudbroker/account/listComputes" const accountListCSAPI = "/cloudapi/account/listCS" const accountListDeletedAPI = "/cloudapi/account/listDeleted" const accountListDisksAPI = "/cloudapi/account/listDisks" @@ -1070,3 +1072,28 @@ type AccountWithResources struct { Account Resources Resources `json:"Resources"` } + +type AccountCompute struct { + AccountId int `json:"accountId"` + AccountName string `json:"accountName"` + CPUs int `json:"cpus"` + CreatedBy string `json:"createdBy"` + CreatedTime int `json:"createdTime"` + DeletedBy string `json:"deletedBy"` + DeletedTime int `json:"deletedTime"` + ComputeId int `json:"id"` + ComputeName string `json:"name"` + RAM int `json:"ram"` + Registered bool `json:"registered"` + RgId int `json:"rgId"` + RgName string `json:"rgName"` + Status string `json:"status"` + TechStatus string `json:"techStatus"` + TotalDisksSize int `json:"totalDisksSize"` + UpdatedBy string `json:"updatedBy"` + UpdatedTime int `json:"updatedTime"` + UserManaged bool `json:"userManaged"` + VinsConnected int `json:"vinsConnected"` +} + +type AccountComputesList []AccountCompute diff --git a/decort/provider.go b/decort/provider.go index 7c7887e..c2a5fa5 100644 --- a/decort/provider.go +++ b/decort/provider.go @@ -117,29 +117,30 @@ func Provider() *schema.Provider { }, DataSourcesMap: map[string]*schema.Resource{ - "decort_account": dataSourceAccount(), - "decort_resgroup": dataSourceResgroup(), - "decort_kvmvm": dataSourceCompute(), - "decort_image": dataSourceImage(), - "decort_disk": dataSourceDisk(), - "decort_vins": dataSourceVins(), - "decort_grid": dataSourceGrid(), - "decort_grid_list": dataSourceGridList(), - "decort_image_list": dataSourceImageList(), - "decort_image_list_stacks": dataSourceImageListStacks(), - "decort_snapshot_list": dataSourceSnapshotList(), - "decort_vgpu": dataSourceVGPU(), - "decort_pcidevice": dataSourcePcidevice(), - "decort_pcidevice_list": dataSourcePcideviceList(), - "decort_sep_list": dataSourceSepList(), - "decort_sep": dataSourceSep(), - "decort_sep_consumption": dataSourceSepConsumption(), - "decort_sep_disk_list": dataSourceSepDiskList(), - "decort_sep_config": dataSourceSepConfig(), - "decort_sep_pool": dataSourceSepPool(), - "decort_disk_list": dataSourceDiskList(), - "decort_rg_list": dataSourceRgList(), - "decort_account_list": dataSourceAccountList(), + "decort_account": dataSourceAccount(), + "decort_resgroup": dataSourceResgroup(), + "decort_kvmvm": dataSourceCompute(), + "decort_image": dataSourceImage(), + "decort_disk": dataSourceDisk(), + "decort_vins": dataSourceVins(), + "decort_grid": dataSourceGrid(), + "decort_grid_list": dataSourceGridList(), + "decort_image_list": dataSourceImageList(), + "decort_image_list_stacks": dataSourceImageListStacks(), + "decort_snapshot_list": dataSourceSnapshotList(), + "decort_vgpu": dataSourceVGPU(), + "decort_pcidevice": dataSourcePcidevice(), + "decort_pcidevice_list": dataSourcePcideviceList(), + "decort_sep_list": dataSourceSepList(), + "decort_sep": dataSourceSep(), + "decort_sep_consumption": dataSourceSepConsumption(), + "decort_sep_disk_list": dataSourceSepDiskList(), + "decort_sep_config": dataSourceSepConfig(), + "decort_sep_pool": dataSourceSepPool(), + "decort_disk_list": dataSourceDiskList(), + "decort_rg_list": dataSourceRgList(), + "decort_account_list": dataSourceAccountList(), + "decort_account_computes_list": dataSourceAccountComputesList(), // "decort_pfw": dataSourcePfw(), }, diff --git a/decort/utility_account.go b/decort/utility_account.go index f1eaf34..c9a6def 100644 --- a/decort/utility_account.go +++ b/decort/utility_account.go @@ -110,8 +110,8 @@ func utilityGetAccountIdBySchema(d *schema.ResourceData, m interface{}) (int, er initiate API calls to the DECORT cloud controller and try to match relevant account by the name. - NOTE that for some resources (most notably, Resource Group) "account_name" attribute is - marked as "Computed: true", so the only way to fully identify Resource Group is to specify + NOTE that for some resources (most notably, Resource Group) "account_name" attribute is + marked as "Computed: true", so the only way to fully identify Resource Group is to specify "account_id", which is marked as "Required: true" */ diff --git a/decort/utility_accout_computes_list.go b/decort/utility_accout_computes_list.go new file mode 100644 index 0000000..6c92590 --- /dev/null +++ b/decort/utility_accout_computes_list.go @@ -0,0 +1,56 @@ +/* +Copyright (c) 2019-2022 Digital Energy Cloud Solutions LLC. All Rights Reserved. +Author: Stanislav Solovev, , + +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. +*/ + +/* +This file is part of Terraform (by Hashicorp) provider for Digital Energy Cloud Orchestration +Technology platfom. + +Visit https://github.com/rudecs/terraform-provider-decort for full source code package and updates. +*/ + +package decort + +import ( + "encoding/json" + "net/url" + "strconv" + + log "github.com/sirupsen/logrus" + + "github.com/hashicorp/terraform-plugin-sdk/helper/schema" +) + +func utilityAccountComputesListCheckPresence(d *schema.ResourceData, m interface{}) (AccountComputesList, error) { + accountComputesList := AccountComputesList{} + controller := m.(*ControllerCfg) + urlValues := &url.Values{} + + urlValues.Add("accountId", strconv.Itoa(d.Get("account_id").(int))) + + log.Debugf("utilityAccountComputesListCheckPresence: load account list") + accountComputesListRaw, err := controller.decortAPICall("POST", accountListComputesAPI, urlValues) + if err != nil { + return nil, err + } + + err = json.Unmarshal([]byte(accountComputesListRaw), &accountComputesList) + if err != nil { + return nil, err + } + + return accountComputesList, nil +} diff --git a/samples/account_computes_list/main.tf b/samples/account_computes_list/main.tf new file mode 100644 index 0000000..26edae2 --- /dev/null +++ b/samples/account_computes_list/main.tf @@ -0,0 +1,39 @@ +/* +Пример использования +Получение списка computes, используемых аккаунтом + +*/ +#Расскомментируйте этот код, +#и внесите необходимые правки в версию и путь, +#чтобы работать с установленным вручную (не через hashicorp provider registry) провайдером +/* +terraform { + required_providers { + decort = { + version = "1.1" + source = "digitalenergy.online/decort/decort" + } + } +} +*/ + +provider "decort" { + authenticator = "oauth2" + #controller_url = + controller_url = "https://ds1.digitalenergy.online" + #oauth2_url = + oauth2_url = "https://sso.digitalenergy.online" + allow_unverified_ssl = true +} + +data "decort_account_computes_list" "acl" { + #id аккаунта + #обязательный параметр + #тип - число + account_id = 1111 + +} + +output "test" { + value = data.decort_account_computes_list.acl +} From 5e515daafacd6b932bc39b7b5fab91f122e10068 Mon Sep 17 00:00:00 2001 From: stSolo Date: Tue, 24 May 2022 17:23:29 +0300 Subject: [PATCH 12/51] Add a account disks list --- decort/data_source_account_disks_list.go | 119 ++++++++++++++++++ decort/models_api.go | 15 ++- decort/provider.go | 1 + ...st.go => utility_account_computes_list.go} | 0 decort/utility_account_disks_list.go | 56 +++++++++ samples/account_disks_list/main.tf | 39 ++++++ 6 files changed, 229 insertions(+), 1 deletion(-) create mode 100644 decort/data_source_account_disks_list.go rename decort/{utility_accout_computes_list.go => utility_account_computes_list.go} (100%) create mode 100644 decort/utility_account_disks_list.go create mode 100644 samples/account_disks_list/main.tf diff --git a/decort/data_source_account_disks_list.go b/decort/data_source_account_disks_list.go new file mode 100644 index 0000000..489f8eb --- /dev/null +++ b/decort/data_source_account_disks_list.go @@ -0,0 +1,119 @@ +/* +Copyright (c) 2019-2021 Digital Energy Cloud Solutions LLC. All Rights Reserved. +Author: Sergey Shubin, , + +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. +*/ + +/* +This file is part of Terraform (by Hashicorp) provider for Digital Energy Cloud Orchestration +Technology platfom. + +Visit https://github.com/rudecs/terraform-provider-decort for full source code package and updates. +*/ + +package decort + +import ( + "github.com/google/uuid" + "github.com/hashicorp/terraform-plugin-sdk/helper/schema" +) + +func flattenAccountDisksList(adl AccountDisksList) []map[string]interface{} { + res := make([]map[string]interface{}, 0) + for _, acc := range adl { + temp := map[string]interface{}{ + "disk_id": acc.ID, + "disk_name": acc.Name, + "pool": acc.Pool, + "sep_id": acc.SepId, + "size_max": acc.SizeMax, + "type": acc.Type, + } + res = append(res, temp) + } + return res + +} + +func dataSourceAccountDiskssListRead(d *schema.ResourceData, m interface{}) error { + accountDisksList, err := utilityAccountDisksListCheckPresence(d, m) + if err != nil { + return err + } + + id := uuid.New() + d.SetId(id.String()) + d.Set("items", flattenAccountDisksList(accountDisksList)) + + return nil +} + +func dataSourceAccountDisksListSchemaMake() map[string]*schema.Schema { + res := map[string]*schema.Schema{ + "account_id": { + Type: schema.TypeInt, + Required: true, + Description: "ID of the account", + }, + "items": { + Type: schema.TypeList, + Computed: true, + Description: "Search Result", + Elem: &schema.Resource{ + Schema: map[string]*schema.Schema{ + "disk_id": { + Type: schema.TypeInt, + Computed: true, + }, + "disk_name": { + Type: schema.TypeString, + Computed: true, + }, + "pool": { + Type: schema.TypeString, + Computed: true, + }, + "sep_id": { + Type: schema.TypeInt, + Computed: true, + }, + "size_max": { + Type: schema.TypeInt, + Computed: true, + }, + "type": { + Type: schema.TypeString, + Computed: true, + }, + }, + }, + }, + } + return res +} + +func dataSourceAccountDisksList() *schema.Resource { + return &schema.Resource{ + SchemaVersion: 1, + + Read: dataSourceAccountDiskssListRead, + + Timeouts: &schema.ResourceTimeout{ + Read: &Timeout30s, + Default: &Timeout60s, + }, + + Schema: dataSourceAccountDisksListSchemaMake(), + } +} diff --git a/decort/models_api.go b/decort/models_api.go index e02ed2c..9c9b3a8 100644 --- a/decort/models_api.go +++ b/decort/models_api.go @@ -1015,7 +1015,9 @@ const accountListAPI = "/restmachine/cloudbroker/account/list" const accountListComputesAPI = "/restmachine/cloudbroker/account/listComputes" const accountListCSAPI = "/cloudapi/account/listCS" const accountListDeletedAPI = "/cloudapi/account/listDeleted" -const accountListDisksAPI = "/cloudapi/account/listDisks" + +//const accountListDisksAPI = "/restmachine/cloudapi/account/listDisks" +const accountListDisksAPI = "/restmachine/cloudbroker/account/listDisks" const accountListFlipGroupsAPI = "/cloudapi/account/listFlipGroups" const accountListRGAPI = "/cloudapi/account/listRG" const accountListTemplatesAPI = "/cloudapi/account/listTemplates" @@ -1097,3 +1099,14 @@ type AccountCompute struct { } type AccountComputesList []AccountCompute + +type AccountDisk struct { + ID int `json:"id"` + Name string `json:"name"` + Pool string `json:"pool"` + SepId int `json:"sepId"` + SizeMax int `json:"sizeMax"` + Type string `json:"type"` +} + +type AccountDisksList []AccountDisk diff --git a/decort/provider.go b/decort/provider.go index c2a5fa5..98760cf 100644 --- a/decort/provider.go +++ b/decort/provider.go @@ -141,6 +141,7 @@ func Provider() *schema.Provider { "decort_rg_list": dataSourceRgList(), "decort_account_list": dataSourceAccountList(), "decort_account_computes_list": dataSourceAccountComputesList(), + "decort_account_disks_list": dataSourceAccountDisksList(), // "decort_pfw": dataSourcePfw(), }, diff --git a/decort/utility_accout_computes_list.go b/decort/utility_account_computes_list.go similarity index 100% rename from decort/utility_accout_computes_list.go rename to decort/utility_account_computes_list.go diff --git a/decort/utility_account_disks_list.go b/decort/utility_account_disks_list.go new file mode 100644 index 0000000..941a2bc --- /dev/null +++ b/decort/utility_account_disks_list.go @@ -0,0 +1,56 @@ +/* +Copyright (c) 2019-2022 Digital Energy Cloud Solutions LLC. All Rights Reserved. +Author: Stanislav Solovev, , + +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. +*/ + +/* +This file is part of Terraform (by Hashicorp) provider for Digital Energy Cloud Orchestration +Technology platfom. + +Visit https://github.com/rudecs/terraform-provider-decort for full source code package and updates. +*/ + +package decort + +import ( + "encoding/json" + "net/url" + "strconv" + + log "github.com/sirupsen/logrus" + + "github.com/hashicorp/terraform-plugin-sdk/helper/schema" +) + +func utilityAccountDisksListCheckPresence(d *schema.ResourceData, m interface{}) (AccountDisksList, error) { + accountDisksList := AccountDisksList{} + controller := m.(*ControllerCfg) + urlValues := &url.Values{} + + urlValues.Add("accountId", strconv.Itoa(d.Get("account_id").(int))) + + log.Debugf("utilityAccountDisksListCheckPresence: load account list") + accountDisksListRaw, err := controller.decortAPICall("POST", accountListDisksAPI, urlValues) + if err != nil { + return nil, err + } + + err = json.Unmarshal([]byte(accountDisksListRaw), &accountDisksList) + if err != nil { + return nil, err + } + + return accountDisksList, nil +} diff --git a/samples/account_disks_list/main.tf b/samples/account_disks_list/main.tf new file mode 100644 index 0000000..ff6b4fa --- /dev/null +++ b/samples/account_disks_list/main.tf @@ -0,0 +1,39 @@ +/* +Пример использования +Получение информации о дисках, которые использует аккаунт + +*/ +#Расскомментируйте этот код, +#и внесите необходимые правки в версию и путь, +#чтобы работать с установленным вручную (не через hashicorp provider registry) провайдером +/* +terraform { + required_providers { + decort = { + version = "1.1" + source = "digitalenergy.online/decort/decort" + } + } +} +*/ + +provider "decort" { + authenticator = "oauth2" + #controller_url = + controller_url = "https://ds1.digitalenergy.online" + #oauth2_url = + oauth2_url = "https://sso.digitalenergy.online" + allow_unverified_ssl = true +} + +data "decort_account_disks_list" "adl" { + #id аккаунта + #обязательный параметр + #тип - число + account_id = 28096 + +} + +output "test" { + value = data.decort_account_disks_list.adl +} From d527d9b47483405cd6e5d8454470232327f88907 Mon Sep 17 00:00:00 2001 From: stSolo Date: Tue, 24 May 2022 18:53:02 +0300 Subject: [PATCH 13/51] Add an account vins list --- decort/data_source_account_disks_list.go | 18 +- decort/data_source_account_vins_list.go | 174 ++++++++++++++++++ decort/models_api.go | 26 ++- decort/provider.go | 1 + decort/utility_account_vins_list.go | 56 ++++++ .../main.tf | 0 .../main.tf | 0 samples/data_account_vins_list/main.tf | 39 ++++ 8 files changed, 304 insertions(+), 10 deletions(-) create mode 100644 decort/data_source_account_vins_list.go create mode 100644 decort/utility_account_vins_list.go rename samples/{account_computes_list => data_account_computes_list}/main.tf (100%) rename samples/{account_disks_list => data_account_disks_list}/main.tf (100%) create mode 100644 samples/data_account_vins_list/main.tf diff --git a/decort/data_source_account_disks_list.go b/decort/data_source_account_disks_list.go index 489f8eb..6c33ced 100644 --- a/decort/data_source_account_disks_list.go +++ b/decort/data_source_account_disks_list.go @@ -31,14 +31,14 @@ import ( func flattenAccountDisksList(adl AccountDisksList) []map[string]interface{} { res := make([]map[string]interface{}, 0) - for _, acc := range adl { + for _, ad := range adl { temp := map[string]interface{}{ - "disk_id": acc.ID, - "disk_name": acc.Name, - "pool": acc.Pool, - "sep_id": acc.SepId, - "size_max": acc.SizeMax, - "type": acc.Type, + "disk_id": ad.ID, + "disk_name": ad.Name, + "pool": ad.Pool, + "sep_id": ad.SepId, + "size_max": ad.SizeMax, + "type": ad.Type, } res = append(res, temp) } @@ -46,7 +46,7 @@ func flattenAccountDisksList(adl AccountDisksList) []map[string]interface{} { } -func dataSourceAccountDiskssListRead(d *schema.ResourceData, m interface{}) error { +func dataSourceAccountDisksListRead(d *schema.ResourceData, m interface{}) error { accountDisksList, err := utilityAccountDisksListCheckPresence(d, m) if err != nil { return err @@ -107,7 +107,7 @@ func dataSourceAccountDisksList() *schema.Resource { return &schema.Resource{ SchemaVersion: 1, - Read: dataSourceAccountDiskssListRead, + Read: dataSourceAccountDisksListRead, Timeouts: &schema.ResourceTimeout{ Read: &Timeout30s, diff --git a/decort/data_source_account_vins_list.go b/decort/data_source_account_vins_list.go new file mode 100644 index 0000000..27307ff --- /dev/null +++ b/decort/data_source_account_vins_list.go @@ -0,0 +1,174 @@ +/* +Copyright (c) 2019-2021 Digital Energy Cloud Solutions LLC. All Rights Reserved. +Author: Sergey Shubin, , + +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. +*/ + +/* +This file is part of Terraform (by Hashicorp) provider for Digital Energy Cloud Orchestration +Technology platfom. + +Visit https://github.com/rudecs/terraform-provider-decort for full source code package and updates. +*/ + +package decort + +import ( + "github.com/google/uuid" + "github.com/hashicorp/terraform-plugin-sdk/helper/schema" +) + +func flattenAccountVinsList(avl AccountVinsList) []map[string]interface{} { + res := make([]map[string]interface{}, 0) + for _, av := range avl { + temp := map[string]interface{}{ + "account_id": av.AccountId, + "account_name": av.AccountName, + "computes": av.Computes, + "created_by": av.CreatedBy, + "created_time": av.CreatedTime, + "deleted_by": av.DeletedBy, + "deleted_time": av.DeletedTime, + "external_ip": av.ExternalIP, + "vin_id": av.ID, + "vin_name": av.Name, + "network": av.Network, + "pri_vnf_dev_id": av.PriVnfDevId, + "rg_id": av.RgId, + "rg_name": av.RgName, + "status": av.Status, + "updated_by": av.UpdatedBy, + "updated_time": av.UpdatedTime, + } + res = append(res, temp) + } + return res + +} + +func dataSourceAccountVinsListRead(d *schema.ResourceData, m interface{}) error { + accountVinsList, err := utilityAccountVinsListCheckPresence(d, m) + if err != nil { + return err + } + + id := uuid.New() + d.SetId(id.String()) + d.Set("items", flattenAccountVinsList(accountVinsList)) + + return nil +} + +func dataSourceAccountVinsListSchemaMake() map[string]*schema.Schema { + res := map[string]*schema.Schema{ + "account_id": { + Type: schema.TypeInt, + Required: true, + Description: "ID of the account", + }, + "items": { + Type: schema.TypeList, + Computed: true, + Description: "Search Result", + Elem: &schema.Resource{ + Schema: map[string]*schema.Schema{ + "account_id": { + Type: schema.TypeInt, + Computed: true, + }, + "account_name": { + Type: schema.TypeString, + Computed: true, + }, + "computes": { + Type: schema.TypeInt, + Computed: true, + }, + "created_by": { + Type: schema.TypeString, + Computed: true, + }, + "created_time": { + Type: schema.TypeInt, + Computed: true, + }, + "deleted_by": { + Type: schema.TypeString, + Computed: true, + }, + "deleted_time": { + Type: schema.TypeInt, + Computed: true, + }, + "external_ip": { + Type: schema.TypeString, + Computed: true, + }, + "vin_id": { + Type: schema.TypeInt, + Computed: true, + }, + "vin_name": { + Type: schema.TypeString, + Computed: true, + }, + "network": { + Type: schema.TypeString, + Computed: true, + }, + "pri_vnf_dev_id": { + Type: schema.TypeInt, + Computed: true, + }, + "rg_id": { + Type: schema.TypeInt, + Computed: true, + }, + "rg_name": { + Type: schema.TypeString, + Computed: true, + }, + "status": { + Type: schema.TypeString, + Computed: true, + }, + "updated_by": { + Type: schema.TypeString, + Computed: true, + }, + "updated_time": { + Type: schema.TypeInt, + Computed: true, + }, + }, + }, + }, + } + return res +} + +func dataSourceAccountVinsList() *schema.Resource { + return &schema.Resource{ + SchemaVersion: 1, + + Read: dataSourceAccountVinsListRead, + + Timeouts: &schema.ResourceTimeout{ + Read: &Timeout30s, + Default: &Timeout60s, + }, + + Schema: dataSourceAccountVinsListSchemaMake(), + } +} diff --git a/decort/models_api.go b/decort/models_api.go index 9c9b3a8..9b100f6 100644 --- a/decort/models_api.go +++ b/decort/models_api.go @@ -1021,7 +1021,9 @@ const accountListDisksAPI = "/restmachine/cloudbroker/account/listDisks" const accountListFlipGroupsAPI = "/cloudapi/account/listFlipGroups" const accountListRGAPI = "/cloudapi/account/listRG" const accountListTemplatesAPI = "/cloudapi/account/listTemplates" -const accountListVinsAPI = "/cloudapi/account/listVins" + +//const accountListVinsAPI = "/restmachine/cloudapi/account/listVins" +const accountListVinsAPI = "/restmachine/cloudbroker/account/listVins" const accountListVMsAPI = "/cloudapi/account/listVMs" const accountRestoreAPI = "/cloudapi/account/restore" const accountUpdateAPI = "/cloudapi/account/update" @@ -1110,3 +1112,25 @@ type AccountDisk struct { } type AccountDisksList []AccountDisk + +type AccountVin struct { + AccountId int `json:"accountId"` + AccountName string `json:"accountName"` + Computes int `json:"computes"` + CreatedBy string `json:"createdBy"` + CreatedTime int `json:"createdTime"` + DeletedBy string `json:"deletedBy"` + DeletedTime int `json:"deletedTime"` + ExternalIP string `json:"externalIP"` + ID int `json:"id"` + Name string `json:"name"` + Network string `json:"network"` + PriVnfDevId int `json:"priVnfDevId"` + RgId int `json:"rgId"` + RgName string `json:"rgName"` + Status string `json:"status"` + UpdatedBy string `json:"updatedBy"` + UpdatedTime int `json:"updatedTime"` +} + +type AccountVinsList []AccountVin diff --git a/decort/provider.go b/decort/provider.go index 98760cf..4f2f4ea 100644 --- a/decort/provider.go +++ b/decort/provider.go @@ -142,6 +142,7 @@ func Provider() *schema.Provider { "decort_account_list": dataSourceAccountList(), "decort_account_computes_list": dataSourceAccountComputesList(), "decort_account_disks_list": dataSourceAccountDisksList(), + "decort_account_vins_list": dataSourceAccountVinsList(), // "decort_pfw": dataSourcePfw(), }, diff --git a/decort/utility_account_vins_list.go b/decort/utility_account_vins_list.go new file mode 100644 index 0000000..31291ff --- /dev/null +++ b/decort/utility_account_vins_list.go @@ -0,0 +1,56 @@ +/* +Copyright (c) 2019-2022 Digital Energy Cloud Solutions LLC. All Rights Reserved. +Author: Stanislav Solovev, , + +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. +*/ + +/* +This file is part of Terraform (by Hashicorp) provider for Digital Energy Cloud Orchestration +Technology platfom. + +Visit https://github.com/rudecs/terraform-provider-decort for full source code package and updates. +*/ + +package decort + +import ( + "encoding/json" + "net/url" + "strconv" + + log "github.com/sirupsen/logrus" + + "github.com/hashicorp/terraform-plugin-sdk/helper/schema" +) + +func utilityAccountVinsListCheckPresence(d *schema.ResourceData, m interface{}) (AccountVinsList, error) { + accountVinsList := AccountVinsList{} + controller := m.(*ControllerCfg) + urlValues := &url.Values{} + + urlValues.Add("accountId", strconv.Itoa(d.Get("account_id").(int))) + + log.Debugf("utilityAccountVinsListCheckPresence: load account list") + accountVinsListRaw, err := controller.decortAPICall("POST", accountListVinsAPI, urlValues) + if err != nil { + return nil, err + } + + err = json.Unmarshal([]byte(accountVinsListRaw), &accountVinsList) + if err != nil { + return nil, err + } + + return accountVinsList, nil +} diff --git a/samples/account_computes_list/main.tf b/samples/data_account_computes_list/main.tf similarity index 100% rename from samples/account_computes_list/main.tf rename to samples/data_account_computes_list/main.tf diff --git a/samples/account_disks_list/main.tf b/samples/data_account_disks_list/main.tf similarity index 100% rename from samples/account_disks_list/main.tf rename to samples/data_account_disks_list/main.tf diff --git a/samples/data_account_vins_list/main.tf b/samples/data_account_vins_list/main.tf new file mode 100644 index 0000000..da28996 --- /dev/null +++ b/samples/data_account_vins_list/main.tf @@ -0,0 +1,39 @@ +/* +Пример использования +Получение списка vins, используемых аккаунтом + +*/ +#Расскомментируйте этот код, +#и внесите необходимые правки в версию и путь, +#чтобы работать с установленным вручную (не через hashicorp provider registry) провайдером +/* +terraform { + required_providers { + decort = { + version = "1.1" + source = "digitalenergy.online/decort/decort" + } + } +} +*/ + +provider "decort" { + authenticator = "oauth2" + #controller_url = + controller_url = "https://ds1.digitalenergy.online" + #oauth2_url = + oauth2_url = "https://sso.digitalenergy.online" + allow_unverified_ssl = true +} + +data "decort_account_vins_list" "avl" { + #id аккаунта + #обязательный параметр + #тип - число + account_id = 28096 + +} + +output "test" { + value = data.decort_account_vins_list.avl +} From 9912b04c2a8c1fc3ebf457a20eb4509ed831806e Mon Sep 17 00:00:00 2001 From: stSolo Date: Tue, 24 May 2022 19:22:29 +0300 Subject: [PATCH 14/51] Add data function account-audits-list --- decort/data_source_account_audits_list.go | 114 ++++++++++++++++++++++ decort/models_api.go | 14 ++- decort/provider.go | 1 + decort/utility_account_audits_list.go | 56 +++++++++++ samples/README.md | 4 + samples/data_account_audits_list/main.tf | 40 ++++++++ 6 files changed, 228 insertions(+), 1 deletion(-) create mode 100644 decort/data_source_account_audits_list.go create mode 100644 decort/utility_account_audits_list.go create mode 100644 samples/data_account_audits_list/main.tf diff --git a/decort/data_source_account_audits_list.go b/decort/data_source_account_audits_list.go new file mode 100644 index 0000000..3475527 --- /dev/null +++ b/decort/data_source_account_audits_list.go @@ -0,0 +1,114 @@ +/* +Copyright (c) 2019-2021 Digital Energy Cloud Solutions LLC. All Rights Reserved. +Author: Sergey Shubin, , + +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. +*/ + +/* +This file is part of Terraform (by Hashicorp) provider for Digital Energy Cloud Orchestration +Technology platfom. + +Visit https://github.com/rudecs/terraform-provider-decort for full source code package and updates. +*/ + +package decort + +import ( + "github.com/google/uuid" + "github.com/hashicorp/terraform-plugin-sdk/helper/schema" +) + +func flattenAccountAuditsList(aal AccountAuditsList) []map[string]interface{} { + res := make([]map[string]interface{}, 0) + for _, aa := range aal { + temp := map[string]interface{}{ + "call": aa.Call, + "responsetime": aa.ResponseTime, + "statuscode": aa.StatusCode, + "timestamp": aa.Timestamp, + "user": aa.User, + } + res = append(res, temp) + } + return res + +} + +func dataSourceAccountAuditsListRead(d *schema.ResourceData, m interface{}) error { + accountAuditsList, err := utilityAccountAuditsListCheckPresence(d, m) + if err != nil { + return err + } + + id := uuid.New() + d.SetId(id.String()) + d.Set("items", flattenAccountAuditsList(accountAuditsList)) + + return nil +} + +func dataSourceAccountAuditsListSchemaMake() map[string]*schema.Schema { + res := map[string]*schema.Schema{ + "account_id": { + Type: schema.TypeInt, + Required: true, + Description: "ID of the account", + }, + "items": { + Type: schema.TypeList, + Computed: true, + Description: "Search Result", + Elem: &schema.Resource{ + Schema: map[string]*schema.Schema{ + "call": { + Type: schema.TypeString, + Computed: true, + }, + "responsetime": { + Type: schema.TypeFloat, + Computed: true, + }, + "statuscode": { + Type: schema.TypeInt, + Computed: true, + }, + "timestamp": { + Type: schema.TypeFloat, + Computed: true, + }, + "user": { + Type: schema.TypeString, + Computed: true, + }, + }, + }, + }, + } + return res +} + +func dataSourceAccountAuditsList() *schema.Resource { + return &schema.Resource{ + SchemaVersion: 1, + + Read: dataSourceAccountAuditsListRead, + + Timeouts: &schema.ResourceTimeout{ + Read: &Timeout30s, + Default: &Timeout60s, + }, + + Schema: dataSourceAccountAuditsListSchemaMake(), + } +} diff --git a/decort/models_api.go b/decort/models_api.go index 9b100f6..d783626 100644 --- a/decort/models_api.go +++ b/decort/models_api.go @@ -993,7 +993,9 @@ type SepPool map[string]interface{} /////////////////////// const accountAddUserAPI = "/cloudapi/account/addUser" -const accountAuditsAPI = "/cloudapi/account/audits" + +//const accountAuditsAPI = "/restmachine/cloudapi/account/audits" +const accountAuditsAPI = "/restmachine/cloudbroker/account/audits" const accountCreateAPI = "/cloudapi/account/create" const accountDeleteAPI = "/cloudapi/account/delete" const accountDeleteAccountsAPI = "/cloudapi/account/deleteAccounts" @@ -1134,3 +1136,13 @@ type AccountVin struct { } type AccountVinsList []AccountVin + +type AccountAudit struct { + Call string `json:"call"` + ResponseTime float64 `json:"responsetime"` + StatusCode int `json:"statuscode"` + Timestamp float64 `json:"timestamp"` + User string `json:"user"` +} + +type AccountAuditsList []AccountAudit diff --git a/decort/provider.go b/decort/provider.go index 4f2f4ea..b2f9e45 100644 --- a/decort/provider.go +++ b/decort/provider.go @@ -143,6 +143,7 @@ func Provider() *schema.Provider { "decort_account_computes_list": dataSourceAccountComputesList(), "decort_account_disks_list": dataSourceAccountDisksList(), "decort_account_vins_list": dataSourceAccountVinsList(), + "decort_account_audits_list": dataSourceAccountAuditsList(), // "decort_pfw": dataSourcePfw(), }, diff --git a/decort/utility_account_audits_list.go b/decort/utility_account_audits_list.go new file mode 100644 index 0000000..283c513 --- /dev/null +++ b/decort/utility_account_audits_list.go @@ -0,0 +1,56 @@ +/* +Copyright (c) 2019-2022 Digital Energy Cloud Solutions LLC. All Rights Reserved. +Author: Stanislav Solovev, , + +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. +*/ + +/* +This file is part of Terraform (by Hashicorp) provider for Digital Energy Cloud Orchestration +Technology platfom. + +Visit https://github.com/rudecs/terraform-provider-decort for full source code package and updates. +*/ + +package decort + +import ( + "encoding/json" + "net/url" + "strconv" + + log "github.com/sirupsen/logrus" + + "github.com/hashicorp/terraform-plugin-sdk/helper/schema" +) + +func utilityAccountAuditsListCheckPresence(d *schema.ResourceData, m interface{}) (AccountAuditsList, error) { + accountAuditsList := AccountAuditsList{} + controller := m.(*ControllerCfg) + urlValues := &url.Values{} + + urlValues.Add("accountId", strconv.Itoa(d.Get("account_id").(int))) + + log.Debugf("utilityAccountAuditsListCheckPresence: load account list") + accountAuditsListRaw, err := controller.decortAPICall("POST", accountAuditsAPI, urlValues) + if err != nil { + return nil, err + } + + err = json.Unmarshal([]byte(accountAuditsListRaw), &accountAuditsList) + if err != nil { + return nil, err + } + + return accountAuditsList, nil +} diff --git a/samples/README.md b/samples/README.md index c4ff93c..7a61d08 100644 --- a/samples/README.md +++ b/samples/README.md @@ -21,6 +21,10 @@ - disk_list - rg_list - account_list + - account_computes_list + - account_disks_list + - account_vins_list + - account_audits_list - resources: - image - virtual_image diff --git a/samples/data_account_audits_list/main.tf b/samples/data_account_audits_list/main.tf new file mode 100644 index 0000000..a30b152 --- /dev/null +++ b/samples/data_account_audits_list/main.tf @@ -0,0 +1,40 @@ +/* +Пример использования +Получение информации об использовании аккаунта + +*/ +#Расскомментируйте этот код, +#и внесите необходимые правки в версию и путь, +#чтобы работать с установленным вручную (не через hashicorp provider registry) провайдером +/* +terraform { + required_providers { + decort = { + version = "1.1" + source = "digitalenergy.online/decort/decort" + } + } +} +*/ + + +provider "decort" { + authenticator = "oauth2" + #controller_url = + controller_url = "https://ds1.digitalenergy.online" + #oauth2_url = + oauth2_url = "https://sso.digitalenergy.online" + allow_unverified_ssl = true +} + +data "decort_account_audits_list" "aal" { + #id аккаунта + #обязательный параметр + #тип - число + account_id = 28096 + +} + +output "test" { + value = data.decort_account_audits_list.aal +} From a0fbc8dd4f81027b06b80106ec02796e9b5d0de5 Mon Sep 17 00:00:00 2001 From: stSolo Date: Wed, 25 May 2022 10:58:29 +0300 Subject: [PATCH 15/51] Add data function for an account --- decort/data_source_account.go | 363 +++++++++++++++----- decort/data_source_account_audits_list.go | 4 +- decort/data_source_account_computes_list.go | 4 +- decort/data_source_account_disks_list.go | 4 +- decort/data_source_account_list.go | 4 +- decort/data_source_account_vins_list.go | 4 +- decort/models_api.go | 4 +- decort/resource_rg.go | 10 +- decort/utility_account.go | 124 +------ decort/utility_disk.go | 46 ++- decort/utility_rg.go | 12 +- samples/README.md | 1 + samples/data_account/main.tf | 39 +++ 13 files changed, 375 insertions(+), 244 deletions(-) create mode 100644 samples/data_account/main.tf diff --git a/decort/data_source_account.go b/decort/data_source_account.go index 735384f..2db3008 100644 --- a/decort/data_source_account.go +++ b/decort/data_source_account.go @@ -1,6 +1,6 @@ /* -Copyright (c) 2019-2021 Digital Energy Cloud Solutions LLC. All Rights Reserved. -Author: Sergey Shubin, , +Copyright (c) 2019-2022 Digital Energy Cloud Solutions LLC. All Rights Reserved. +Author: Stanislav Solovev, Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. @@ -25,45 +25,298 @@ Visit https://github.com/rudecs/terraform-provider-decort for full source code p package decort import ( - "encoding/json" - "fmt" - // "net/url" - - log "github.com/sirupsen/logrus" - + "github.com/google/uuid" "github.com/hashicorp/terraform-plugin-sdk/helper/schema" ) -func flattenAccount(d *schema.ResourceData, acc_facts string) error { - // NOTE: this function modifies ResourceData argument - as such it should never be called - // from resourceAccountExists(...) method - - // log.Debugf("flattenAccount: ready to decode response body from %q", CloudspacesGetAPI) - details := AccountRecord{} - err := json.Unmarshal([]byte(acc_facts), &details) +func dataSourceAccountRead(d *schema.ResourceData, m interface{}) error { + acc, err := utilityAccountCheckPresence(d, m) if err != nil { return err } - log.Debugf("flattenAccount: decoded Account name %q / ID %d, status %q", details.Name, details.ID, details.Status) - - d.SetId(fmt.Sprintf("%d", details.ID)) - d.Set("name", details.Name) - d.Set("status", details.Status) - + id := uuid.New() + d.SetId(id.String()) + d.Set("dc_location", acc.DCLocation) + d.Set("resources", flattenAccResources(acc.Resources)) + d.Set("ckey", acc.CKey) + d.Set("meta", flattenMeta(acc.Meta)) + d.Set("acl", flattenRgAcl(acc.Acl)) + d.Set("company", acc.Company) + d.Set("companyurl", acc.CompanyUrl) + d.Set("created_by", acc.CreatedBy) + d.Set("created_time", acc.CreatedTime) + d.Set("deactivation_time", acc.DeactiovationTime) + d.Set("deleted_by", acc.DeletedBy) + d.Set("deleted_time", acc.DeletedTime) + d.Set("displayname", acc.DisplayName) + d.Set("guid", acc.GUID) + d.Set("account_id", acc.ID) + d.Set("account_name", acc.Name) + d.Set("resource_limits", flattenRgResourceLimits(acc.ResourceLimits)) + d.Set("send_access_emails", acc.SendAccessEmails) + d.Set("service_account", acc.ServiceAccount) + d.Set("status", acc.Status) + d.Set("updated_time", acc.UpdatedTime) + d.Set("version", acc.Version) + d.Set("vins", acc.Vins) return nil } -func dataSourceAccountRead(d *schema.ResourceData, m interface{}) error { - acc_facts, err := utilityAccountCheckPresence(d, m) - if acc_facts == "" { - // if empty string is returned from utilityAccountCheckPresence then there is no - // such account and err tells so - just return it to the calling party - d.SetId("") // ensure ID is empty in this case - return err +func flattenAccResources(r Resources) []map[string]interface{} { + res := make([]map[string]interface{}, 0) + temp := map[string]interface{}{ + "current": flattenAccResource(r.Current), + "reserved": flattenAccResource(r.Reserved), } + res = append(res, temp) + return res +} + +func flattenAccResource(r Resource) []map[string]interface{} { + res := make([]map[string]interface{}, 0) + temp := map[string]interface{}{ + "cpu": r.CPU, + "disksize": r.Disksize, + "extips": r.Extips, + "exttraffic": r.Exttraffic, + "gpu": r.GPU, + "ram": r.RAM, + } + res = append(res, temp) + return res +} - return flattenAccount(d, acc_facts) +func dataSourceAccountSchemaMake() map[string]*schema.Schema { + res := map[string]*schema.Schema{ + "account_id": { + Type: schema.TypeInt, + Required: true, + }, + "dc_location": { + Type: schema.TypeString, + Computed: true, + }, + "resources": { + Type: schema.TypeList, + Computed: true, + MaxItems: 1, + Elem: &schema.Resource{ + Schema: map[string]*schema.Schema{ + "current": { + Type: schema.TypeList, + Computed: true, + MaxItems: 1, + Elem: &schema.Resource{ + Schema: map[string]*schema.Schema{ + "cpu": { + Type: schema.TypeInt, + Computed: true, + }, + "disksize": { + Type: schema.TypeInt, + Computed: true, + }, + "extips": { + Type: schema.TypeInt, + Computed: true, + }, + "exttraffic": { + Type: schema.TypeInt, + Computed: true, + }, + "gpu": { + Type: schema.TypeInt, + Computed: true, + }, + "ram": { + Type: schema.TypeInt, + Computed: true, + }, + }, + }, + }, + "reserved": { + Type: schema.TypeList, + Computed: true, + MaxItems: 1, + Elem: &schema.Resource{ + Schema: map[string]*schema.Schema{ + "cpu": { + Type: schema.TypeInt, + Computed: true, + }, + "disksize": { + Type: schema.TypeInt, + Computed: true, + }, + "extips": { + Type: schema.TypeInt, + Computed: true, + }, + "exttraffic": { + Type: schema.TypeInt, + Computed: true, + }, + "gpu": { + Type: schema.TypeInt, + Computed: true, + }, + "ram": { + Type: schema.TypeInt, + Computed: true, + }, + }, + }, + }, + }, + }, + }, + "ckey": { + Type: schema.TypeString, + Computed: true, + }, + "meta": { + Type: schema.TypeList, + Computed: true, + Elem: &schema.Schema{ + Type: schema.TypeString, + }, + }, + "acl": { + Type: schema.TypeList, + Computed: true, + Elem: &schema.Resource{ + Schema: map[string]*schema.Schema{ + "explicit": { + Type: schema.TypeBool, + Computed: true, + }, + "guid": { + Type: schema.TypeString, + Computed: true, + }, + "right": { + Type: schema.TypeString, + Computed: true, + }, + "status": { + Type: schema.TypeString, + Computed: true, + }, + "type": { + Type: schema.TypeString, + Computed: true, + }, + "user_group_id": { + Type: schema.TypeString, + Computed: true, + }, + }, + }, + }, + "company": { + Type: schema.TypeString, + Computed: true, + }, + "companyurl": { + Type: schema.TypeString, + Computed: true, + }, + "created_by": { + Type: schema.TypeString, + Computed: true, + }, + "created_time": { + Type: schema.TypeInt, + Computed: true, + }, + "deactivation_time": { + Type: schema.TypeFloat, + Computed: true, + }, + "deleted_by": { + Type: schema.TypeString, + Computed: true, + }, + "deleted_time": { + Type: schema.TypeInt, + Computed: true, + }, + "displayname": { + Type: schema.TypeString, + Computed: true, + }, + "guid": { + Type: schema.TypeInt, + Computed: true, + }, + "account_name": { + Type: schema.TypeString, + Computed: true, + }, + "resource_limits": { + Type: schema.TypeList, + Computed: true, + MaxItems: 1, + Elem: &schema.Resource{ + Schema: map[string]*schema.Schema{ + "cu_c": { + Type: schema.TypeFloat, + Computed: true, + }, + "cu_d": { + Type: schema.TypeFloat, + Computed: true, + }, + "cu_i": { + Type: schema.TypeFloat, + Computed: true, + }, + "cu_m": { + Type: schema.TypeFloat, + Computed: true, + }, + "cu_np": { + Type: schema.TypeFloat, + Computed: true, + }, + "gpu_units": { + Type: schema.TypeFloat, + Computed: true, + }, + }, + }, + }, + "send_access_emails": { + Type: schema.TypeBool, + Computed: true, + }, + "service_account": { + Type: schema.TypeBool, + Computed: true, + }, + "status": { + Type: schema.TypeString, + Computed: true, + }, + "updated_time": { + Type: schema.TypeInt, + Computed: true, + }, + "version": { + Type: schema.TypeInt, + Computed: true, + }, + "vins": { + Type: schema.TypeList, + Computed: true, + Elem: &schema.Schema{ + Type: schema.TypeInt, + }, + }, + } + return res } func dataSourceAccount() *schema.Resource { @@ -77,56 +330,6 @@ func dataSourceAccount() *schema.Resource { Default: &Timeout60s, }, - Schema: map[string]*schema.Schema{ - "name": { - Type: schema.TypeString, - Optional: true, - Description: "Name of the account. Names are case sensitive and unique.", - }, - - "account_id": { - Type: schema.TypeInt, - Optional: true, - Description: "Unique ID of the account. If account ID is specified, then account name is ignored.", - }, - - "status": { - Type: schema.TypeString, - Computed: true, - Description: "Current status of the account.", - }, - - /* We keep the following attributes commented out, as we are not implementing account - management with Terraform plugin, so we do not need this extra info. - - "quota": { - Type: schema.TypeList, - Optional: true, - MaxItems: 1, - Elem: &schema.Resource{ - Schema: quotaRgSubresourceSchema(), // this is a dictionary - }, - Description: "Quotas on the resources for this account and all its resource groups.", - }, - - "resource_groups": { - Type: schema.TypeList, - Computed: true, - Elem: &schema.Schema { - Type: schema.TypeInt, - }, - Description: "IDs of resource groups in this account." - }, - - "vins": { - Type: schema.TypeList, - Computed: true, - Elem: &schema.Schema { - Type: schema.TypeInt, - }, - Description: "IDs of VINSes created at the account level." - }, - */ - }, + Schema: dataSourceAccountSchemaMake(), } } diff --git a/decort/data_source_account_audits_list.go b/decort/data_source_account_audits_list.go index 3475527..c31e947 100644 --- a/decort/data_source_account_audits_list.go +++ b/decort/data_source_account_audits_list.go @@ -1,6 +1,6 @@ /* -Copyright (c) 2019-2021 Digital Energy Cloud Solutions LLC. All Rights Reserved. -Author: Sergey Shubin, , +Copyright (c) 2019-2022 Digital Energy Cloud Solutions LLC. All Rights Reserved. +Author: Stanislav Solovev, Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. diff --git a/decort/data_source_account_computes_list.go b/decort/data_source_account_computes_list.go index b4b99ad..8a7ba77 100644 --- a/decort/data_source_account_computes_list.go +++ b/decort/data_source_account_computes_list.go @@ -1,6 +1,6 @@ /* -Copyright (c) 2019-2021 Digital Energy Cloud Solutions LLC. All Rights Reserved. -Author: Sergey Shubin, , +Copyright (c) 2019-2022 Digital Energy Cloud Solutions LLC. All Rights Reserved. +Author: Stanislav Solovev, Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. diff --git a/decort/data_source_account_disks_list.go b/decort/data_source_account_disks_list.go index 6c33ced..def9676 100644 --- a/decort/data_source_account_disks_list.go +++ b/decort/data_source_account_disks_list.go @@ -1,6 +1,6 @@ /* -Copyright (c) 2019-2021 Digital Energy Cloud Solutions LLC. All Rights Reserved. -Author: Sergey Shubin, , +Copyright (c) 2019-2022 Digital Energy Cloud Solutions LLC. All Rights Reserved. +Author: Stanislav Solovev, Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. diff --git a/decort/data_source_account_list.go b/decort/data_source_account_list.go index c6f6919..866f232 100644 --- a/decort/data_source_account_list.go +++ b/decort/data_source_account_list.go @@ -1,6 +1,6 @@ /* -Copyright (c) 2019-2021 Digital Energy Cloud Solutions LLC. All Rights Reserved. -Author: Sergey Shubin, , +Copyright (c) 2019-2022 Digital Energy Cloud Solutions LLC. All Rights Reserved. +Author: Stanislav Solovev, Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. diff --git a/decort/data_source_account_vins_list.go b/decort/data_source_account_vins_list.go index 27307ff..e9d50e7 100644 --- a/decort/data_source_account_vins_list.go +++ b/decort/data_source_account_vins_list.go @@ -1,6 +1,6 @@ /* -Copyright (c) 2019-2021 Digital Energy Cloud Solutions LLC. All Rights Reserved. -Author: Sergey Shubin, , +Copyright (c) 2019-2022 Digital Energy Cloud Solutions LLC. All Rights Reserved. +Author: Stanislav Solovev, Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. diff --git a/decort/models_api.go b/decort/models_api.go index d783626..3c07f8b 100644 --- a/decort/models_api.go +++ b/decort/models_api.go @@ -1002,7 +1002,9 @@ const accountDeleteAccountsAPI = "/cloudapi/account/deleteAccounts" const accountDeleteUserAPI = "/cloudapi/account/deleteUser" const accountDisableAPI = "/cloudapi/account/disable" const accountEnableAPI = "/cloudapi/account/enable" -const accountGetAPI = "/cloudapi/account/get" + +//const accountGetAPI = "/restmachine/cloudapi/account/get" +const accountGetAPI = "/restmachine/cloudbroker/account/get" const accountGetConsumedAccountUnitsAPI = "/cloudapi/account/getConsumedAccountUnits" const accountGetConsumedCloudUnitsByTypeAPI = "/cloudapi/account/getConsumedCloudUnitsByType" const accountGetConsumptionGetAPI = "/cloudapi/account/getConsumption" diff --git a/decort/resource_rg.go b/decort/resource_rg.go index 4a07cb6..5528bb4 100644 --- a/decort/resource_rg.go +++ b/decort/resource_rg.go @@ -39,10 +39,6 @@ func resourceResgroupCreate(d *schema.ResourceData, m interface{}) error { // Valid account ID is required to create new resource group // obtain Account ID by account name - it should not be zero on success - validated_account_id, err := utilityGetAccountIdBySchema(d, m) - if err != nil { - return err - } rg_name, arg_set := d.GetOk("name") if !arg_set { @@ -62,7 +58,7 @@ func resourceResgroupCreate(d *schema.ResourceData, m interface{}) error { // all required parameters are set in the schema - we can continue with RG creation log.Debugf("resourceResgroupCreate: called for RG name %s, account ID %d", - rg_name.(string), validated_account_id) + rg_name.(string), d.Get("account_id").(int)) // quota settings are optional set_quota := false @@ -77,10 +73,10 @@ func resourceResgroupCreate(d *schema.ResourceData, m interface{}) error { controller := m.(*ControllerCfg) log.Debugf("resourceResgroupCreate: called by user %q for RG name %s, account ID %d", controller.getDecortUsername(), - rg_name.(string), validated_account_id) + rg_name.(string), d.Get("account_id").(int)) url_values := &url.Values{} - url_values.Add("accountId", fmt.Sprintf("%d", validated_account_id)) + url_values.Add("accountId", fmt.Sprintf("%d", d.Get("account_id").(int))) url_values.Add("name", rg_name.(string)) url_values.Add("gid", fmt.Sprintf("%d", DefaultGridID)) // use default Grid ID, similar to disk resource mgmt convention url_values.Add("owner", controller.getDecortUsername()) diff --git a/decort/utility_account.go b/decort/utility_account.go index c9a6def..f2b5e2e 100644 --- a/decort/utility_account.go +++ b/decort/utility_account.go @@ -1,6 +1,6 @@ /* -Copyright (c) 2019-2021 Digital Energy Cloud Solutions LLC. All Rights Reserved. -Author: Sergey Shubin, , +Copyright (c) 2019-2022 Digital Energy Cloud Solutions LLC. All Rights Reserved. +Author: Stanislav Solovev, , Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. @@ -26,131 +26,31 @@ package decort import ( "encoding/json" - "fmt" "net/url" + "strconv" log "github.com/sirupsen/logrus" "github.com/hashicorp/terraform-plugin-sdk/helper/schema" - // "github.com/hashicorp/terraform-plugin-sdk/helper/validation" ) -func utilityAccountCheckPresence(d *schema.ResourceData, m interface{}) (string, error) { +func utilityAccountCheckPresence(d *schema.ResourceData, m interface{}) (*AccountWithResources, error) { + account := &AccountWithResources{} controller := m.(*ControllerCfg) urlValues := &url.Values{} - accId, argSet := d.GetOk("account_id") - if argSet { - // get Account right away by its ID - log.Debugf("utilityAccountCheckPresence: locating Account by its ID %d", accId.(int)) - urlValues.Add("accountId", fmt.Sprintf("%d", accId.(int))) - apiResp, err := controller.decortAPICall("POST", AccountsGetAPI, urlValues) - if err != nil { - return "", err - } - return apiResp, nil - } - - accName, argSet := d.GetOk("name") - if !argSet { - // neither ID nor name - no account for you! - return "", fmt.Errorf("Cannot check account presence if name is empty and no account ID specified") - } - - apiResp, err := controller.decortAPICall("POST", AccountsListAPI, urlValues) - if err != nil { - return "", err - } - // log.Debugf("%s", apiResp) - // log.Debugf("utilityAccountCheckPresence: ready to decode response body from %q", AccountsListAPI) - accList := AccountsListResp{} - err = json.Unmarshal([]byte(apiResp), &accList) - if err != nil { - return "", err - } - - log.Debugf("utilityAccountCheckPresence: traversing decoded Json of length %d", len(accList)) - for index, item := range accList { - // match by account name - if item.Name == accName.(string) { - log.Debugf("utilityAccountCheckPresence: match account name %q / ID %d at index %d", - item.Name, item.ID, index) - - // NB: unlike accounts/get API, accounts/list API returns abridged set of account info, - // for instance it does not return quotas - - reencodedItem, err := json.Marshal(item) - if err != nil { - return "", err - } - return string(reencodedItem[:]), nil - } - } - - return "", fmt.Errorf("Cannot find account name %q", accName.(string)) -} + urlValues.Add("accountId", strconv.Itoa(d.Get("account_id").(int))) -func utilityGetAccountIdBySchema(d *schema.ResourceData, m interface{}) (int, error) { - /* - This function expects schema that contains the following two elements: - - "account_name": &schema.Schema{ - Type: schema.TypeString, - Required: Optional, - Description: "Name of the account, ....", - }, - - "account_id": &schema.Schema{ - Type: schema.TypeInt, - Optional: true, - Description: "Unique ID of the account, ....", - }, - - Then it will check, which argument is set, and if account name is present, it will - initiate API calls to the DECORT cloud controller and try to match relevant account - by the name. - - NOTE that for some resources (most notably, Resource Group) "account_name" attribute is - marked as "Computed: true", so the only way to fully identify Resource Group is to specify - "account_id", which is marked as "Required: true" - - */ - - accId, argSet := d.GetOk("account_id") - if argSet { - if accId.(int) > 0 { - return accId.(int), nil - } - return 0, fmt.Errorf("Account ID must be positive") - } - - accName, argSet := d.GetOk("account_name") - if !argSet { - return 0, fmt.Errorf("Either non-empty account name or valid account ID must be specified") - } - - controller := m.(*ControllerCfg) - urlValues := &url.Values{} - apiResp, err := controller.decortAPICall("POST", AccountsListAPI, urlValues) + log.Debugf("utilityAccountCheckPresence: load account") + accountRaw, err := controller.decortAPICall("POST", accountGetAPI, urlValues) if err != nil { - return 0, err + return nil, err } - model := AccountsListResp{} - err = json.Unmarshal([]byte(apiResp), &model) + err = json.Unmarshal([]byte(accountRaw), &account) if err != nil { - return 0, err - } - - log.Debugf("utilityGetAccountIdBySchema: traversing decoded Json of length %d", len(model)) - for index, item := range model { - // need to match Account by name - if item.Name == accName.(string) { - log.Debugf("utilityGetAccountIdBySchema: match Account name %q / ID %d at index %d", - item.Name, item.ID, index) - return item.ID, nil - } + return nil, err } - return 0, fmt.Errorf("Cannot find account %q for the current user. Check account name and your access rights", accName.(string)) + return account, nil } diff --git a/decort/utility_disk.go b/decort/utility_disk.go index 1422c03..c9a8605 100644 --- a/decort/utility_disk.go +++ b/decort/utility_disk.go @@ -16,16 +16,15 @@ limitations under the License. */ /* -This file is part of Terraform (by Hashicorp) provider for Digital Energy Cloud Orchestration +This file is part of Terraform (by Hashicorp) provider for Digital Energy Cloud Orchestration Technology platfom. -Visit https://github.com/rudecs/terraform-provider-decort for full source code package and updates. +Visit https://github.com/rudecs/terraform-provider-decort for full source code package and updates. */ package decort import ( - "encoding/json" "fmt" "net/url" @@ -36,16 +35,15 @@ import ( "github.com/hashicorp/terraform-plugin-sdk/helper/schema" ) - func utilityDiskCheckPresence(d *schema.ResourceData, m interface{}) (string, error) { - // This function tries to locate Disk by one of the following algorithms depending on + // This function tries to locate Disk by one of the following algorithms depending on // the parameters passed: // - if disk ID is specified -> by disk ID // - if disk name is specifeid -> by disk name and either account ID or account name // // NOTE: disk names are not unique, so the first occurence of this name in the account will // be returned. There is no such ambiguity when locating disk by its ID. - // + // // If succeeded, it returns non empty string that contains JSON formatted facts about the disk // as returned by disks/get API call. // Otherwise it returns empty string and meaningful error. @@ -64,7 +62,7 @@ func utilityDiskCheckPresence(d *schema.ResourceData, m interface{}) (string, er if err != nil || theId <= 0 { diskId, argSet := d.GetOk("disk_id") if argSet { - theId =diskId.(int) + theId = diskId.(int) idSet = true } } else { @@ -92,18 +90,14 @@ func utilityDiskCheckPresence(d *schema.ResourceData, m interface{}) (string, er // Valid account ID is required to locate disks // obtain Account ID by account name - it should not be zero on success - validatedAccountId, err := utilityGetAccountIdBySchema(d, m) - if err != nil { - return "", err - } - urlValues.Add("accountId", fmt.Sprintf("%d", validatedAccountId)) + urlValues.Add("accountId", fmt.Sprintf("%d", d.Get("account_id").(int))) diskFacts, err := controller.decortAPICall("POST", DisksListAPI, urlValues) if err != nil { return "", err } - log.Debugf("utilityDiskCheckPresence: ready to unmarshal string %s", diskFacts) + log.Debugf("utilityDiskCheckPresence: ready to unmarshal string %s", diskFacts) disksList := DisksListResp{} err = json.Unmarshal([]byte(diskFacts), &disksList) @@ -119,25 +113,25 @@ func utilityDiskCheckPresence(d *schema.ResourceData, m interface{}) (string, er log.Debugf("utilityDiskCheckPresence: index %d, matched disk name %q", index, item.Name) // we found the disk we need - not get detailed information via API call to disks/get /* - // TODO: this may not be optimal as it initiates one extra call to the DECORT controller - // in spite of the fact that we already have all required information about the disk in - // item variable - // - get_urlValues := &url.Values{} - get_urlValues.Add("diskId", fmt.Sprintf("%d", item.ID)) - diskFacts, err = controller.decortAPICall("POST", DisksGetAPI, get_urlValues) - if err != nil { - return "", err - } - return diskFacts, nil + // TODO: this may not be optimal as it initiates one extra call to the DECORT controller + // in spite of the fact that we already have all required information about the disk in + // item variable + // + get_urlValues := &url.Values{} + get_urlValues.Add("diskId", fmt.Sprintf("%d", item.ID)) + diskFacts, err = controller.decortAPICall("POST", DisksGetAPI, get_urlValues) + if err != nil { + return "", err + } + return diskFacts, nil */ reencodedItem, err := json.Marshal(item) if err != nil { return "", err } - return string(reencodedItem[:]), nil + return string(reencodedItem[:]), nil } } return "", nil // there should be no error if disk does not exist -} \ No newline at end of file +} diff --git a/decort/utility_rg.go b/decort/utility_rg.go index 371e678..6a62ebd 100644 --- a/decort/utility_rg.go +++ b/decort/utility_rg.go @@ -104,7 +104,7 @@ func utilityResgroupCheckPresence(d *schema.ResourceData, m interface{}) (string } else { idSet = true } - + if idSet { // go straight for the RG by its ID log.Debugf("utilityResgroupCheckPresence: locating RG by its ID %d", theId) @@ -124,10 +124,6 @@ func utilityResgroupCheckPresence(d *schema.ResourceData, m interface{}) (string // Valid account ID is required to locate a resource group // obtain Account ID by account name - it should not be zero on success - validatedAccountId, err := utilityGetAccountIdBySchema(d, m) - if err != nil { - return "", err - } urlValues.Add("includedeleted", "false") apiResp, err := controller.decortAPICall("POST", ResgroupListAPI, urlValues) @@ -145,7 +141,7 @@ func utilityResgroupCheckPresence(d *schema.ResourceData, m interface{}) (string log.Debugf("utilityResgroupCheckPresence: traversing decoded Json of length %d", len(model)) for index, item := range model { // match by RG name & account ID - if item.Name == rgName.(string) && item.AccountID == validatedAccountId { + if item.Name == rgName.(string) && item.AccountID == d.Get("account_id").(int) { log.Debugf("utilityResgroupCheckPresence: match RG name %s / ID %d, account ID %d at index %d", item.Name, item.ID, item.AccountID, index) @@ -163,7 +159,7 @@ func utilityResgroupCheckPresence(d *schema.ResourceData, m interface{}) (string } } - return "", fmt.Errorf("Cannot find RG name %s owned by account ID %d", rgName, validatedAccountId) + return "", fmt.Errorf("Cannot find RG name %s owned by account ID %d", rgName, d.Get("account_id").(int)) } func utilityResgroupGetDefaultGridID() (interface{}, error) { @@ -172,4 +168,4 @@ func utilityResgroupGetDefaultGridID() (interface{}, error) { } return "", fmt.Errorf("utilityResgroupGetDefaultGridID: invalid default Grid ID %d", DefaultGridID) - } +} diff --git a/samples/README.md b/samples/README.md index 7a61d08..3b091f7 100644 --- a/samples/README.md +++ b/samples/README.md @@ -25,6 +25,7 @@ - account_disks_list - account_vins_list - account_audits_list + - account - resources: - image - virtual_image diff --git a/samples/data_account/main.tf b/samples/data_account/main.tf new file mode 100644 index 0000000..1cc63dc --- /dev/null +++ b/samples/data_account/main.tf @@ -0,0 +1,39 @@ +/* +Пример использования +Получение информации об аккаунте + +*/ +#Расскомментируйте этот код, +#и внесите необходимые правки в версию и путь, +#чтобы работать с установленным вручную (не через hashicorp provider registry) провайдером +/* +terraform { + required_providers { + decort = { + version = "1.1" + source = "digitalenergy.online/decort/decort" + } + } +} +*/ + +provider "decort" { + authenticator = "oauth2" + #controller_url = + controller_url = "https://ds1.digitalenergy.online" + #oauth2_url = + oauth2_url = "https://sso.digitalenergy.online" + allow_unverified_ssl = true +} + +data "decort_account" "a" { + #id аккаунта + #обязательный параметр + #тип - число + account_id = 28096 + +} + +output "test" { + value = data.decort_account.a +} From 4a326e9ceb45f1fd7dfd9e05ccd13b7981f64c35 Mon Sep 17 00:00:00 2001 From: stSolo Date: Fri, 27 May 2022 12:26:11 +0300 Subject: [PATCH 16/51] Add a resource account --- decort/data_source_account.go | 84 +++- decort/data_source_account_list.go | 58 ++- decort/data_source_rg_list.go | 4 +- decort/models_api.go | 86 ++-- decort/provider.go | 1 + decort/resource_account.go | 729 +++++++++++++++++++++++++++++ decort/utility_account.go | 6 +- decort/utility_account_list.go | 28 ++ samples/resource_account/main.tf | 59 +++ 9 files changed, 1003 insertions(+), 52 deletions(-) create mode 100644 decort/resource_account.go create mode 100644 samples/resource_account/main.tf diff --git a/decort/data_source_account.go b/decort/data_source_account.go index 2db3008..39ef95c 100644 --- a/decort/data_source_account.go +++ b/decort/data_source_account.go @@ -41,7 +41,7 @@ func dataSourceAccountRead(d *schema.ResourceData, m interface{}) error { d.Set("resources", flattenAccResources(acc.Resources)) d.Set("ckey", acc.CKey) d.Set("meta", flattenMeta(acc.Meta)) - d.Set("acl", flattenRgAcl(acc.Acl)) + d.Set("acl", flattenAccAcl(acc.Acl)) d.Set("company", acc.Company) d.Set("companyurl", acc.CompanyUrl) d.Set("created_by", acc.CreatedBy) @@ -60,9 +60,49 @@ func dataSourceAccountRead(d *schema.ResourceData, m interface{}) error { d.Set("updated_time", acc.UpdatedTime) d.Set("version", acc.Version) d.Set("vins", acc.Vins) + d.Set("vinses", acc.Vinses) + d.Set("computes", flattenAccComputes(acc.Computes)) + d.Set("machines", flattenAccMachines(acc.Machines)) return nil } +func flattenAccComputes(acs Computes) []map[string]interface{} { + res := make([]map[string]interface{}, 0) + temp := map[string]interface{}{ + "started": acs.Started, + "stopped": acs.Stopped, + } + res = append(res, temp) + return res +} + +func flattenAccMachines(ams Machines) []map[string]interface{} { + res := make([]map[string]interface{}, 0) + temp := map[string]interface{}{ + "running": ams.Running, + "halted": ams.Halted, + } + res = append(res, temp) + return res +} + +func flattenAccAcl(acls []AccountAclRecord) []map[string]interface{} { + res := make([]map[string]interface{}, 0) + for _, acls := range acls { + temp := map[string]interface{}{ + "can_be_deleted": acls.CanBeDeleted, + "explicit": acls.IsExplicit, + "guid": acls.Guid, + "right": acls.Rights, + "status": acls.Status, + "type": acls.Type, + "user_group_id": acls.UgroupID, + } + res = append(res, temp) + } + return res +} + func flattenAccResources(r Resources) []map[string]interface{} { res := make([]map[string]interface{}, 0) temp := map[string]interface{}{ @@ -188,6 +228,10 @@ func dataSourceAccountSchemaMake() map[string]*schema.Schema { Computed: true, Elem: &schema.Resource{ Schema: map[string]*schema.Schema{ + "can_be_deleted": { + Type: schema.TypeBool, + Computed: true, + }, "explicit": { Type: schema.TypeBool, Computed: true, @@ -315,6 +359,44 @@ func dataSourceAccountSchemaMake() map[string]*schema.Schema { Type: schema.TypeInt, }, }, + "computes": { + Type: schema.TypeList, + Computed: true, + MaxItems: 1, + Elem: &schema.Resource{ + Schema: map[string]*schema.Schema{ + "started": { + Type: schema.TypeInt, + Computed: true, + }, + "stopped": { + Type: schema.TypeInt, + Computed: true, + }, + }, + }, + }, + "machines": { + Type: schema.TypeList, + Computed: true, + MaxItems: 1, + Elem: &schema.Resource{ + Schema: map[string]*schema.Schema{ + "halted": { + Type: schema.TypeInt, + Computed: true, + }, + "running": { + Type: schema.TypeInt, + Computed: true, + }, + }, + }, + }, + "vinses": { + Type: schema.TypeInt, + Computed: true, + }, } return res } diff --git a/decort/data_source_account_list.go b/decort/data_source_account_list.go index 866f232..b587bda 100644 --- a/decort/data_source_account_list.go +++ b/decort/data_source_account_list.go @@ -29,6 +29,24 @@ import ( "github.com/hashicorp/terraform-plugin-sdk/helper/schema" ) +func flattenAccountList(al AccountCloudApiList) []map[string]interface{} { + res := make([]map[string]interface{}, 0) + for _, acc := range al { + temp := map[string]interface{}{ + "acl": flattenRgAcl(acc.Acl), + "created_time": acc.CreatedTime, + "deleted_time": acc.DeletedTime, + "account_id": acc.ID, + "account_name": acc.Name, + "status": acc.Status, + "updated_time": acc.UpdatedTime, + } + res = append(res, temp) + } + return res +} + +/*uncomment for cloudbroker func flattenAccountList(al AccountList) []map[string]interface{} { res := make([]map[string]interface{}, 0) for _, acc := range al { @@ -36,31 +54,42 @@ func flattenAccountList(al AccountList) []map[string]interface{} { "dc_location": acc.DCLocation, "ckey": acc.CKey, "meta": flattenMeta(acc.Meta), - "acl": flattenRgAcl(acc.Acl), + + "acl": flattenRgAcl(acc.Acl), + "company": acc.Company, "companyurl": acc.CompanyUrl, "created_by": acc.CreatedBy, - "created_time": acc.CreatedTime, + + "created_time": acc.CreatedTime, + "deactivation_time": acc.DeactiovationTime, "deleted_by": acc.DeletedBy, - "deleted_time": acc.DeletedTime, + + "deleted_time": acc.DeletedTime, + "displayname": acc.DisplayName, "guid": acc.GUID, - "account_id": acc.ID, - "account_name": acc.Name, + + "account_id": acc.ID, + "account_name": acc.Name, + "resource_limits": flattenRgResourceLimits(acc.ResourceLimits), "send_access_emails": acc.SendAccessEmails, "service_account": acc.ServiceAccount, - "status": acc.Status, - "updated_time": acc.UpdatedTime, + + "status": acc.Status, + "updated_time": acc.UpdatedTime, + "version": acc.Version, "vins": acc.Vins, + } res = append(res, temp) } return res - } +*/ func dataSourceAccountListRead(d *schema.ResourceData, m interface{}) error { accountList, err := utilityAccountListCheckPresence(d, m) @@ -92,6 +121,7 @@ func dataSourceAccountListSchemaMake() map[string]*schema.Schema { Computed: true, Elem: &schema.Resource{ Schema: map[string]*schema.Schema{ + /*uncomment for cloudbroker "dc_location": { Type: schema.TypeString, Computed: true, @@ -106,7 +136,7 @@ func dataSourceAccountListSchemaMake() map[string]*schema.Schema { Elem: &schema.Schema{ Type: schema.TypeString, }, - }, + },*/ "acl": { Type: schema.TypeList, Computed: true, @@ -139,6 +169,7 @@ func dataSourceAccountListSchemaMake() map[string]*schema.Schema { }, }, }, + /*uncomment for cloudbroker "company": { Type: schema.TypeString, Computed: true, @@ -151,10 +182,12 @@ func dataSourceAccountListSchemaMake() map[string]*schema.Schema { Type: schema.TypeString, Computed: true, }, + */ "created_time": { Type: schema.TypeInt, Computed: true, }, + /*uncomment for cloudbroker "deactivation_time": { Type: schema.TypeFloat, Computed: true, @@ -163,10 +196,12 @@ func dataSourceAccountListSchemaMake() map[string]*schema.Schema { Type: schema.TypeString, Computed: true, }, + */ "deleted_time": { Type: schema.TypeInt, Computed: true, }, + /*uncomment for cloudbroker "displayname": { Type: schema.TypeString, Computed: true, @@ -175,6 +210,7 @@ func dataSourceAccountListSchemaMake() map[string]*schema.Schema { Type: schema.TypeInt, Computed: true, }, + */ "account_id": { Type: schema.TypeInt, Computed: true, @@ -183,6 +219,7 @@ func dataSourceAccountListSchemaMake() map[string]*schema.Schema { Type: schema.TypeString, Computed: true, }, + /*uncomment for cloudbroker "resource_limits": { Type: schema.TypeList, Computed: true, @@ -224,6 +261,7 @@ func dataSourceAccountListSchemaMake() map[string]*schema.Schema { Type: schema.TypeBool, Computed: true, }, + */ "status": { Type: schema.TypeString, Computed: true, @@ -232,6 +270,7 @@ func dataSourceAccountListSchemaMake() map[string]*schema.Schema { Type: schema.TypeInt, Computed: true, }, + /*uncomment for cloudbroker "version": { Type: schema.TypeInt, Computed: true, @@ -243,6 +282,7 @@ func dataSourceAccountListSchemaMake() map[string]*schema.Schema { Type: schema.TypeInt, }, }, + */ }, }, }, diff --git a/decort/data_source_rg_list.go b/decort/data_source_rg_list.go index 9220693..73afce5 100644 --- a/decort/data_source_rg_list.go +++ b/decort/data_source_rg_list.go @@ -1,6 +1,6 @@ /* -Copyright (c) 2019-2021 Digital Energy Cloud Solutions LLC. All Rights Reserved. -Author: Sergey Shubin, , +Copyright (c) 2019-2022 Digital Energy Cloud Solutions LLC. All Rights Reserved. +Author: Stanislav Solovev, Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. diff --git a/decort/models_api.go b/decort/models_api.go index 3c07f8b..80b5ffd 100644 --- a/decort/models_api.go +++ b/decort/models_api.go @@ -51,12 +51,13 @@ type UserAclRecord struct { } type AccountAclRecord struct { - IsExplicit bool `json:"explicit"` - Guid string `json:"guid"` - Rights string `json:"right"` - Status string `json:"status"` - Type string `json:"type"` - UgroupID string `json:"userGroupId"` + IsExplicit bool `json:"explicit"` + Guid string `json:"guid"` + Rights string `json:"right"` + Status string `json:"status"` + Type string `json:"type"` + UgroupID string `json:"userGroupId"` + CanBeDeleted bool `json:"canBeDeleted"` } type ResourceLimits struct { @@ -992,46 +993,28 @@ type SepPool map[string]interface{} ///// ACCOUNTS //// /////////////////////// -const accountAddUserAPI = "/cloudapi/account/addUser" - -//const accountAuditsAPI = "/restmachine/cloudapi/account/audits" -const accountAuditsAPI = "/restmachine/cloudbroker/account/audits" -const accountCreateAPI = "/cloudapi/account/create" -const accountDeleteAPI = "/cloudapi/account/delete" +const accountAddUserAPI = "/restmachine/cloudapi/account/addUser" +const accountAuditsAPI = "/restmachine/cloudapi/account/audits" +const accountCreateAPI = "/restmachine/cloudapi/account/create" +const accountDeleteAPI = "/restmachine/cloudapi/account/delete" const accountDeleteAccountsAPI = "/cloudapi/account/deleteAccounts" -const accountDeleteUserAPI = "/cloudapi/account/deleteUser" -const accountDisableAPI = "/cloudapi/account/disable" -const accountEnableAPI = "/cloudapi/account/enable" - -//const accountGetAPI = "/restmachine/cloudapi/account/get" -const accountGetAPI = "/restmachine/cloudbroker/account/get" -const accountGetConsumedAccountUnitsAPI = "/cloudapi/account/getConsumedAccountUnits" -const accountGetConsumedCloudUnitsByTypeAPI = "/cloudapi/account/getConsumedCloudUnitsByType" -const accountGetConsumptionGetAPI = "/cloudapi/account/getConsumption" -const accountGetConsumptionPostAPI = "/cloudapi/account/getConsumption" -const accountGetReservedAccountUnitsAPI = "/cloudapi/account/getReservedAccountUnits" -const accountGetStatsAPI = "/cloudapi/account/getStats" - -//const accountListAPI = "/restmachine/cloudapi/account/list" -const accountListAPI = "/restmachine/cloudbroker/account/list" - -//const accountListComputesAPI = "/restmachine/cloudapi/account/listComputes" -const accountListComputesAPI = "/restmachine/cloudbroker/account/listComputes" +const accountDeleteUserAPI = "/restmachine/cloudapi/account/deleteUser" +const accountDisableAPI = "/restmachine/cloudapi/account/disable" +const accountEnableAPI = "/restmachine/cloudapi/account/enable" +const accountGetAPI = "/restmachine/cloudapi/account/get" +const accountListAPI = "/restmachine/cloudapi/account/list" +const accountListComputesAPI = "/restmachine/cloudapi/account/listComputes" const accountListCSAPI = "/cloudapi/account/listCS" const accountListDeletedAPI = "/cloudapi/account/listDeleted" - -//const accountListDisksAPI = "/restmachine/cloudapi/account/listDisks" -const accountListDisksAPI = "/restmachine/cloudbroker/account/listDisks" +const accountListDisksAPI = "/restmachine/cloudapi/account/listDisks" const accountListFlipGroupsAPI = "/cloudapi/account/listFlipGroups" const accountListRGAPI = "/cloudapi/account/listRG" const accountListTemplatesAPI = "/cloudapi/account/listTemplates" - -//const accountListVinsAPI = "/restmachine/cloudapi/account/listVins" -const accountListVinsAPI = "/restmachine/cloudbroker/account/listVins" +const accountListVinsAPI = "/restmachine/cloudapi/account/listVins" const accountListVMsAPI = "/cloudapi/account/listVMs" -const accountRestoreAPI = "/cloudapi/account/restore" -const accountUpdateAPI = "/cloudapi/account/update" -const accountUpdateUserAPI = "/cloudapi/account/updateUser" +const accountRestoreAPI = "/restmachine/cloudapi/account/restore" +const accountUpdateAPI = "/restmachine/cloudapi/account/update" +const accountUpdateUserAPI = "/restmachine/cloudapi/account/updateUser" ////Structs @@ -1062,6 +1045,18 @@ type Account struct { type AccountList []Account +type AccountCloudApi struct { + Acl []AccountAclRecord `json:"acl"` + CreatedTime int `json:"createdTime"` + DeletedTime int `json:"deletedTime"` + ID int `json:"id"` + Name string `json:"name"` + Status string `json:"status"` + UpdatedTime int `json:"updatedTime"` +} + +type AccountCloudApiList []AccountCloudApi + type Resource struct { CPU int `json:"cpu"` Disksize int `json:"disksize"` @@ -1076,9 +1071,22 @@ type Resources struct { Reserved Resource `json:"Reserved"` } +type Computes struct { + Started int `json:"started"` + Stopped int `json:"stopped"` +} + +type Machines struct { + Running int `json:"running"` + Halted int `json:"halted"` +} + type AccountWithResources struct { Account Resources Resources `json:"Resources"` + Computes Computes `json:"computes"` + Machines Machines `json:"machines"` + Vinses int `json:"vinses"` } type AccountCompute struct { diff --git a/decort/provider.go b/decort/provider.go index b2f9e45..7145229 100644 --- a/decort/provider.go +++ b/decort/provider.go @@ -114,6 +114,7 @@ func Provider() *schema.Provider { "decort_pcidevice": resourcePcidevice(), "decort_sep": resourceSep(), "decort_sep_config": resourceSepConfig(), + "decort_account": resourceAccount(), }, DataSourcesMap: map[string]*schema.Resource{ diff --git a/decort/resource_account.go b/decort/resource_account.go new file mode 100644 index 0000000..05cd238 --- /dev/null +++ b/decort/resource_account.go @@ -0,0 +1,729 @@ +/* +Copyright (c) 2019-2022 Digital Energy Cloud Solutions LLC. All Rights Reserved. +Author: Stanislav Solovev, + +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. +*/ + +/* +This file is part of Terraform (by Hashicorp) provider for Digital Energy Cloud Orchestration +Technology platfom. + +Visit https://github.com/rudecs/terraform-provider-decort for full source code package and updates. +*/ + +package decort + +import ( + "errors" + "net/url" + "strconv" + "strings" + + "github.com/google/uuid" + "github.com/hashicorp/terraform-plugin-sdk/helper/schema" + log "github.com/sirupsen/logrus" +) + +func resourceAccountCreate(d *schema.ResourceData, m interface{}) error { + log.Debugf("resourceAccountCreate") + + if accountId, ok := d.GetOk("account_id"); ok { + if exists, err := resourceAccountExists(d, m); exists { + if err != nil { + return err + } + d.SetId(strconv.Itoa(accountId.(int))) + err = resourceAccountRead(d, m) + if err != nil { + return err + } + + return nil + } + return errors.New("provided sep id does not exist") + } + + controller := m.(*ControllerCfg) + urlValues := &url.Values{} + + urlValues.Add("name", d.Get("account_name").(string)) + urlValues.Add("username", d.Get("username").(string)) + + if emailaddress, ok := d.GetOk("emailaddress"); ok { + urlValues.Add("emailaddress", emailaddress.(string)) + } + if sendAccessEmails, ok := d.GetOk("send_access_emails"); ok { + urlValues.Add("sendAccessEmails", strconv.FormatBool(sendAccessEmails.(bool))) + } + if resLimits, ok := d.GetOk("resource_limits"); ok { + resLimit := resLimits.([]interface{})[0] + resLimitConv := resLimit.(map[string]interface{}) + + if resLimitConv["cu_m"] != nil { + urlValues.Add("maxMemoryCapacity", strconv.Itoa(int(resLimitConv["cu_m"].(float64)))) + } + if resLimitConv["cu_d"] != nil { + urlValues.Add("maxVDiskCapacity", strconv.Itoa(int(resLimitConv["cu_d"].(float64)))) + } + if resLimitConv["cu_c"] != nil { + urlValues.Add("maxCPUCapacity", strconv.Itoa(int(resLimitConv["cu_c"].(float64)))) + } + if resLimitConv["cu_i"] != nil { + urlValues.Add("maxNumPublicIP", strconv.Itoa(int(resLimitConv["cu_i"].(float64)))) + } + if resLimitConv["cu_np"] != nil { + urlValues.Add("maxNetworkPeerTransfer", strconv.Itoa(int(resLimitConv["cu_np"].(float64)))) + } + if resLimitConv["gpu_units"] != nil { + urlValues.Add("gpu_units", strconv.Itoa(int(resLimitConv["gpu_units"].(float64)))) + } + } + + accountId, err := controller.decortAPICall("POST", accountCreateAPI, urlValues) + if err != nil { + return err + } + + id := uuid.New() + d.SetId(accountId) + d.Set("account_id", accountId) + + err = resourceAccountRead(d, m) + if err != nil { + return err + } + + d.SetId(id.String()) + + return nil +} + +func resourceAccountRead(d *schema.ResourceData, m interface{}) error { + log.Debugf("resourceSepRead") + + acc, err := utilityAccountCheckPresence(d, m) + if acc == nil { + d.SetId("") + return err + } + + d.Set("dc_location", acc.DCLocation) + d.Set("resources", flattenAccResources(acc.Resources)) + d.Set("ckey", acc.CKey) + d.Set("meta", flattenMeta(acc.Meta)) + d.Set("acl", flattenAccAcl(acc.Acl)) + d.Set("company", acc.Company) + d.Set("companyurl", acc.CompanyUrl) + d.Set("created_by", acc.CreatedBy) + d.Set("created_time", acc.CreatedTime) + d.Set("deactivation_time", acc.DeactiovationTime) + d.Set("deleted_by", acc.DeletedBy) + d.Set("deleted_time", acc.DeletedTime) + d.Set("displayname", acc.DisplayName) + d.Set("guid", acc.GUID) + d.Set("account_id", acc.ID) + d.Set("account_name", acc.Name) + d.Set("resource_limits", flattenRgResourceLimits(acc.ResourceLimits)) + d.Set("send_access_emails", acc.SendAccessEmails) + d.Set("service_account", acc.ServiceAccount) + d.Set("status", acc.Status) + d.Set("updated_time", acc.UpdatedTime) + d.Set("version", acc.Version) + d.Set("vins", acc.Vins) + d.Set("vinses", acc.Vinses) + d.Set("computes", flattenAccComputes(acc.Computes)) + d.Set("machines", flattenAccMachines(acc.Machines)) + + return nil +} + +func resourceAccountDelete(d *schema.ResourceData, m interface{}) error { + log.Debugf("resourceAccountDelete") + + account, err := utilityAccountCheckPresence(d, m) + if account == nil { + if err != nil { + return err + } + return nil + } + + controller := m.(*ControllerCfg) + urlValues := &url.Values{} + urlValues.Add("accountId", strconv.Itoa(d.Get("account_id").(int))) + urlValues.Add("permanently", strconv.FormatBool(d.Get("permanently").(bool))) + + _, err = controller.decortAPICall("POST", accountDeleteAPI, urlValues) + if err != nil { + return err + } + d.SetId("") + + return nil +} + +func resourceAccountExists(d *schema.ResourceData, m interface{}) (bool, error) { + log.Debugf("resourceAccountExists") + + account, err := utilityAccountCheckPresence(d, m) + if account == nil { + if err != nil { + return false, err + } + return false, nil + } + + return true, nil +} + +func resourceAccountEdit(d *schema.ResourceData, m interface{}) error { + log.Debugf("resourceAccountEdit") + c := m.(*ControllerCfg) + + urlValues := &url.Values{} + if d.HasChange("enable") { + api := accountDisableAPI + enable := d.Get("enable").(bool) + if enable { + api = accountEnableAPI + } + urlValues.Add("accountId", strconv.Itoa(d.Get("account_id").(int))) + + _, err := c.decortAPICall("POST", api, urlValues) + if err != nil { + return err + } + + urlValues = &url.Values{} + } + + if d.HasChange("account_name") { + urlValues.Add("name", d.Get("account_name").(string)) + urlValues.Add("accountId", strconv.Itoa(d.Get("account_id").(int))) + _, err := c.decortAPICall("POST", accountUpdateAPI, urlValues) + if err != nil { + return err + } + + urlValues = &url.Values{} + } + if d.HasChange("resource_limits") { + resLimit := d.Get("resource_limits").([]interface{})[0] + resLimitConv := resLimit.(map[string]interface{}) + + if resLimitConv["cu_m"] != nil { + urlValues.Add("maxMemoryCapacity", strconv.Itoa(int(resLimitConv["cu_m"].(float64)))) + } + if resLimitConv["cu_d"] != nil { + urlValues.Add("maxVDiskCapacity", strconv.Itoa(int(resLimitConv["cu_d"].(float64)))) + } + if resLimitConv["cu_c"] != nil { + urlValues.Add("maxCPUCapacity", strconv.Itoa(int(resLimitConv["cu_c"].(float64)))) + } + if resLimitConv["cu_i"] != nil { + urlValues.Add("maxNumPublicIP", strconv.Itoa(int(resLimitConv["cu_i"].(float64)))) + } + if resLimitConv["cu_np"] != nil { + urlValues.Add("maxNetworkPeerTransfer", strconv.Itoa(int(resLimitConv["cu_np"].(float64)))) + } + if resLimitConv["gpu_units"] != nil { + urlValues.Add("gpu_units", strconv.Itoa(int(resLimitConv["gpu_units"].(float64)))) + } + + urlValues.Add("accountId", strconv.Itoa(d.Get("account_id").(int))) + _, err := c.decortAPICall("POST", accountUpdateAPI, urlValues) + if err != nil { + return err + } + + urlValues = &url.Values{} + } + + if d.HasChange("send_access_emails") { + urlValues.Add("sendAccessEmails", strconv.FormatBool(d.Get("send_access_emails").(bool))) + urlValues.Add("accountId", strconv.Itoa(d.Get("account_id").(int))) + _, err := c.decortAPICall("POST", accountUpdateAPI, urlValues) + if err != nil { + return err + } + + urlValues = &url.Values{} + } + + if d.HasChange("restore") { + restore := d.Get("restore").(bool) + if restore { + urlValues.Add("accountId", strconv.Itoa(d.Get("account_id").(int))) + _, err := c.decortAPICall("POST", accountRestoreAPI, urlValues) + if err != nil { + return err + } + + urlValues = &url.Values{} + } + } + + if d.HasChange("users") { + deletedUsers := make([]interface{}, 0) + addedUsers := make([]interface{}, 0) + updatedUsers := make([]interface{}, 0) + + old, new := d.GetChange("users") + oldConv := old.([]interface{}) + newConv := new.([]interface{}) + for _, el := range oldConv { + if !isContainsUser(newConv, el) { + deletedUsers = append(deletedUsers, el) + } + } + for _, el := range newConv { + if !isContainsUser(oldConv, el) { + addedUsers = append(addedUsers, el) + } else { + if isChangedUser(oldConv, el) { + updatedUsers = append(updatedUsers, el) + } + } + } + + if len(deletedUsers) > 0 { + for _, user := range deletedUsers { + userConv := user.(map[string]interface{}) + urlValues.Add("accountId", strconv.Itoa(d.Get("account_id").(int))) + urlValues.Add("userId", userConv["user_id"].(string)) + urlValues.Add("recursivedelete", strconv.FormatBool(userConv["recursive_delete"].(bool))) + _, err := c.decortAPICall("POST", accountDeleteUserAPI, urlValues) + if err != nil { + return err + } + + urlValues = &url.Values{} + } + } + + if len(addedUsers) > 0 { + for _, user := range addedUsers { + userConv := user.(map[string]interface{}) + urlValues.Add("accountId", strconv.Itoa(d.Get("account_id").(int))) + urlValues.Add("userId", userConv["user_id"].(string)) + urlValues.Add("accesstype", strings.ToUpper(userConv["access_type"].(string))) + _, err := c.decortAPICall("POST", accountAddUserAPI, urlValues) + if err != nil { + return err + } + + urlValues = &url.Values{} + } + } + + if len(updatedUsers) > 0 { + for _, user := range updatedUsers { + userConv := user.(map[string]interface{}) + urlValues.Add("accountId", strconv.Itoa(d.Get("account_id").(int))) + urlValues.Add("userId", userConv["user_id"].(string)) + urlValues.Add("accesstype", strings.ToUpper(userConv["access_type"].(string))) + _, err := c.decortAPICall("POST", accountUpdateUserAPI, urlValues) + if err != nil { + return err + } + + urlValues = &url.Values{} + } + } + + } + + return nil +} + +func isContainsUser(els []interface{}, el interface{}) bool { + for _, elOld := range els { + elOldConv := elOld.(map[string]interface{}) + elConv := el.(map[string]interface{}) + if elOldConv["user_id"].(string) == elConv["user_id"].(string) { + return true + } + } + return false +} + +func isChangedUser(els []interface{}, el interface{}) bool { + for _, elOld := range els { + elOldConv := elOld.(map[string]interface{}) + elConv := el.(map[string]interface{}) + if elOldConv["user_id"].(string) == elConv["user_id"].(string) && + (strings.ToUpper(elOldConv["access_type"].(string)) != strings.ToUpper(elConv["access_type"].(string)) || + elOldConv["recursive_delete"].(bool) != elConv["recursive_delete"].(bool)) { + return true + } + } + return false +} + +func resourceAccountSchemaMake() map[string]*schema.Schema { + return map[string]*schema.Schema{ + "account_name": { + Type: schema.TypeString, + Required: true, + Description: "account name", + }, + "username": { + Type: schema.TypeString, + Required: true, + Description: "username of owner the account", + }, + "emailaddress": { + Type: schema.TypeString, + Optional: true, + Description: "email", + }, + "send_access_emails": { + Type: schema.TypeBool, + Optional: true, + Default: true, + Description: "if true send emails when a user is granted access to resources", + }, + "users": { + Type: schema.TypeList, + Optional: true, + Elem: &schema.Resource{ + Schema: map[string]*schema.Schema{ + "user_id": { + Type: schema.TypeString, + Required: true, + }, + "access_type": { + Type: schema.TypeString, + Required: true, + }, + "recursive_delete": { + Type: schema.TypeBool, + Optional: true, + Default: false, + }, + }, + }, + }, + "restore": { + Type: schema.TypeBool, + Optional: true, + Description: "restore a deleted account", + }, + "permanently": { + Type: schema.TypeBool, + Optional: true, + Default: false, + Description: "whether to completely delete the account", + }, + "enable": { + Type: schema.TypeBool, + Optional: true, + Description: "enable/disable account", + }, + "resource_limits": { + Type: schema.TypeList, + Optional: true, + Computed: true, + MaxItems: 1, + Elem: &schema.Resource{ + Schema: map[string]*schema.Schema{ + "cu_c": { + Type: schema.TypeFloat, + Optional: true, + Computed: true, + }, + "cu_d": { + Type: schema.TypeFloat, + Optional: true, + Computed: true, + }, + "cu_i": { + Type: schema.TypeFloat, + Optional: true, + Computed: true, + }, + "cu_m": { + Type: schema.TypeFloat, + Optional: true, + Computed: true, + }, + "cu_np": { + Type: schema.TypeFloat, + Optional: true, + Computed: true, + }, + "gpu_units": { + Type: schema.TypeFloat, + Optional: true, + Computed: true, + }, + }, + }, + }, + "account_id": { + Type: schema.TypeInt, + Optional: true, + Computed: true, + }, + "dc_location": { + Type: schema.TypeString, + Computed: true, + }, + "resources": { + Type: schema.TypeList, + Computed: true, + MaxItems: 1, + Elem: &schema.Resource{ + Schema: map[string]*schema.Schema{ + "current": { + Type: schema.TypeList, + Computed: true, + MaxItems: 1, + Elem: &schema.Resource{ + Schema: map[string]*schema.Schema{ + "cpu": { + Type: schema.TypeInt, + Computed: true, + }, + "disksize": { + Type: schema.TypeInt, + Computed: true, + }, + "extips": { + Type: schema.TypeInt, + Computed: true, + }, + "exttraffic": { + Type: schema.TypeInt, + Computed: true, + }, + "gpu": { + Type: schema.TypeInt, + Computed: true, + }, + "ram": { + Type: schema.TypeInt, + Computed: true, + }, + }, + }, + }, + "reserved": { + Type: schema.TypeList, + Computed: true, + MaxItems: 1, + Elem: &schema.Resource{ + Schema: map[string]*schema.Schema{ + "cpu": { + Type: schema.TypeInt, + Computed: true, + }, + "disksize": { + Type: schema.TypeInt, + Computed: true, + }, + "extips": { + Type: schema.TypeInt, + Computed: true, + }, + "exttraffic": { + Type: schema.TypeInt, + Computed: true, + }, + "gpu": { + Type: schema.TypeInt, + Computed: true, + }, + "ram": { + Type: schema.TypeInt, + Computed: true, + }, + }, + }, + }, + }, + }, + }, + "ckey": { + Type: schema.TypeString, + Computed: true, + }, + "meta": { + Type: schema.TypeList, + Computed: true, + Elem: &schema.Schema{ + Type: schema.TypeString, + }, + }, + "acl": { + Type: schema.TypeList, + Computed: true, + Elem: &schema.Resource{ + Schema: map[string]*schema.Schema{ + "can_be_deleted": { + Type: schema.TypeBool, + Computed: true, + }, + "explicit": { + Type: schema.TypeBool, + Computed: true, + }, + "guid": { + Type: schema.TypeString, + Computed: true, + }, + "right": { + Type: schema.TypeString, + Computed: true, + }, + "status": { + Type: schema.TypeString, + Computed: true, + }, + "type": { + Type: schema.TypeString, + Computed: true, + }, + "user_group_id": { + Type: schema.TypeString, + Computed: true, + }, + }, + }, + }, + "company": { + Type: schema.TypeString, + Computed: true, + }, + "companyurl": { + Type: schema.TypeString, + Computed: true, + }, + "created_by": { + Type: schema.TypeString, + Computed: true, + }, + "created_time": { + Type: schema.TypeInt, + Computed: true, + }, + "deactivation_time": { + Type: schema.TypeFloat, + Computed: true, + }, + "deleted_by": { + Type: schema.TypeString, + Computed: true, + }, + "deleted_time": { + Type: schema.TypeInt, + Computed: true, + }, + "displayname": { + Type: schema.TypeString, + Computed: true, + }, + "guid": { + Type: schema.TypeInt, + Computed: true, + }, + "service_account": { + Type: schema.TypeBool, + Computed: true, + }, + "status": { + Type: schema.TypeString, + Computed: true, + }, + "updated_time": { + Type: schema.TypeInt, + Computed: true, + }, + "version": { + Type: schema.TypeInt, + Computed: true, + }, + "vins": { + Type: schema.TypeList, + Computed: true, + Elem: &schema.Schema{ + Type: schema.TypeInt, + }, + }, + "computes": { + Type: schema.TypeList, + Computed: true, + MaxItems: 1, + Elem: &schema.Resource{ + Schema: map[string]*schema.Schema{ + "started": { + Type: schema.TypeInt, + Computed: true, + }, + "stopped": { + Type: schema.TypeInt, + Computed: true, + }, + }, + }, + }, + "machines": { + Type: schema.TypeList, + Computed: true, + MaxItems: 1, + Elem: &schema.Resource{ + Schema: map[string]*schema.Schema{ + "halted": { + Type: schema.TypeInt, + Computed: true, + }, + "running": { + Type: schema.TypeInt, + Computed: true, + }, + }, + }, + }, + "vinses": { + Type: schema.TypeInt, + Computed: true, + }, + } +} + +func resourceAccount() *schema.Resource { + return &schema.Resource{ + SchemaVersion: 1, + + Create: resourceAccountCreate, + Read: resourceAccountRead, + Update: resourceAccountEdit, + Delete: resourceAccountDelete, + Exists: resourceAccountExists, + + Importer: &schema.ResourceImporter{ + State: schema.ImportStatePassthrough, + }, + + Timeouts: &schema.ResourceTimeout{ + Create: &Timeout60s, + Read: &Timeout30s, + Update: &Timeout60s, + Delete: &Timeout60s, + Default: &Timeout60s, + }, + + Schema: resourceAccountSchemaMake(), + } +} diff --git a/decort/utility_account.go b/decort/utility_account.go index f2b5e2e..136a939 100644 --- a/decort/utility_account.go +++ b/decort/utility_account.go @@ -39,7 +39,11 @@ func utilityAccountCheckPresence(d *schema.ResourceData, m interface{}) (*Accoun controller := m.(*ControllerCfg) urlValues := &url.Values{} - urlValues.Add("accountId", strconv.Itoa(d.Get("account_id").(int))) + if (strconv.Itoa(d.Get("account_id").(int))) != "0" { + urlValues.Add("accountId", strconv.Itoa(d.Get("account_id").(int))) + } else { + urlValues.Add("accountId", d.Id()) + } log.Debugf("utilityAccountCheckPresence: load account") accountRaw, err := controller.decortAPICall("POST", accountGetAPI, urlValues) diff --git a/decort/utility_account_list.go b/decort/utility_account_list.go index 828ecf9..0dd3514 100644 --- a/decort/utility_account_list.go +++ b/decort/utility_account_list.go @@ -34,6 +34,33 @@ import ( "github.com/hashicorp/terraform-plugin-sdk/helper/schema" ) +func utilityAccountListCheckPresence(d *schema.ResourceData, m interface{}) (AccountCloudApiList, error) { + accountList := AccountCloudApiList{} + controller := m.(*ControllerCfg) + urlValues := &url.Values{} + + if page, ok := d.GetOk("page"); ok { + urlValues.Add("page", strconv.Itoa(page.(int))) + } + if size, ok := d.GetOk("size"); ok { + urlValues.Add("size", strconv.Itoa(size.(int))) + } + + log.Debugf("utilityAccountListCheckPresence: load account list") + accountListRaw, err := controller.decortAPICall("POST", accountListAPI, urlValues) + if err != nil { + return nil, err + } + + err = json.Unmarshal([]byte(accountListRaw), &accountList) + if err != nil { + return nil, err + } + + return accountList, nil +} + +/*uncomment for cloudbroker func utilityAccountListCheckPresence(d *schema.ResourceData, m interface{}) (AccountList, error) { accountList := AccountList{} controller := m.(*ControllerCfg) @@ -59,3 +86,4 @@ func utilityAccountListCheckPresence(d *schema.ResourceData, m interface{}) (Acc return accountList, nil } +*/ diff --git a/samples/resource_account/main.tf b/samples/resource_account/main.tf new file mode 100644 index 0000000..1b456be --- /dev/null +++ b/samples/resource_account/main.tf @@ -0,0 +1,59 @@ +/* +Пример использования +Ресурса cdrom image +Ресурс позволяет: +1. Создавать образ +2. Редактировать образ +3. Удалять образ + +*/ +#Расскомментируйте этот код, +#и внесите необходимые правки в версию и путь, +#чтобы работать с установленным вручную (не через hashicorp provider registry) провайдером + +terraform { + required_providers { + decort = { + version = "1.1" + source = "digitalenergy.online/decort/decort" + } + } +} + + +provider "decort" { + authenticator = "oauth2" + #controller_url = + controller_url = "https://ds1.digitalenergy.online" + #oauth2_url = + oauth2_url = "https://sso.digitalenergy.online" + allow_unverified_ssl = true +} + +resource "decort_account" "a" { + #id аккаунта + #обязательный параметр + #тип - число + account_id = 11111 + account_name = "new_my_account" + username = "isername@decs3o" + enable = true + send_access_emails = true + /*users { + user_id = "username_2@decs3o" + access_type = "R" + } + users { + user_id = "username_1@decs3o" + access_type = "R" + }*/ + resource_limits { + cu_m = 1024 + } + + +} + +output "test" { + value = decort_account.a +} From 9f5b4ab771b7200f29b47f02ace3b16472ef653b Mon Sep 17 00:00:00 2001 From: stSolo Date: Fri, 27 May 2022 13:48:58 +0300 Subject: [PATCH 17/51] Add a data for account rg list --- decort/data_source_account_rg_list.go | 294 ++++++++++++++++++++++++++ decort/models_api.go | 31 ++- decort/provider.go | 1 + decort/utility_account_rg_list.go | 56 +++++ samples/README.md | 2 + samples/data_account_rg_list/main.tf | 37 ++++ 6 files changed, 420 insertions(+), 1 deletion(-) create mode 100644 decort/data_source_account_rg_list.go create mode 100644 decort/utility_account_rg_list.go create mode 100644 samples/data_account_rg_list/main.tf diff --git a/decort/data_source_account_rg_list.go b/decort/data_source_account_rg_list.go new file mode 100644 index 0000000..40e2284 --- /dev/null +++ b/decort/data_source_account_rg_list.go @@ -0,0 +1,294 @@ +/* +Copyright (c) 2019-2022 Digital Energy Cloud Solutions LLC. All Rights Reserved. +Author: Stanislav Solovev, + +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. +*/ + +/* +This file is part of Terraform (by Hashicorp) provider for Digital Energy Cloud Orchestration +Technology platfom. + +Visit https://github.com/rudecs/terraform-provider-decort for full source code package and updates. +*/ + +package decort + +import ( + "github.com/google/uuid" + "github.com/hashicorp/terraform-plugin-sdk/helper/schema" +) + +func flattenAccountRGList(argl AccountRGList) []map[string]interface{} { + res := make([]map[string]interface{}, 0) + for _, arg := range argl { + temp := map[string]interface{}{ + "computes": flattenAccRGComputes(arg.Computes), + "resources": flattenAccRGResources(arg.Resources), + "created_by": arg.CreatedBy, + "created_time": arg.CreatedTime, + "deleted_by": arg.DeletedBy, + "deleted_time": arg.DeletedTime, + "rg_id": arg.RGID, + "milestones": arg.Milestones, + "rg_name": arg.RGName, + "status": arg.Status, + "updated_by": arg.UpdatedBy, + "updated_time": arg.UpdatedTime, + "vinses": arg.Vinses, + } + res = append(res, temp) + } + return res + +} + +func flattenAccRGComputes(argc AccountRGComputes) []map[string]interface{} { + res := make([]map[string]interface{}, 0) + temp := map[string]interface{}{ + "started": argc.Started, + "stopped": argc.Stopped, + } + res = append(res, temp) + return res +} + +func flattenAccRGResources(argr AccountRGResources) []map[string]interface{} { + res := make([]map[string]interface{}, 0) + temp := map[string]interface{}{ + "consumed": flattenAccResource(argr.Consumed), + "limits": flattenAccResource(argr.Limits), + "reserved": flattenAccResource(argr.Reserved), + } + res = append(res, temp) + return res +} + +func dataSourceAccountRGListRead(d *schema.ResourceData, m interface{}) error { + accountRGList, err := utilityAccountRGListCheckPresence(d, m) + if err != nil { + return err + } + + id := uuid.New() + d.SetId(id.String()) + d.Set("items", flattenAccountRGList(accountRGList)) + + return nil +} + +func dataSourceAccountRGListSchemaMake() map[string]*schema.Schema { + res := map[string]*schema.Schema{ + "account_id": { + Type: schema.TypeInt, + Required: true, + Description: "ID of the account", + }, + "items": { + Type: schema.TypeList, + Computed: true, + Description: "Search Result", + Elem: &schema.Resource{ + Schema: map[string]*schema.Schema{ + "computes": { + Type: schema.TypeList, + MaxItems: 1, + Computed: true, + Elem: &schema.Resource{ + Schema: map[string]*schema.Schema{ + "started": { + Type: schema.TypeInt, + Computed: true, + }, + "stopped": { + Type: schema.TypeInt, + Computed: true, + }, + }, + }, + }, + "resources": { + Type: schema.TypeList, + Computed: true, + MaxItems: 1, + Elem: &schema.Resource{ + Schema: map[string]*schema.Schema{ + "consumed": { + Type: schema.TypeList, + Computed: true, + MaxItems: 1, + Elem: &schema.Resource{ + Schema: map[string]*schema.Schema{ + "cpu": { + Type: schema.TypeInt, + Computed: true, + }, + "disksize": { + Type: schema.TypeInt, + Computed: true, + }, + "extips": { + Type: schema.TypeInt, + Computed: true, + }, + "exttraffic": { + Type: schema.TypeInt, + Computed: true, + }, + "gpu": { + Type: schema.TypeInt, + Computed: true, + }, + "ram": { + Type: schema.TypeInt, + Computed: true, + }, + }, + }, + }, + + "limits": { + Type: schema.TypeList, + Computed: true, + MaxItems: 1, + Elem: &schema.Resource{ + Schema: map[string]*schema.Schema{ + "cpu": { + Type: schema.TypeInt, + Computed: true, + }, + "disksize": { + Type: schema.TypeInt, + Computed: true, + }, + "extips": { + Type: schema.TypeInt, + Computed: true, + }, + "exttraffic": { + Type: schema.TypeInt, + Computed: true, + }, + "gpu": { + Type: schema.TypeInt, + Computed: true, + }, + "ram": { + Type: schema.TypeInt, + Computed: true, + }, + }, + }, + }, + "reserved": { + Type: schema.TypeList, + Computed: true, + MaxItems: 1, + Elem: &schema.Resource{ + Schema: map[string]*schema.Schema{ + "cpu": { + Type: schema.TypeInt, + Computed: true, + }, + "disksize": { + Type: schema.TypeInt, + Computed: true, + }, + "extips": { + Type: schema.TypeInt, + Computed: true, + }, + "exttraffic": { + Type: schema.TypeInt, + Computed: true, + }, + "gpu": { + Type: schema.TypeInt, + Computed: true, + }, + "ram": { + Type: schema.TypeInt, + Computed: true, + }, + }, + }, + }, + }, + }, + }, + + "created_by": { + Type: schema.TypeString, + Computed: true, + }, + "created_time": { + Type: schema.TypeInt, + Computed: true, + }, + "deleted_by": { + Type: schema.TypeString, + Computed: true, + }, + "deleted_time": { + Type: schema.TypeInt, + Computed: true, + }, + "rg_id": { + Type: schema.TypeInt, + Computed: true, + }, + "milestones": { + Type: schema.TypeInt, + Computed: true, + }, + "rg_name": { + Type: schema.TypeString, + Computed: true, + }, + "status": { + Type: schema.TypeString, + Computed: true, + }, + "updated_by": { + Type: schema.TypeString, + Computed: true, + }, + "updated_time": { + Type: schema.TypeInt, + Computed: true, + }, + "vinses": { + Type: schema.TypeInt, + Computed: true, + }, + }, + }, + }, + } + return res +} + +func dataSourceAccountRGList() *schema.Resource { + return &schema.Resource{ + SchemaVersion: 1, + + Read: dataSourceAccountRGListRead, + + Timeouts: &schema.ResourceTimeout{ + Read: &Timeout30s, + Default: &Timeout60s, + }, + + Schema: dataSourceAccountRGListSchemaMake(), + } +} diff --git a/decort/models_api.go b/decort/models_api.go index 80b5ffd..69745b4 100644 --- a/decort/models_api.go +++ b/decort/models_api.go @@ -1008,7 +1008,7 @@ const accountListCSAPI = "/cloudapi/account/listCS" const accountListDeletedAPI = "/cloudapi/account/listDeleted" const accountListDisksAPI = "/restmachine/cloudapi/account/listDisks" const accountListFlipGroupsAPI = "/cloudapi/account/listFlipGroups" -const accountListRGAPI = "/cloudapi/account/listRG" +const accountListRGAPI = "/restmachine/cloudapi/account/listRG" const accountListTemplatesAPI = "/cloudapi/account/listTemplates" const accountListVinsAPI = "/restmachine/cloudapi/account/listVins" const accountListVMsAPI = "/cloudapi/account/listVMs" @@ -1156,3 +1156,32 @@ type AccountAudit struct { } type AccountAuditsList []AccountAudit + +type AccountRGComputes struct { + Started int `json:"Started"` + Stopped int `json:"Stopped"` +} + +type AccountRGResources struct { + Consumed Resource `json:"Consumed"` + Limits Resource `json:"Limits"` + Reserved Resource `json:"Reserved"` +} + +type AccountRG struct { + Computes AccountRGComputes `json:"Computes"` + Resources AccountRGResources `json:"Resources"` + CreatedBy string `json:"createdBy"` + CreatedTime int `json:"createdTime"` + DeletedBy string `json:"deletedBy"` + DeletedTime int `json:"deletedTime"` + RGID int `json:"id"` + Milestones int `json:"milestones"` + RGName string `json:"name"` + Status string `json:"status"` + UpdatedBy string `json:"updatedBy"` + UpdatedTime int `json:"updatedTime"` + Vinses int `json:"vinses"` +} + +type AccountRGList []AccountRG diff --git a/decort/provider.go b/decort/provider.go index 7145229..aba1acc 100644 --- a/decort/provider.go +++ b/decort/provider.go @@ -145,6 +145,7 @@ func Provider() *schema.Provider { "decort_account_disks_list": dataSourceAccountDisksList(), "decort_account_vins_list": dataSourceAccountVinsList(), "decort_account_audits_list": dataSourceAccountAuditsList(), + "decort_account_rg_list": dataSourceAccountRGList(), // "decort_pfw": dataSourcePfw(), }, diff --git a/decort/utility_account_rg_list.go b/decort/utility_account_rg_list.go new file mode 100644 index 0000000..0145b3a --- /dev/null +++ b/decort/utility_account_rg_list.go @@ -0,0 +1,56 @@ +/* +Copyright (c) 2019-2022 Digital Energy Cloud Solutions LLC. All Rights Reserved. +Author: Stanislav Solovev, , + +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. +*/ + +/* +This file is part of Terraform (by Hashicorp) provider for Digital Energy Cloud Orchestration +Technology platfom. + +Visit https://github.com/rudecs/terraform-provider-decort for full source code package and updates. +*/ + +package decort + +import ( + "encoding/json" + "net/url" + "strconv" + + log "github.com/sirupsen/logrus" + + "github.com/hashicorp/terraform-plugin-sdk/helper/schema" +) + +func utilityAccountRGListCheckPresence(d *schema.ResourceData, m interface{}) (AccountRGList, error) { + accountRGList := AccountRGList{} + controller := m.(*ControllerCfg) + urlValues := &url.Values{} + + urlValues.Add("accountId", strconv.Itoa(d.Get("account_id").(int))) + + log.Debugf("utilityAccountRGListCheckPresence: load account list") + accountRGListRaw, err := controller.decortAPICall("POST", accountListRGAPI, urlValues) + if err != nil { + return nil, err + } + + err = json.Unmarshal([]byte(accountRGListRaw), &accountRGList) + if err != nil { + return nil, err + } + + return accountRGList, nil +} diff --git a/samples/README.md b/samples/README.md index 3b091f7..20326fc 100644 --- a/samples/README.md +++ b/samples/README.md @@ -26,6 +26,7 @@ - account_vins_list - account_audits_list - account + - account_rg_list - resources: - image - virtual_image @@ -37,6 +38,7 @@ - pcidevice - sep - sep_config + - account ## Как пользоваться примерами 1. Установить terraform diff --git a/samples/data_account_rg_list/main.tf b/samples/data_account_rg_list/main.tf new file mode 100644 index 0000000..48d5418 --- /dev/null +++ b/samples/data_account_rg_list/main.tf @@ -0,0 +1,37 @@ +/* +Пример использования +Получение информации о ресурных группах, используемых аккаунтом +*/ +#Расскомментируйте этот код, +#и внесите необходимые правки в версию и путь, +#чтобы работать с установленным вручную (не через hashicorp provider registry) провайдером +/* +terraform { + required_providers { + decort = { + version = "1.1" + source = "digitalenergy.online/decort/decort" + } + } +} +*/ + +provider "decort" { + authenticator = "oauth2" + #controller_url = + controller_url = "https://ds1.digitalenergy.online" + #oauth2_url = + oauth2_url = "https://sso.digitalenergy.online" + allow_unverified_ssl = true +} + +data "decort_account_rg_list" "argl" { + #id аккаунта + #обязательный параметр + #тип - число + account_id = 88366 +} + +output "test" { + value = data.decort_account_rg_list.argl +} From 839841aee4f41b096ceb0818039e8693ddc5bfac Mon Sep 17 00:00:00 2001 From: stSolo Date: Fri, 27 May 2022 15:11:53 +0300 Subject: [PATCH 18/51] Add data for account consumed units --- decort/data_account_consumed_units.go | 98 +++++++++++++++++++++ decort/models_api.go | 1 + decort/provider.go | 57 ++++++------ decort/utility_account_consumed_units.go | 56 ++++++++++++ samples/README.md | 1 + samples/data_account_consumed_units/main.tf | 37 ++++++++ 6 files changed, 222 insertions(+), 28 deletions(-) create mode 100644 decort/data_account_consumed_units.go create mode 100644 decort/utility_account_consumed_units.go create mode 100644 samples/data_account_consumed_units/main.tf diff --git a/decort/data_account_consumed_units.go b/decort/data_account_consumed_units.go new file mode 100644 index 0000000..6723e17 --- /dev/null +++ b/decort/data_account_consumed_units.go @@ -0,0 +1,98 @@ +/* +Copyright (c) 2019-2022 Digital Energy Cloud Solutions LLC. All Rights Reserved. +Author: Stanislav Solovev, + +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. +*/ + +/* +This file is part of Terraform (by Hashicorp) provider for Digital Energy Cloud Orchestration +Technology platfom. + +Visit https://github.com/rudecs/terraform-provider-decort for full source code package and updates. +*/ + +package decort + +import ( + "github.com/google/uuid" + "github.com/hashicorp/terraform-plugin-sdk/helper/schema" +) + +func dataSourceAccountConsumedUnitsRead(d *schema.ResourceData, m interface{}) error { + accountConsumedUnits, err := utilityAccountConsumedUnitsCheckPresence(d, m) + if err != nil { + return err + } + + id := uuid.New() + d.SetId(id.String()) + d.Set("cu_c", accountConsumedUnits.CUC) + d.Set("cu_d", accountConsumedUnits.CUD) + d.Set("cu_i", accountConsumedUnits.CUI) + d.Set("cu_m", accountConsumedUnits.CUM) + d.Set("cu_np", accountConsumedUnits.CUNP) + d.Set("gpu_units", accountConsumedUnits.GpuUnits) + + return nil +} + +func dataSourceAccountConsumedUnitsSchemaMake() map[string]*schema.Schema { + res := map[string]*schema.Schema{ + "account_id": { + Type: schema.TypeInt, + Required: true, + Description: "ID of the account", + }, + "cu_c": { + Type: schema.TypeFloat, + Computed: true, + }, + "cu_d": { + Type: schema.TypeFloat, + Computed: true, + }, + "cu_i": { + Type: schema.TypeFloat, + Computed: true, + }, + "cu_m": { + Type: schema.TypeFloat, + Computed: true, + }, + "cu_np": { + Type: schema.TypeFloat, + Computed: true, + }, + "gpu_units": { + Type: schema.TypeFloat, + Computed: true, + }, + } + return res +} + +func dataSourceAccountConsumedUnits() *schema.Resource { + return &schema.Resource{ + SchemaVersion: 1, + + Read: dataSourceAccountConsumedUnitsRead, + + Timeouts: &schema.ResourceTimeout{ + Read: &Timeout30s, + Default: &Timeout60s, + }, + + Schema: dataSourceAccountConsumedUnitsSchemaMake(), + } +} diff --git a/decort/models_api.go b/decort/models_api.go index 69745b4..d1a7d9b 100644 --- a/decort/models_api.go +++ b/decort/models_api.go @@ -1002,6 +1002,7 @@ const accountDeleteUserAPI = "/restmachine/cloudapi/account/deleteUser" const accountDisableAPI = "/restmachine/cloudapi/account/disable" const accountEnableAPI = "/restmachine/cloudapi/account/enable" const accountGetAPI = "/restmachine/cloudapi/account/get" +const accountGetConsumedUnitsAPI = "/restmachine/cloudapi/account/getConsumedAccountUnits" const accountListAPI = "/restmachine/cloudapi/account/list" const accountListComputesAPI = "/restmachine/cloudapi/account/listComputes" const accountListCSAPI = "/cloudapi/account/listCS" diff --git a/decort/provider.go b/decort/provider.go index aba1acc..cd0ff67 100644 --- a/decort/provider.go +++ b/decort/provider.go @@ -118,34 +118,35 @@ func Provider() *schema.Provider { }, DataSourcesMap: map[string]*schema.Resource{ - "decort_account": dataSourceAccount(), - "decort_resgroup": dataSourceResgroup(), - "decort_kvmvm": dataSourceCompute(), - "decort_image": dataSourceImage(), - "decort_disk": dataSourceDisk(), - "decort_vins": dataSourceVins(), - "decort_grid": dataSourceGrid(), - "decort_grid_list": dataSourceGridList(), - "decort_image_list": dataSourceImageList(), - "decort_image_list_stacks": dataSourceImageListStacks(), - "decort_snapshot_list": dataSourceSnapshotList(), - "decort_vgpu": dataSourceVGPU(), - "decort_pcidevice": dataSourcePcidevice(), - "decort_pcidevice_list": dataSourcePcideviceList(), - "decort_sep_list": dataSourceSepList(), - "decort_sep": dataSourceSep(), - "decort_sep_consumption": dataSourceSepConsumption(), - "decort_sep_disk_list": dataSourceSepDiskList(), - "decort_sep_config": dataSourceSepConfig(), - "decort_sep_pool": dataSourceSepPool(), - "decort_disk_list": dataSourceDiskList(), - "decort_rg_list": dataSourceRgList(), - "decort_account_list": dataSourceAccountList(), - "decort_account_computes_list": dataSourceAccountComputesList(), - "decort_account_disks_list": dataSourceAccountDisksList(), - "decort_account_vins_list": dataSourceAccountVinsList(), - "decort_account_audits_list": dataSourceAccountAuditsList(), - "decort_account_rg_list": dataSourceAccountRGList(), + "decort_account": dataSourceAccount(), + "decort_resgroup": dataSourceResgroup(), + "decort_kvmvm": dataSourceCompute(), + "decort_image": dataSourceImage(), + "decort_disk": dataSourceDisk(), + "decort_vins": dataSourceVins(), + "decort_grid": dataSourceGrid(), + "decort_grid_list": dataSourceGridList(), + "decort_image_list": dataSourceImageList(), + "decort_image_list_stacks": dataSourceImageListStacks(), + "decort_snapshot_list": dataSourceSnapshotList(), + "decort_vgpu": dataSourceVGPU(), + "decort_pcidevice": dataSourcePcidevice(), + "decort_pcidevice_list": dataSourcePcideviceList(), + "decort_sep_list": dataSourceSepList(), + "decort_sep": dataSourceSep(), + "decort_sep_consumption": dataSourceSepConsumption(), + "decort_sep_disk_list": dataSourceSepDiskList(), + "decort_sep_config": dataSourceSepConfig(), + "decort_sep_pool": dataSourceSepPool(), + "decort_disk_list": dataSourceDiskList(), + "decort_rg_list": dataSourceRgList(), + "decort_account_list": dataSourceAccountList(), + "decort_account_computes_list": dataSourceAccountComputesList(), + "decort_account_disks_list": dataSourceAccountDisksList(), + "decort_account_vins_list": dataSourceAccountVinsList(), + "decort_account_audits_list": dataSourceAccountAuditsList(), + "decort_account_rg_list": dataSourceAccountRGList(), + "decort_account_consumed_units": dataSourceAccountConsumedUnits(), // "decort_pfw": dataSourcePfw(), }, diff --git a/decort/utility_account_consumed_units.go b/decort/utility_account_consumed_units.go new file mode 100644 index 0000000..b5cdd1e --- /dev/null +++ b/decort/utility_account_consumed_units.go @@ -0,0 +1,56 @@ +/* +Copyright (c) 2019-2022 Digital Energy Cloud Solutions LLC. All Rights Reserved. +Author: Stanislav Solovev, , + +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. +*/ + +/* +This file is part of Terraform (by Hashicorp) provider for Digital Energy Cloud Orchestration +Technology platfom. + +Visit https://github.com/rudecs/terraform-provider-decort for full source code package and updates. +*/ + +package decort + +import ( + "encoding/json" + "net/url" + "strconv" + + log "github.com/sirupsen/logrus" + + "github.com/hashicorp/terraform-plugin-sdk/helper/schema" +) + +func utilityAccountConsumedUnitsCheckPresence(d *schema.ResourceData, m interface{}) (*ResourceLimits, error) { + accountConsumedUnits := &ResourceLimits{} + controller := m.(*ControllerCfg) + urlValues := &url.Values{} + + urlValues.Add("accountId", strconv.Itoa(d.Get("account_id").(int))) + + log.Debugf("utilityAccountConsumedUnitsCheckPresence: load account list") + accountConsumedUnitsRaw, err := controller.decortAPICall("POST", accountGetConsumedUnitsAPI, urlValues) + if err != nil { + return nil, err + } + + err = json.Unmarshal([]byte(accountConsumedUnitsRaw), accountConsumedUnits) + if err != nil { + return nil, err + } + + return accountConsumedUnits, nil +} diff --git a/samples/README.md b/samples/README.md index 20326fc..ca7b7b6 100644 --- a/samples/README.md +++ b/samples/README.md @@ -27,6 +27,7 @@ - account_audits_list - account - account_rg_list + - account_counsumed_units - resources: - image - virtual_image diff --git a/samples/data_account_consumed_units/main.tf b/samples/data_account_consumed_units/main.tf new file mode 100644 index 0000000..b12b1df --- /dev/null +++ b/samples/data_account_consumed_units/main.tf @@ -0,0 +1,37 @@ +/* +Пример использования +Получение информации о расходуемых ресурсах аккаута +*/ +#Расскомментируйте этот код, +#и внесите необходимые правки в версию и путь, +#чтобы работать с установленным вручную (не через hashicorp provider registry) провайдером +/* +terraform { + required_providers { + decort = { + version = "1.1" + source = "digitalenergy.online/decort/decort" + } + } +} +*/ + +provider "decort" { + authenticator = "oauth2" + #controller_url = + controller_url = "https://ds1.digitalenergy.online" + #oauth2_url = + oauth2_url = "https://sso.digitalenergy.online" + allow_unverified_ssl = true +} + +data "decort_account_consumed_units" "acu" { + #id аккаунта + #обязательный параметр + #тип - число + account_id = 88366 +} + +output "test" { + value = data.decort_account_consumed_units.acu +} From a685a91f868b2fcaa5b070a94630d20a627eea10 Mon Sep 17 00:00:00 2001 From: stSolo Date: Fri, 27 May 2022 16:01:50 +0300 Subject: [PATCH 19/51] Add data for account consumed units by type --- decort/data_account_consumed_units_by_type.go | 78 +++++++++++++++++++ decort/models_api.go | 1 + decort/provider.go | 59 +++++++------- .../utility_account_consumed_units_by_type.go | 55 +++++++++++++ samples/README.md | 1 + .../main.tf | 54 +++++++++++++ 6 files changed, 219 insertions(+), 29 deletions(-) create mode 100644 decort/data_account_consumed_units_by_type.go create mode 100644 decort/utility_account_consumed_units_by_type.go create mode 100644 samples/data_account_consumed_units_by_type/main.tf diff --git a/decort/data_account_consumed_units_by_type.go b/decort/data_account_consumed_units_by_type.go new file mode 100644 index 0000000..4b9ccd6 --- /dev/null +++ b/decort/data_account_consumed_units_by_type.go @@ -0,0 +1,78 @@ +/* +Copyright (c) 2019-2022 Digital Energy Cloud Solutions LLC. All Rights Reserved. +Author: Stanislav Solovev, + +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. +*/ + +/* +This file is part of Terraform (by Hashicorp) provider for Digital Energy Cloud Orchestration +Technology platfom. + +Visit https://github.com/rudecs/terraform-provider-decort for full source code package and updates. +*/ + +package decort + +import ( + "github.com/google/uuid" + "github.com/hashicorp/terraform-plugin-sdk/helper/schema" +) + +func dataSourceAccountConsumedUnitsByTypeRead(d *schema.ResourceData, m interface{}) error { + result, err := utilityAccountConsumedUnitsByTypeCheckPresence(d, m) + if err != nil { + return err + } + + id := uuid.New() + d.SetId(id.String()) + d.Set("cu_result", result) + + return nil +} + +func dataSourceAccountConsumedUnitsByTypeSchemaMake() map[string]*schema.Schema { + res := map[string]*schema.Schema{ + "account_id": { + Type: schema.TypeInt, + Required: true, + Description: "ID of the account", + }, + "cu_type": { + Type: schema.TypeString, + Required: true, + Description: "cloud unit resource type", + }, + "cu_result": { + Type: schema.TypeFloat, + Computed: true, + }, + } + return res +} + +func dataSourceAccountConsumedUnitsByType() *schema.Resource { + return &schema.Resource{ + SchemaVersion: 1, + + Read: dataSourceAccountConsumedUnitsByTypeRead, + + Timeouts: &schema.ResourceTimeout{ + Read: &Timeout30s, + Default: &Timeout60s, + }, + + Schema: dataSourceAccountConsumedUnitsByTypeSchemaMake(), + } +} diff --git a/decort/models_api.go b/decort/models_api.go index d1a7d9b..b321d0e 100644 --- a/decort/models_api.go +++ b/decort/models_api.go @@ -1003,6 +1003,7 @@ const accountDisableAPI = "/restmachine/cloudapi/account/disable" const accountEnableAPI = "/restmachine/cloudapi/account/enable" const accountGetAPI = "/restmachine/cloudapi/account/get" const accountGetConsumedUnitsAPI = "/restmachine/cloudapi/account/getConsumedAccountUnits" +const accountGetConsumedUnitsByTypeAPI = "/restmachine/cloudapi/account/getConsumedCloudUnitsByType" const accountListAPI = "/restmachine/cloudapi/account/list" const accountListComputesAPI = "/restmachine/cloudapi/account/listComputes" const accountListCSAPI = "/cloudapi/account/listCS" diff --git a/decort/provider.go b/decort/provider.go index cd0ff67..a12a61c 100644 --- a/decort/provider.go +++ b/decort/provider.go @@ -118,35 +118,36 @@ func Provider() *schema.Provider { }, DataSourcesMap: map[string]*schema.Resource{ - "decort_account": dataSourceAccount(), - "decort_resgroup": dataSourceResgroup(), - "decort_kvmvm": dataSourceCompute(), - "decort_image": dataSourceImage(), - "decort_disk": dataSourceDisk(), - "decort_vins": dataSourceVins(), - "decort_grid": dataSourceGrid(), - "decort_grid_list": dataSourceGridList(), - "decort_image_list": dataSourceImageList(), - "decort_image_list_stacks": dataSourceImageListStacks(), - "decort_snapshot_list": dataSourceSnapshotList(), - "decort_vgpu": dataSourceVGPU(), - "decort_pcidevice": dataSourcePcidevice(), - "decort_pcidevice_list": dataSourcePcideviceList(), - "decort_sep_list": dataSourceSepList(), - "decort_sep": dataSourceSep(), - "decort_sep_consumption": dataSourceSepConsumption(), - "decort_sep_disk_list": dataSourceSepDiskList(), - "decort_sep_config": dataSourceSepConfig(), - "decort_sep_pool": dataSourceSepPool(), - "decort_disk_list": dataSourceDiskList(), - "decort_rg_list": dataSourceRgList(), - "decort_account_list": dataSourceAccountList(), - "decort_account_computes_list": dataSourceAccountComputesList(), - "decort_account_disks_list": dataSourceAccountDisksList(), - "decort_account_vins_list": dataSourceAccountVinsList(), - "decort_account_audits_list": dataSourceAccountAuditsList(), - "decort_account_rg_list": dataSourceAccountRGList(), - "decort_account_consumed_units": dataSourceAccountConsumedUnits(), + "decort_account": dataSourceAccount(), + "decort_resgroup": dataSourceResgroup(), + "decort_kvmvm": dataSourceCompute(), + "decort_image": dataSourceImage(), + "decort_disk": dataSourceDisk(), + "decort_vins": dataSourceVins(), + "decort_grid": dataSourceGrid(), + "decort_grid_list": dataSourceGridList(), + "decort_image_list": dataSourceImageList(), + "decort_image_list_stacks": dataSourceImageListStacks(), + "decort_snapshot_list": dataSourceSnapshotList(), + "decort_vgpu": dataSourceVGPU(), + "decort_pcidevice": dataSourcePcidevice(), + "decort_pcidevice_list": dataSourcePcideviceList(), + "decort_sep_list": dataSourceSepList(), + "decort_sep": dataSourceSep(), + "decort_sep_consumption": dataSourceSepConsumption(), + "decort_sep_disk_list": dataSourceSepDiskList(), + "decort_sep_config": dataSourceSepConfig(), + "decort_sep_pool": dataSourceSepPool(), + "decort_disk_list": dataSourceDiskList(), + "decort_rg_list": dataSourceRgList(), + "decort_account_list": dataSourceAccountList(), + "decort_account_computes_list": dataSourceAccountComputesList(), + "decort_account_disks_list": dataSourceAccountDisksList(), + "decort_account_vins_list": dataSourceAccountVinsList(), + "decort_account_audits_list": dataSourceAccountAuditsList(), + "decort_account_rg_list": dataSourceAccountRGList(), + "decort_account_consumed_units": dataSourceAccountConsumedUnits(), + "decort_account_consumed_units_by_type": dataSourceAccountConsumedUnitsByType(), // "decort_pfw": dataSourcePfw(), }, diff --git a/decort/utility_account_consumed_units_by_type.go b/decort/utility_account_consumed_units_by_type.go new file mode 100644 index 0000000..d0d65f2 --- /dev/null +++ b/decort/utility_account_consumed_units_by_type.go @@ -0,0 +1,55 @@ +/* +Copyright (c) 2019-2022 Digital Energy Cloud Solutions LLC. All Rights Reserved. +Author: Stanislav Solovev, , + +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. +*/ + +/* +This file is part of Terraform (by Hashicorp) provider for Digital Energy Cloud Orchestration +Technology platfom. + +Visit https://github.com/rudecs/terraform-provider-decort for full source code package and updates. +*/ + +package decort + +import ( + "net/url" + "strconv" + "strings" + + log "github.com/sirupsen/logrus" + + "github.com/hashicorp/terraform-plugin-sdk/helper/schema" +) + +func utilityAccountConsumedUnitsByTypeCheckPresence(d *schema.ResourceData, m interface{}) (float64, error) { + controller := m.(*ControllerCfg) + urlValues := &url.Values{} + + urlValues.Add("accountId", strconv.Itoa(d.Get("account_id").(int))) + urlValues.Add("cutype", strings.ToUpper(d.Get("cu_type").(string))) + + log.Debugf("utilityAccountConsumedUnitsByTypeCheckPresence") + resultRaw, err := controller.decortAPICall("POST", accountGetConsumedUnitsByTypeAPI, urlValues) + if err != nil { + return 0, err + } + result, err := strconv.ParseFloat(resultRaw, 64) + if err != nil { + return 0, err + } + + return result, nil +} diff --git a/samples/README.md b/samples/README.md index ca7b7b6..dbc389e 100644 --- a/samples/README.md +++ b/samples/README.md @@ -28,6 +28,7 @@ - account - account_rg_list - account_counsumed_units + - account_counsumed_units_by_type - resources: - image - virtual_image diff --git a/samples/data_account_consumed_units_by_type/main.tf b/samples/data_account_consumed_units_by_type/main.tf new file mode 100644 index 0000000..67d3043 --- /dev/null +++ b/samples/data_account_consumed_units_by_type/main.tf @@ -0,0 +1,54 @@ +/* +Пример использования +Ресурса cdrom image +Ресурс позволяет: +1. Создавать образ +2. Редактировать образ +3. Удалять образ + +*/ +#Расскомментируйте этот код, +#и внесите необходимые правки в версию и путь, +#чтобы работать с установленным вручную (не через hashicorp provider registry) провайдером +/* +terraform { + required_providers { + decort = { + version = "1.1" + source = "digitalenergy.online/decort/decort" + } + } +} +*/ + +provider "decort" { + authenticator = "oauth2" + #controller_url = + controller_url = "https://ds1.digitalenergy.online" + #oauth2_url = + oauth2_url = "https://sso.digitalenergy.online" + allow_unverified_ssl = true +} + +data "decort_account_consumed_units_by_type" "acubt" { + #id аккаунта + #обязательный параметр + #тип - число + account_id = 88366 + + #тип вычислительной еденицы + #обязательный параметр + #тип - строка + #значения: + #cu_c - кол-во виртуальных cpu ядер + #cu_m - кол-во RAM в МБ + #cu_d - кол-в используемой дисковой памяти, в ГБ + #cu_i - кол-во публичных ip адресов + #cu_np - кол-во полученного/отданного трафика, в ГБ + #gpu_units - кол-во gpu ядер + cu_type = "cu_a" +} + +output "test" { + value = data.decort_account_consumed_units_by_type.acubt +} From 96c4175e74ccf68e9518228223ddbeadb51981d7 Mon Sep 17 00:00:00 2001 From: stSolo Date: Fri, 27 May 2022 18:23:38 +0300 Subject: [PATCH 20/51] Add data for account reserved units --- decort/data_account_reserved_units.go | 98 +++++++++++++++++++++ decort/models_api.go | 1 + decort/provider.go | 1 + decort/utility_account_reserved_units.go | 56 ++++++++++++ samples/README.md | 1 + samples/data_account_reserved_units/main.tf | 38 ++++++++ 6 files changed, 195 insertions(+) create mode 100644 decort/data_account_reserved_units.go create mode 100644 decort/utility_account_reserved_units.go create mode 100644 samples/data_account_reserved_units/main.tf diff --git a/decort/data_account_reserved_units.go b/decort/data_account_reserved_units.go new file mode 100644 index 0000000..b4d48c9 --- /dev/null +++ b/decort/data_account_reserved_units.go @@ -0,0 +1,98 @@ +/* +Copyright (c) 2019-2022 Digital Energy Cloud Solutions LLC. All Rights Reserved. +Author: Stanislav Solovev, + +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. +*/ + +/* +This file is part of Terraform (by Hashicorp) provider for Digital Energy Cloud Orchestration +Technology platfom. + +Visit https://github.com/rudecs/terraform-provider-decort for full source code package and updates. +*/ + +package decort + +import ( + "github.com/google/uuid" + "github.com/hashicorp/terraform-plugin-sdk/helper/schema" +) + +func dataSourceAccountReservedUnitsRead(d *schema.ResourceData, m interface{}) error { + accountReservedUnits, err := utilityAccountReservedUnitsCheckPresence(d, m) + if err != nil { + return err + } + + id := uuid.New() + d.SetId(id.String()) + d.Set("cu_c", accountReservedUnits.CUC) + d.Set("cu_d", accountReservedUnits.CUD) + d.Set("cu_i", accountReservedUnits.CUI) + d.Set("cu_m", accountReservedUnits.CUM) + d.Set("cu_np", accountReservedUnits.CUNP) + d.Set("gpu_units", accountReservedUnits.GpuUnits) + + return nil +} + +func dataSourceAccountReservedUnitsSchemaMake() map[string]*schema.Schema { + res := map[string]*schema.Schema{ + "account_id": { + Type: schema.TypeInt, + Required: true, + Description: "ID of the account", + }, + "cu_c": { + Type: schema.TypeFloat, + Computed: true, + }, + "cu_d": { + Type: schema.TypeFloat, + Computed: true, + }, + "cu_i": { + Type: schema.TypeFloat, + Computed: true, + }, + "cu_m": { + Type: schema.TypeFloat, + Computed: true, + }, + "cu_np": { + Type: schema.TypeFloat, + Computed: true, + }, + "gpu_units": { + Type: schema.TypeFloat, + Computed: true, + }, + } + return res +} + +func dataSourceAccountReservedUnits() *schema.Resource { + return &schema.Resource{ + SchemaVersion: 1, + + Read: dataSourceAccountReservedUnitsRead, + + Timeouts: &schema.ResourceTimeout{ + Read: &Timeout30s, + Default: &Timeout60s, + }, + + Schema: dataSourceAccountReservedUnitsSchemaMake(), + } +} diff --git a/decort/models_api.go b/decort/models_api.go index b321d0e..ce6f97f 100644 --- a/decort/models_api.go +++ b/decort/models_api.go @@ -1004,6 +1004,7 @@ const accountEnableAPI = "/restmachine/cloudapi/account/enable" const accountGetAPI = "/restmachine/cloudapi/account/get" const accountGetConsumedUnitsAPI = "/restmachine/cloudapi/account/getConsumedAccountUnits" const accountGetConsumedUnitsByTypeAPI = "/restmachine/cloudapi/account/getConsumedCloudUnitsByType" +const accountGetReservedUnitsAPI = "/restmachine/cloudapi/account/getReservedAccountUnits" const accountListAPI = "/restmachine/cloudapi/account/list" const accountListComputesAPI = "/restmachine/cloudapi/account/listComputes" const accountListCSAPI = "/cloudapi/account/listCS" diff --git a/decort/provider.go b/decort/provider.go index a12a61c..66f2ce6 100644 --- a/decort/provider.go +++ b/decort/provider.go @@ -148,6 +148,7 @@ func Provider() *schema.Provider { "decort_account_rg_list": dataSourceAccountRGList(), "decort_account_consumed_units": dataSourceAccountConsumedUnits(), "decort_account_consumed_units_by_type": dataSourceAccountConsumedUnitsByType(), + "decort_account_reserved_units": dataSourceAccountReservedUnits(), // "decort_pfw": dataSourcePfw(), }, diff --git a/decort/utility_account_reserved_units.go b/decort/utility_account_reserved_units.go new file mode 100644 index 0000000..31bd4b9 --- /dev/null +++ b/decort/utility_account_reserved_units.go @@ -0,0 +1,56 @@ +/* +Copyright (c) 2019-2022 Digital Energy Cloud Solutions LLC. All Rights Reserved. +Author: Stanislav Solovev, , + +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. +*/ + +/* +This file is part of Terraform (by Hashicorp) provider for Digital Energy Cloud Orchestration +Technology platfom. + +Visit https://github.com/rudecs/terraform-provider-decort for full source code package and updates. +*/ + +package decort + +import ( + "encoding/json" + "net/url" + "strconv" + + log "github.com/sirupsen/logrus" + + "github.com/hashicorp/terraform-plugin-sdk/helper/schema" +) + +func utilityAccountReservedUnitsCheckPresence(d *schema.ResourceData, m interface{}) (*ResourceLimits, error) { + accountReservedUnits := &ResourceLimits{} + controller := m.(*ControllerCfg) + urlValues := &url.Values{} + + urlValues.Add("accountId", strconv.Itoa(d.Get("account_id").(int))) + + log.Debugf("utilityAccountReservedUnitsCheckPresence: load units") + accountReservedUnitsRaw, err := controller.decortAPICall("POST", accountGetReservedUnitsAPI, urlValues) + if err != nil { + return nil, err + } + + err = json.Unmarshal([]byte(accountReservedUnitsRaw), accountReservedUnits) + if err != nil { + return nil, err + } + + return accountReservedUnits, nil +} diff --git a/samples/README.md b/samples/README.md index dbc389e..85e8dc0 100644 --- a/samples/README.md +++ b/samples/README.md @@ -29,6 +29,7 @@ - account_rg_list - account_counsumed_units - account_counsumed_units_by_type + - account_reserved_units - resources: - image - virtual_image diff --git a/samples/data_account_reserved_units/main.tf b/samples/data_account_reserved_units/main.tf new file mode 100644 index 0000000..f86a3dc --- /dev/null +++ b/samples/data_account_reserved_units/main.tf @@ -0,0 +1,38 @@ +/* +Пример использования +Получение информии о зарезервированных вычислительных мощностях + +*/ +#Расскомментируйте этот код, +#и внесите необходимые правки в версию и путь, +#чтобы работать с установленным вручную (не через hashicorp provider registry) провайдером +/* +terraform { + required_providers { + decort = { + version = "1.1" + source = "digitalenergy.online/decort/decort" + } + } +} +*/ + +provider "decort" { + authenticator = "oauth2" + #controller_url = + controller_url = "https://ds1.digitalenergy.online" + #oauth2_url = + oauth2_url = "https://sso.digitalenergy.online" + allow_unverified_ssl = true +} + +data "decort_account_reserved_units" "aru" { + #id аккаунта + #обязательный параметр + #тип - число + account_id = 88366 +} + +output "test" { + value = data.decort_account_reserved_units.aru +} From 61b8765c82af2f4bf4e467539ec6c4ad7a988dfd Mon Sep 17 00:00:00 2001 From: stSolo Date: Fri, 27 May 2022 19:39:49 +0300 Subject: [PATCH 21/51] Add data for account templates lis --- decort/data_account_templates_list.go | 139 ++++++++++++++++++++ decort/models_api.go | 17 ++- decort/provider.go | 1 + decort/utility_account_templates_list.go | 56 ++++++++ samples/README.md | 1 + samples/data_account_templates_list/main.tf | 38 ++++++ 6 files changed, 251 insertions(+), 1 deletion(-) create mode 100644 decort/data_account_templates_list.go create mode 100644 decort/utility_account_templates_list.go create mode 100644 samples/data_account_templates_list/main.tf diff --git a/decort/data_account_templates_list.go b/decort/data_account_templates_list.go new file mode 100644 index 0000000..4071088 --- /dev/null +++ b/decort/data_account_templates_list.go @@ -0,0 +1,139 @@ +/* +Copyright (c) 2019-2022 Digital Energy Cloud Solutions LLC. All Rights Reserved. +Author: Stanislav Solovev, + +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. +*/ + +/* +This file is part of Terraform (by Hashicorp) provider for Digital Energy Cloud Orchestration +Technology platfom. + +Visit https://github.com/rudecs/terraform-provider-decort for full source code package and updates. +*/ + +package decort + +import ( + "github.com/google/uuid" + "github.com/hashicorp/terraform-plugin-sdk/helper/schema" +) + +func flattenAccountTemplatesList(atl AccountTemplatesList) []map[string]interface{} { + res := make([]map[string]interface{}, 0) + for _, at := range atl { + temp := map[string]interface{}{ + "unc_path": at.UNCPath, + "account_id": at.AccountId, + "desc": at.Desc, + "template_id": at.ID, + "template_name": at.Name, + "public": at.Public, + "size": at.Size, + "status": at.Status, + "type": at.Type, + "username": at.Username, + } + res = append(res, temp) + } + return res + +} + +func dataSourceAccountTemplatesListRead(d *schema.ResourceData, m interface{}) error { + accountTemplatesList, err := utilityAccountTemplatesListCheckPresence(d, m) + if err != nil { + return err + } + + id := uuid.New() + d.SetId(id.String()) + d.Set("items", flattenAccountTemplatesList(accountTemplatesList)) + + return nil +} + +func dataSourceAccountTemplatesListSchemaMake() map[string]*schema.Schema { + res := map[string]*schema.Schema{ + "account_id": { + Type: schema.TypeInt, + Required: true, + Description: "ID of the account", + }, + "items": { + Type: schema.TypeList, + Computed: true, + Description: "Search Result", + Elem: &schema.Resource{ + Schema: map[string]*schema.Schema{ + "unc_path": { + Type: schema.TypeString, + Computed: true, + }, + "account_id": { + Type: schema.TypeInt, + Computed: true, + }, + "desc": { + Type: schema.TypeString, + Computed: true, + }, + "template_id": { + Type: schema.TypeInt, + Computed: true, + }, + "template_name": { + Type: schema.TypeString, + Computed: true, + }, + "public": { + Type: schema.TypeBool, + Computed: true, + }, + "size": { + Type: schema.TypeInt, + Computed: true, + }, + "status": { + Type: schema.TypeString, + Computed: true, + }, + "type": { + Type: schema.TypeString, + Computed: true, + }, + "username": { + Type: schema.TypeString, + Computed: true, + }, + }, + }, + }, + } + return res +} + +func dataSourceAccountTemplatessList() *schema.Resource { + return &schema.Resource{ + SchemaVersion: 1, + + Read: dataSourceAccountTemplatesListRead, + + Timeouts: &schema.ResourceTimeout{ + Read: &Timeout30s, + Default: &Timeout60s, + }, + + Schema: dataSourceAccountTemplatesListSchemaMake(), + } +} diff --git a/decort/models_api.go b/decort/models_api.go index ce6f97f..cbdf434 100644 --- a/decort/models_api.go +++ b/decort/models_api.go @@ -1012,7 +1012,7 @@ const accountListDeletedAPI = "/cloudapi/account/listDeleted" const accountListDisksAPI = "/restmachine/cloudapi/account/listDisks" const accountListFlipGroupsAPI = "/cloudapi/account/listFlipGroups" const accountListRGAPI = "/restmachine/cloudapi/account/listRG" -const accountListTemplatesAPI = "/cloudapi/account/listTemplates" +const accountListTemplatesAPI = "/restmachine/cloudapi/account/listTemplates" const accountListVinsAPI = "/restmachine/cloudapi/account/listVins" const accountListVMsAPI = "/cloudapi/account/listVMs" const accountRestoreAPI = "/restmachine/cloudapi/account/restore" @@ -1188,3 +1188,18 @@ type AccountRG struct { } type AccountRGList []AccountRG + +type AccountTemplate struct { + UNCPath string `json:"UNCPath"` + AccountId int `json:"accountId"` + Desc string `json:"desc"` + ID int `json:"id"` + Name string `json:"name"` + Public bool `json:"public"` + Size int `json:"size"` + Status string `json:"status"` + Type string `json:"type"` + Username string `json:"username"` +} + +type AccountTemplatesList []AccountTemplate diff --git a/decort/provider.go b/decort/provider.go index 66f2ce6..0e48ce6 100644 --- a/decort/provider.go +++ b/decort/provider.go @@ -149,6 +149,7 @@ func Provider() *schema.Provider { "decort_account_consumed_units": dataSourceAccountConsumedUnits(), "decort_account_consumed_units_by_type": dataSourceAccountConsumedUnitsByType(), "decort_account_reserved_units": dataSourceAccountReservedUnits(), + "decort_account_templates_list": dataSourceAccountTemplatessList(), // "decort_pfw": dataSourcePfw(), }, diff --git a/decort/utility_account_templates_list.go b/decort/utility_account_templates_list.go new file mode 100644 index 0000000..2dd3a2e --- /dev/null +++ b/decort/utility_account_templates_list.go @@ -0,0 +1,56 @@ +/* +Copyright (c) 2019-2022 Digital Energy Cloud Solutions LLC. All Rights Reserved. +Author: Stanislav Solovev, , + +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. +*/ + +/* +This file is part of Terraform (by Hashicorp) provider for Digital Energy Cloud Orchestration +Technology platfom. + +Visit https://github.com/rudecs/terraform-provider-decort for full source code package and updates. +*/ + +package decort + +import ( + "encoding/json" + "net/url" + "strconv" + + log "github.com/sirupsen/logrus" + + "github.com/hashicorp/terraform-plugin-sdk/helper/schema" +) + +func utilityAccountTemplatesListCheckPresence(d *schema.ResourceData, m interface{}) (AccountTemplatesList, error) { + accountTemplatesList := AccountTemplatesList{} + controller := m.(*ControllerCfg) + urlValues := &url.Values{} + + urlValues.Add("accountId", strconv.Itoa(d.Get("account_id").(int))) + + log.Debugf("utilityAccountTemplatesListCheckPresence: load") + accountTemplatesListRaw, err := controller.decortAPICall("POST", accountListTemplatesAPI, urlValues) + if err != nil { + return nil, err + } + + err = json.Unmarshal([]byte(accountTemplatesListRaw), &accountTemplatesList) + if err != nil { + return nil, err + } + + return accountTemplatesList, nil +} diff --git a/samples/README.md b/samples/README.md index 85e8dc0..291ac14 100644 --- a/samples/README.md +++ b/samples/README.md @@ -30,6 +30,7 @@ - account_counsumed_units - account_counsumed_units_by_type - account_reserved_units + - account_templates_list - resources: - image - virtual_image diff --git a/samples/data_account_templates_list/main.tf b/samples/data_account_templates_list/main.tf new file mode 100644 index 0000000..276fe68 --- /dev/null +++ b/samples/data_account_templates_list/main.tf @@ -0,0 +1,38 @@ +/* +Пример использования +Получение информации о шаблонах, используемых аккаунтом + +*/ +#Расскомментируйте этот код, +#и внесите необходимые правки в версию и путь, +#чтобы работать с установленным вручную (не через hashicorp provider registry) провайдером + +terraform { + required_providers { + decort = { + version = "1.1" + source = "digitalenergy.online/decort/decort" + } + } +} + + +provider "decort" { + authenticator = "oauth2" + #controller_url = + controller_url = "https://ds1.digitalenergy.online" + #oauth2_url = + oauth2_url = "https://sso.digitalenergy.online" + allow_unverified_ssl = true +} + +data "decort_account_templates_list" "atl" { + #id аккаунта + #обязательный параметр + #тип - число + account_id = 11111 +} + +output "test" { + value = data.decort_account_templates_list.atl +} From eb22dee25b2be9670b31bb5218294a5ac6a818b5 Mon Sep 17 00:00:00 2001 From: stSolo Date: Fri, 27 May 2022 20:17:25 +0300 Subject: [PATCH 22/51] Add data for account deleted list --- decort/data_account_deleted_list.go | 58 +++++++++++++++++++++ decort/models_api.go | 3 +- decort/provider.go | 1 + decort/utility_account_deleted_list.go | 61 +++++++++++++++++++++++ samples/README.md | 1 + samples/data_account_deleted_list/main.tf | 45 +++++++++++++++++ 6 files changed, 167 insertions(+), 2 deletions(-) create mode 100644 decort/data_account_deleted_list.go create mode 100644 decort/utility_account_deleted_list.go create mode 100644 samples/data_account_deleted_list/main.tf diff --git a/decort/data_account_deleted_list.go b/decort/data_account_deleted_list.go new file mode 100644 index 0000000..d2a57c5 --- /dev/null +++ b/decort/data_account_deleted_list.go @@ -0,0 +1,58 @@ +/* +Copyright (c) 2019-2022 Digital Energy Cloud Solutions LLC. All Rights Reserved. +Author: Stanislav Solovev, + +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. +*/ + +/* +This file is part of Terraform (by Hashicorp) provider for Digital Energy Cloud Orchestration +Technology platfom. + +Visit https://github.com/rudecs/terraform-provider-decort for full source code package and updates. +*/ + +package decort + +import ( + "github.com/google/uuid" + "github.com/hashicorp/terraform-plugin-sdk/helper/schema" +) + +func dataSourceAccountDeletedListRead(d *schema.ResourceData, m interface{}) error { + accountDeletedList, err := utilityAccountDeletedListCheckPresence(d, m) + if err != nil { + return err + } + + id := uuid.New() + d.SetId(id.String()) + d.Set("items", flattenAccountList(accountDeletedList)) + + return nil +} + +func dataSourceAccountDeletedList() *schema.Resource { + return &schema.Resource{ + SchemaVersion: 1, + + Read: dataSourceAccountDeletedListRead, + + Timeouts: &schema.ResourceTimeout{ + Read: &Timeout30s, + Default: &Timeout60s, + }, + + Schema: dataSourceAccountListSchemaMake(), + } +} diff --git a/decort/models_api.go b/decort/models_api.go index cbdf434..7e893eb 100644 --- a/decort/models_api.go +++ b/decort/models_api.go @@ -997,7 +997,6 @@ const accountAddUserAPI = "/restmachine/cloudapi/account/addUser" const accountAuditsAPI = "/restmachine/cloudapi/account/audits" const accountCreateAPI = "/restmachine/cloudapi/account/create" const accountDeleteAPI = "/restmachine/cloudapi/account/delete" -const accountDeleteAccountsAPI = "/cloudapi/account/deleteAccounts" const accountDeleteUserAPI = "/restmachine/cloudapi/account/deleteUser" const accountDisableAPI = "/restmachine/cloudapi/account/disable" const accountEnableAPI = "/restmachine/cloudapi/account/enable" @@ -1008,7 +1007,7 @@ const accountGetReservedUnitsAPI = "/restmachine/cloudapi/account/getReservedAcc const accountListAPI = "/restmachine/cloudapi/account/list" const accountListComputesAPI = "/restmachine/cloudapi/account/listComputes" const accountListCSAPI = "/cloudapi/account/listCS" -const accountListDeletedAPI = "/cloudapi/account/listDeleted" +const accountListDeletedAPI = "/restmachine/cloudapi/account/listDeleted" const accountListDisksAPI = "/restmachine/cloudapi/account/listDisks" const accountListFlipGroupsAPI = "/cloudapi/account/listFlipGroups" const accountListRGAPI = "/restmachine/cloudapi/account/listRG" diff --git a/decort/provider.go b/decort/provider.go index 0e48ce6..22c365e 100644 --- a/decort/provider.go +++ b/decort/provider.go @@ -150,6 +150,7 @@ func Provider() *schema.Provider { "decort_account_consumed_units_by_type": dataSourceAccountConsumedUnitsByType(), "decort_account_reserved_units": dataSourceAccountReservedUnits(), "decort_account_templates_list": dataSourceAccountTemplatessList(), + "decort_account_deleted_list": dataSourceAccountDeletedList(), // "decort_pfw": dataSourcePfw(), }, diff --git a/decort/utility_account_deleted_list.go b/decort/utility_account_deleted_list.go new file mode 100644 index 0000000..7c82750 --- /dev/null +++ b/decort/utility_account_deleted_list.go @@ -0,0 +1,61 @@ +/* +Copyright (c) 2019-2022 Digital Energy Cloud Solutions LLC. All Rights Reserved. +Author: Stanislav Solovev, , + +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. +*/ + +/* +This file is part of Terraform (by Hashicorp) provider for Digital Energy Cloud Orchestration +Technology platfom. + +Visit https://github.com/rudecs/terraform-provider-decort for full source code package and updates. +*/ + +package decort + +import ( + "encoding/json" + "net/url" + "strconv" + + log "github.com/sirupsen/logrus" + + "github.com/hashicorp/terraform-plugin-sdk/helper/schema" +) + +func utilityAccountDeletedListCheckPresence(d *schema.ResourceData, m interface{}) (AccountCloudApiList, error) { + accountDeletedList := AccountCloudApiList{} + controller := m.(*ControllerCfg) + urlValues := &url.Values{} + + if page, ok := d.GetOk("page"); ok { + urlValues.Add("page", strconv.Itoa(page.(int))) + } + if size, ok := d.GetOk("size"); ok { + urlValues.Add("size", strconv.Itoa(size.(int))) + } + + log.Debugf("utilityAccountDeletedListCheckPresence: load") + accountDeletedListRaw, err := controller.decortAPICall("POST", accountListDeletedAPI, urlValues) + if err != nil { + return nil, err + } + + err = json.Unmarshal([]byte(accountDeletedListRaw), &accountDeletedList) + if err != nil { + return nil, err + } + + return accountDeletedList, nil +} diff --git a/samples/README.md b/samples/README.md index 291ac14..db5b79e 100644 --- a/samples/README.md +++ b/samples/README.md @@ -31,6 +31,7 @@ - account_counsumed_units_by_type - account_reserved_units - account_templates_list + - account_deleted_list - resources: - image - virtual_image diff --git a/samples/data_account_deleted_list/main.tf b/samples/data_account_deleted_list/main.tf new file mode 100644 index 0000000..7309fcd --- /dev/null +++ b/samples/data_account_deleted_list/main.tf @@ -0,0 +1,45 @@ +/* +Пример использования +Получение информации об удаленных аккаунтах +Информация предоставляется только по аккаунтам, удаленным без флага permanently +*/ +#Расскомментируйте этот код, +#и внесите необходимые правки в версию и путь, +#чтобы работать с установленным вручную (не через hashicorp provider registry) провайдером +/* +terraform { + required_providers { + decort = { + version = "1.1" + source = "digitalenergy.online/decort/decort" + } + } +} +*/ + +provider "decort" { + authenticator = "oauth2" + #controller_url = + controller_url = "https://ds1.digitalenergy.online" + #oauth2_url = + oauth2_url = "https://sso.digitalenergy.online" + allow_unverified_ssl = true +} + +data "decort_account_deleted_list" "adl" { + #номер страницы для отображения + #опциональный параметр + #тип - число + #если не задан - выводятся все доступные данные + #page = 2 + + #размер страницы + #опциональный параметр + #тип - число + #если не задан - выводятся все доступные данные + #size = 3 +} + +output "test" { + value = data.decort_account_deleted_list.adl +} From b70cdcabf669db273a6f860f100cf749a3d2f7b4 Mon Sep 17 00:00:00 2001 From: stSolo Date: Sat, 28 May 2022 19:23:17 +0300 Subject: [PATCH 23/51] Rename files --- ...nt_consumed_units.go => data_source_account_consumed_units.go} | 0 ...s_by_type.go => data_source_account_consumed_units_by_type.go} | 0 ...ccount_deleted_list.go => data_source_account_deleted_list.go} | 0 ...nt_reserved_units.go => data_source_account_reserved_units.go} | 0 ...nt_templates_list.go => data_source_account_templates_list.go} | 0 5 files changed, 0 insertions(+), 0 deletions(-) rename decort/{data_account_consumed_units.go => data_source_account_consumed_units.go} (100%) rename decort/{data_account_consumed_units_by_type.go => data_source_account_consumed_units_by_type.go} (100%) rename decort/{data_account_deleted_list.go => data_source_account_deleted_list.go} (100%) rename decort/{data_account_reserved_units.go => data_source_account_reserved_units.go} (100%) rename decort/{data_account_templates_list.go => data_source_account_templates_list.go} (100%) diff --git a/decort/data_account_consumed_units.go b/decort/data_source_account_consumed_units.go similarity index 100% rename from decort/data_account_consumed_units.go rename to decort/data_source_account_consumed_units.go diff --git a/decort/data_account_consumed_units_by_type.go b/decort/data_source_account_consumed_units_by_type.go similarity index 100% rename from decort/data_account_consumed_units_by_type.go rename to decort/data_source_account_consumed_units_by_type.go diff --git a/decort/data_account_deleted_list.go b/decort/data_source_account_deleted_list.go similarity index 100% rename from decort/data_account_deleted_list.go rename to decort/data_source_account_deleted_list.go diff --git a/decort/data_account_reserved_units.go b/decort/data_source_account_reserved_units.go similarity index 100% rename from decort/data_account_reserved_units.go rename to decort/data_source_account_reserved_units.go diff --git a/decort/data_account_templates_list.go b/decort/data_source_account_templates_list.go similarity index 100% rename from decort/data_account_templates_list.go rename to decort/data_source_account_templates_list.go From 95ab4e37c4927190364676745ff2c4bd95f762cf Mon Sep 17 00:00:00 2001 From: stSolo Date: Sat, 28 May 2022 19:53:41 +0300 Subject: [PATCH 24/51] Add data for flipgroups list --- decort/data_source_account_flipgroups_list.go | 194 ++++++++++++++++++ decort/models_api.go | 30 ++- decort/provider.go | 1 + decort/utility_account_flip_groups.go | 56 +++++ samples/data_account_flipgroups_list/main.tf | 38 ++++ 5 files changed, 316 insertions(+), 3 deletions(-) create mode 100644 decort/data_source_account_flipgroups_list.go create mode 100644 decort/utility_account_flip_groups.go create mode 100644 samples/data_account_flipgroups_list/main.tf diff --git a/decort/data_source_account_flipgroups_list.go b/decort/data_source_account_flipgroups_list.go new file mode 100644 index 0000000..dd83716 --- /dev/null +++ b/decort/data_source_account_flipgroups_list.go @@ -0,0 +1,194 @@ +/* +Copyright (c) 2019-2022 Digital Energy Cloud Solutions LLC. All Rights Reserved. +Author: Stanislav Solovev, + +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. +*/ + +/* +This file is part of Terraform (by Hashicorp) provider for Digital Energy Cloud Orchestration +Technology platfom. + +Visit https://github.com/rudecs/terraform-provider-decort for full source code package and updates. +*/ + +package decort + +import ( + "github.com/google/uuid" + "github.com/hashicorp/terraform-plugin-sdk/helper/schema" +) + +func flattenAccountFlipGroupsList(afgl AccountFlipGroupsList) []map[string]interface{} { + res := make([]map[string]interface{}, 0) + for _, afg := range afgl { + temp := map[string]interface{}{ + "account_id": afg.AccountId, + "client_type": afg.ClientType, + "conn_type": afg.ConnType, + "created_by": afg.CreatedBy, + "created_time": afg.CreatedTime, + "default_gw": afg.DefaultGW, + "deleted_by": afg.DeletedBy, + "deleted_time": afg.DeletedTime, + "desc": afg.Desc, + "gid": afg.GID, + "guid": afg.GUID, + "fg_id": afg.ID, + "ip": afg.IP, + "milestones": afg.Milestones, + "fg_name": afg.Name, + "net_id": afg.NetID, + "net_type": afg.NetType, + "netmask": afg.NetMask, + "status": afg.Status, + "updated_by": afg.UpdatedBy, + "updated_time": afg.UpdatedTime, + } + res = append(res, temp) + } + return res + +} + +func dataSourceAccountFlipGroupsListRead(d *schema.ResourceData, m interface{}) error { + accountFlipGroupsList, err := utilityAccountFlipGroupsListCheckPresence(d, m) + if err != nil { + return err + } + + id := uuid.New() + d.SetId(id.String()) + d.Set("items", flattenAccountFlipGroupsList(accountFlipGroupsList)) + + return nil +} + +func dataSourceAccountFlipGroupsListSchemaMake() map[string]*schema.Schema { + res := map[string]*schema.Schema{ + "account_id": { + Type: schema.TypeInt, + Required: true, + Description: "ID of the account", + }, + "items": { + Type: schema.TypeList, + Computed: true, + Description: "Search Result", + Elem: &schema.Resource{ + Schema: map[string]*schema.Schema{ + "account_id": { + Type: schema.TypeInt, + Computed: true, + }, + "client_type": { + Type: schema.TypeString, + Computed: true, + }, + "conn_type": { + Type: schema.TypeString, + Computed: true, + }, + "created_by": { + Type: schema.TypeString, + Computed: true, + }, + "created_time": { + Type: schema.TypeInt, + Computed: true, + }, + "default_gw": { + Type: schema.TypeString, + Computed: true, + }, + "deleted_by": { + Type: schema.TypeString, + Computed: true, + }, + "deleted_time": { + Type: schema.TypeInt, + Computed: true, + }, + "desc": { + Type: schema.TypeString, + Computed: true, + }, + "gid": { + Type: schema.TypeInt, + Computed: true, + }, + "guid": { + Type: schema.TypeInt, + Computed: true, + }, + "fg_id": { + Type: schema.TypeInt, + Computed: true, + }, + "ip": { + Type: schema.TypeString, + Computed: true, + }, + "milestones": { + Type: schema.TypeInt, + Computed: true, + }, + "fg_name": { + Type: schema.TypeString, + Computed: true, + }, + "net_id": { + Type: schema.TypeInt, + Computed: true, + }, + "net_type": { + Type: schema.TypeString, + Computed: true, + }, + "netmask": { + Type: schema.TypeInt, + Computed: true, + }, + "status": { + Type: schema.TypeString, + Computed: true, + }, + "updated_by": { + Type: schema.TypeString, + Computed: true, + }, + "updated_time": { + Type: schema.TypeInt, + Computed: true, + }, + }, + }, + }, + } + return res +} + +func dataSourceAccountFlipGroupsList() *schema.Resource { + return &schema.Resource{ + SchemaVersion: 1, + + Read: dataSourceAccountFlipGroupsListRead, + + Timeouts: &schema.ResourceTimeout{ + Read: &Timeout30s, + Default: &Timeout60s, + }, + + Schema: dataSourceAccountFlipGroupsListSchemaMake(), + } +} diff --git a/decort/models_api.go b/decort/models_api.go index 7e893eb..119f11e 100644 --- a/decort/models_api.go +++ b/decort/models_api.go @@ -1006,14 +1006,12 @@ const accountGetConsumedUnitsByTypeAPI = "/restmachine/cloudapi/account/getConsu const accountGetReservedUnitsAPI = "/restmachine/cloudapi/account/getReservedAccountUnits" const accountListAPI = "/restmachine/cloudapi/account/list" const accountListComputesAPI = "/restmachine/cloudapi/account/listComputes" -const accountListCSAPI = "/cloudapi/account/listCS" const accountListDeletedAPI = "/restmachine/cloudapi/account/listDeleted" const accountListDisksAPI = "/restmachine/cloudapi/account/listDisks" -const accountListFlipGroupsAPI = "/cloudapi/account/listFlipGroups" +const accountListFlipGroupsAPI = "/restmachine/cloudapi/account/listFlipGroups" const accountListRGAPI = "/restmachine/cloudapi/account/listRG" const accountListTemplatesAPI = "/restmachine/cloudapi/account/listTemplates" const accountListVinsAPI = "/restmachine/cloudapi/account/listVins" -const accountListVMsAPI = "/cloudapi/account/listVMs" const accountRestoreAPI = "/restmachine/cloudapi/account/restore" const accountUpdateAPI = "/restmachine/cloudapi/account/update" const accountUpdateUserAPI = "/restmachine/cloudapi/account/updateUser" @@ -1202,3 +1200,29 @@ type AccountTemplate struct { } type AccountTemplatesList []AccountTemplate + +type AccountFlipGroup struct { + AccountId int `json:"accountId"` + ClientType string `json:"clientType"` + ConnType string `json:"connType"` + CreatedBy string `json:"createdBy"` + CreatedTime int `json:"createdTime"` + DefaultGW string `json:"defaultGW"` + DeletedBy string `json:"deletedBy"` + DeletedTime int `json:"deletedTime"` + Desc string `json:"desc"` + GID int `json:"gid"` + GUID int `json:"guid"` + ID int `json:"id"` + IP string `json:"ip"` + Milestones int `json:"milestones"` + Name string `json:"name"` + NetID int `json:"netId"` + NetType string `json:"netType"` + NetMask int `json:"netmask"` + Status string `json:"status"` + UpdatedBy string `json:"updatedBy"` + UpdatedTime int `json:"updatedTime"` +} + +type AccountFlipGroupsList []AccountFlipGroup diff --git a/decort/provider.go b/decort/provider.go index 22c365e..030b263 100644 --- a/decort/provider.go +++ b/decort/provider.go @@ -151,6 +151,7 @@ func Provider() *schema.Provider { "decort_account_reserved_units": dataSourceAccountReservedUnits(), "decort_account_templates_list": dataSourceAccountTemplatessList(), "decort_account_deleted_list": dataSourceAccountDeletedList(), + "decort_account_flipgroups_list": dataSourceAccountFlipGroupsList(), // "decort_pfw": dataSourcePfw(), }, diff --git a/decort/utility_account_flip_groups.go b/decort/utility_account_flip_groups.go new file mode 100644 index 0000000..df2c36b --- /dev/null +++ b/decort/utility_account_flip_groups.go @@ -0,0 +1,56 @@ +/* +Copyright (c) 2019-2022 Digital Energy Cloud Solutions LLC. All Rights Reserved. +Author: Stanislav Solovev, , + +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. +*/ + +/* +This file is part of Terraform (by Hashicorp) provider for Digital Energy Cloud Orchestration +Technology platfom. + +Visit https://github.com/rudecs/terraform-provider-decort for full source code package and updates. +*/ + +package decort + +import ( + "encoding/json" + "net/url" + "strconv" + + log "github.com/sirupsen/logrus" + + "github.com/hashicorp/terraform-plugin-sdk/helper/schema" +) + +func utilityAccountFlipGroupsListCheckPresence(d *schema.ResourceData, m interface{}) (AccountFlipGroupsList, error) { + accountFlipGroupsList := AccountFlipGroupsList{} + controller := m.(*ControllerCfg) + urlValues := &url.Values{} + + urlValues.Add("accountId", strconv.Itoa(d.Get("account_id").(int))) + + log.Debugf("utilityAccountFlipGroupsListCheckPresence") + accountFlipGroupsListRaw, err := controller.decortAPICall("POST", accountListFlipGroupsAPI, urlValues) + if err != nil { + return nil, err + } + + err = json.Unmarshal([]byte(accountFlipGroupsListRaw), &accountFlipGroupsList) + if err != nil { + return nil, err + } + + return accountFlipGroupsList, nil +} diff --git a/samples/data_account_flipgroups_list/main.tf b/samples/data_account_flipgroups_list/main.tf new file mode 100644 index 0000000..134d621 --- /dev/null +++ b/samples/data_account_flipgroups_list/main.tf @@ -0,0 +1,38 @@ +/* +Пример использования +Получение информации о flipgroups, используемых аккаунтом + +*/ +#Расскомментируйте этот код, +#и внесите необходимые правки в версию и путь, +#чтобы работать с установленным вручную (не через hashicorp provider registry) провайдером +/* +terraform { + required_providers { + decort = { + version = "1.1" + source = "digitalenergy.online/decort/decort" + } + } +} +*/ + +provider "decort" { + authenticator = "oauth2" + #controller_url = + controller_url = "https://ds1.digitalenergy.online" + #oauth2_url = + oauth2_url = "https://sso.digitalenergy.online" + allow_unverified_ssl = true +} + +data "decort_account_flipgroups_list" "afgl" { + #id аккаунта + #обязательный параметр + #тип - число + account_id = 1111 +} + +output "test" { + value = data.decort_account_flipgroups_list.afgl +} From c73a6e0d71eacae05f7c35d5a6def70d0a9f73dd Mon Sep 17 00:00:00 2001 From: stSolo Date: Mon, 30 May 2022 11:38:26 +0300 Subject: [PATCH 25/51] Fix resource account, add comment for a resource account sample --- decort/resource_account.go | 91 +++++++++++++++++++---- samples/resource_account/main.tf | 122 ++++++++++++++++++++++++++++--- 2 files changed, 189 insertions(+), 24 deletions(-) diff --git a/decort/resource_account.go b/decort/resource_account.go index 05cd238..a113092 100644 --- a/decort/resource_account.go +++ b/decort/resource_account.go @@ -69,24 +69,56 @@ func resourceAccountCreate(d *schema.ResourceData, m interface{}) error { if resLimits, ok := d.GetOk("resource_limits"); ok { resLimit := resLimits.([]interface{})[0] resLimitConv := resLimit.(map[string]interface{}) - if resLimitConv["cu_m"] != nil { - urlValues.Add("maxMemoryCapacity", strconv.Itoa(int(resLimitConv["cu_m"].(float64)))) + maxMemCap := int(resLimitConv["cu_m"].(float64)) + if maxMemCap == 0 { + urlValues.Add("maxMemoryCapacity", strconv.Itoa(-1)) + } else { + urlValues.Add("maxMemoryCapacity", strconv.Itoa(maxMemCap)) + } } if resLimitConv["cu_d"] != nil { - urlValues.Add("maxVDiskCapacity", strconv.Itoa(int(resLimitConv["cu_d"].(float64)))) + maxDiskCap := int(resLimitConv["cu_d"].(float64)) + if maxDiskCap == 0 { + urlValues.Add("maxVDiskCapacity", strconv.Itoa(-1)) + } else { + urlValues.Add("maxVDiskCapacity", strconv.Itoa(maxDiskCap)) + } } if resLimitConv["cu_c"] != nil { - urlValues.Add("maxCPUCapacity", strconv.Itoa(int(resLimitConv["cu_c"].(float64)))) + maxCPUCap := int(resLimitConv["cu_c"].(float64)) + if maxCPUCap == 0 { + urlValues.Add("maxCPUCapacity", strconv.Itoa(-1)) + } else { + urlValues.Add("maxCPUCapacity", strconv.Itoa(maxCPUCap)) + } + } if resLimitConv["cu_i"] != nil { - urlValues.Add("maxNumPublicIP", strconv.Itoa(int(resLimitConv["cu_i"].(float64)))) + maxNumPublicIP := int(resLimitConv["cu_i"].(float64)) + if maxNumPublicIP == 0 { + urlValues.Add("maxNumPublicIP", strconv.Itoa(-1)) + } else { + urlValues.Add("maxNumPublicIP", strconv.Itoa(maxNumPublicIP)) + } + } if resLimitConv["cu_np"] != nil { - urlValues.Add("maxNetworkPeerTransfer", strconv.Itoa(int(resLimitConv["cu_np"].(float64)))) + maxNP := int(resLimitConv["cu_np"].(float64)) + if maxNP == 0 { + urlValues.Add("maxNetworkPeerTransfer", strconv.Itoa(-1)) + } else { + urlValues.Add("maxNetworkPeerTransfer", strconv.Itoa(maxNP)) + } + } if resLimitConv["gpu_units"] != nil { - urlValues.Add("gpu_units", strconv.Itoa(int(resLimitConv["gpu_units"].(float64)))) + gpuUnits := int(resLimitConv["gpu_units"].(float64)) + if gpuUnits == 0 { + urlValues.Add("gpu_units", strconv.Itoa(-1)) + } else { + urlValues.Add("gpu_units", strconv.Itoa(gpuUnits)) + } } } @@ -223,22 +255,55 @@ func resourceAccountEdit(d *schema.ResourceData, m interface{}) error { resLimitConv := resLimit.(map[string]interface{}) if resLimitConv["cu_m"] != nil { - urlValues.Add("maxMemoryCapacity", strconv.Itoa(int(resLimitConv["cu_m"].(float64)))) + maxMemCap := int(resLimitConv["cu_m"].(float64)) + if maxMemCap == 0 { + urlValues.Add("maxMemoryCapacity", strconv.Itoa(-1)) + } else { + urlValues.Add("maxMemoryCapacity", strconv.Itoa(maxMemCap)) + } } if resLimitConv["cu_d"] != nil { - urlValues.Add("maxVDiskCapacity", strconv.Itoa(int(resLimitConv["cu_d"].(float64)))) + maxDiskCap := int(resLimitConv["cu_d"].(float64)) + if maxDiskCap == 0 { + urlValues.Add("maxVDiskCapacity", strconv.Itoa(-1)) + } else { + urlValues.Add("maxVDiskCapacity", strconv.Itoa(maxDiskCap)) + } } if resLimitConv["cu_c"] != nil { - urlValues.Add("maxCPUCapacity", strconv.Itoa(int(resLimitConv["cu_c"].(float64)))) + maxCPUCap := int(resLimitConv["cu_c"].(float64)) + if maxCPUCap == 0 { + urlValues.Add("maxCPUCapacity", strconv.Itoa(-1)) + } else { + urlValues.Add("maxCPUCapacity", strconv.Itoa(maxCPUCap)) + } + } if resLimitConv["cu_i"] != nil { - urlValues.Add("maxNumPublicIP", strconv.Itoa(int(resLimitConv["cu_i"].(float64)))) + maxNumPublicIP := int(resLimitConv["cu_i"].(float64)) + if maxNumPublicIP == 0 { + urlValues.Add("maxNumPublicIP", strconv.Itoa(-1)) + } else { + urlValues.Add("maxNumPublicIP", strconv.Itoa(maxNumPublicIP)) + } + } if resLimitConv["cu_np"] != nil { - urlValues.Add("maxNetworkPeerTransfer", strconv.Itoa(int(resLimitConv["cu_np"].(float64)))) + maxNP := int(resLimitConv["cu_np"].(float64)) + if maxNP == 0 { + urlValues.Add("maxNetworkPeerTransfer", strconv.Itoa(-1)) + } else { + urlValues.Add("maxNetworkPeerTransfer", strconv.Itoa(maxNP)) + } + } if resLimitConv["gpu_units"] != nil { - urlValues.Add("gpu_units", strconv.Itoa(int(resLimitConv["gpu_units"].(float64)))) + gpuUnits := int(resLimitConv["gpu_units"].(float64)) + if gpuUnits == 0 { + urlValues.Add("gpu_units", strconv.Itoa(-1)) + } else { + urlValues.Add("gpu_units", strconv.Itoa(gpuUnits)) + } } urlValues.Add("accountId", strconv.Itoa(d.Get("account_id").(int))) diff --git a/samples/resource_account/main.tf b/samples/resource_account/main.tf index 1b456be..f8bcf72 100644 --- a/samples/resource_account/main.tf +++ b/samples/resource_account/main.tf @@ -1,16 +1,16 @@ /* Пример использования -Ресурса cdrom image +Ресурса account Ресурс позволяет: -1. Создавать образ -2. Редактировать образ -3. Удалять образ +1. Создавать аккаунт +2. Редактировать аккаунт +3. Удалять аккаунт */ #Расскомментируйте этот код, #и внесите необходимые правки в версию и путь, #чтобы работать с установленным вручную (не через hashicorp provider registry) провайдером - +/* terraform { required_providers { decort = { @@ -19,7 +19,7 @@ terraform { } } } - +*/ provider "decort" { authenticator = "oauth2" @@ -31,26 +31,126 @@ provider "decort" { } resource "decort_account" "a" { - #id аккаунта + #имя аккаунта + #обязательный параметр + #тип - строка + #используется при создании и редактировании аккаунта + account_name = "new_my_account" + + #имя пользователя - создателя аккаунта #обязательный параметр + #тип - строка + username = "username@decs3o" + + #доступность аккаунта + #необязательный параметр + #тип - будев тип + #может применяться при редактировании аккаунта + enable = true + + #id аккаунта, позволяет сформировать .tfstate, если аккаунт имеет в платформе + #необязательный параметр #тип - число - account_id = 11111 - account_name = "new_my_account" - username = "isername@decs3o" - enable = true + account_id = 11111 + + #электронная почта, на которую будет отправлена информация о доступе + #необязательный параметр + #тип - строка + #применяется при создании аккаунта + emailaddress = "fff@fff.ff" + + #отправлять ли на электронную почту письмо о доступе + #необязательный параметр + #тип - булев тип + #применяется при создании аккаунта и редактировании аккаунта send_access_emails = true + + #добавление/редактирование/удаление пользователей, к которым привязан аккаунт + #необязательный параметр + #тип - объект, кол-во таких объектов не ограничено /*users { + #id пользователя + #обязательный параметр + #тип - строка user_id = "username_2@decs3o" + + #тип доступа пользователя + #обязательный параметр + #тип - строка + #возможные параметры: + #R - чтение + #RCX - запись + #ARCXDU - админ access_type = "R" + + #рекурсивное удаление пользователя из всех ресурсов аккаунтов + #необязательный параметр + #тип - булев тип + #по-умолчанию - false + #применяется при удалении пользователя из аккаунта + recursive_delete = true } users { user_id = "username_1@decs3o" access_type = "R" }*/ + + #ограничение используемых ресурсов + #необязательный параметр + #тип - объект + #используется при создании и редактировании resource_limits { + #кол-во используемых ядер cpu + #необязательный параметр + #тип - ичсло + #если установлена -1 - кол-во неограичено + cu_c = 2 + + #кол-во используемой RAM в МБ + #необязательный параметр + #тип - ичсло + #если установлена -1 - кол-во неограичено cu_m = 1024 + + #размер дисков, в ГБ + #необязательный параметр + #тип - ичсло + #если установлена -1 - размер неограичен + cu_d = 23 + + #кол-во используемых публичных IP + #необязательный параметр + #тип - ичсло + #если установлена -1 - кол-во неограичено + cu_i = 2 + + #ограничения на кол-во передачи данных, в ГБ + #необязательный параметр + #тип - ичсло + #если установлена -1 - кол-во неограичено + cu_np = 2 + + #кол-во графических процессоров + #необязательный параметр + #тип - ичсло + #если установлена -1 - кол-во неограичено + gpu_units = 2 } + #восстановление аккаунта + #необязательный параметр + #тип - булев тип + #применяется к удаленным аккаунтам + #по-умолчанию - false + #retore = false + + #мгновеное удаление аккаунта, если да - то аккаунт невозможно будет восстановить + #необязательный параметр + #тип - булев тип + #используется при удалении аккаунта + #по-умолчанию - false + #permanently = true + } From 8d1b13f7b798143ef13085b24f80904760dd0f81 Mon Sep 17 00:00:00 2001 From: stSolo Date: Fri, 3 Jun 2022 11:22:42 +0300 Subject: [PATCH 26/51] Add bservice, extnet, vins --- README.md | 3 +- README_EN.md | 3 +- decort/data_source_bservice.go | 293 ++++++++ decort/data_source_bservice_deleted_list.go | 58 ++ decort/data_source_bservice_group.go | 291 ++++++++ decort/data_source_bservice_list.go | 215 ++++++ decort/data_source_bservice_snapshot_list.go | 93 +++ decort/data_source_extnet.go | 321 +++++++++ decort/data_source_extnet_computes_list.go | 156 +++++ decort/data_source_extnet_default.go | 74 +++ decort/data_source_extnet_list.go | 112 ++++ decort/data_source_vins_list.go | 178 +++++ decort/models_api.go | 258 ++++++++ decort/provider.go | 44 +- decort/resource_account.go | 4 +- decort/resource_bservice.go | 554 ++++++++++++++++ decort/resource_bservice_group.go | 660 +++++++++++++++++++ decort/utility_bservicce_deleted_list.go | 67 ++ decort/utility_bservice.go | 60 ++ decort/utility_bservice_group.go | 61 ++ decort/utility_bservice_list.go | 67 ++ decort/utility_bservice_snapshot_list.go | 58 ++ decort/utility_extnet.go | 56 ++ decort/utility_extnet_computes_list.go | 56 ++ decort/utility_extnet_default.go | 46 ++ decort/utility_extnet_list.go | 64 ++ decort/utility_vins_list.go | 64 ++ samples/README.md | 10 + samples/data_bservice/main.tf | 39 ++ samples/data_bservice_deleted_list/main.tf | 57 ++ samples/data_bservice_group/main.tf | 44 ++ samples/data_bservice_list/main.tf | 58 ++ samples/data_bservice_snapshot_list/main.tf | 39 ++ samples/data_extnet/main.tf | 38 ++ samples/data_extnet_computes_list/main.tf | 37 ++ samples/data_extnet_default/main.tf | 36 + samples/data_extnet_list/main.tf | 48 ++ samples/data_vins_list/main.tf | 51 ++ samples/resource_bservice/main.tf | 110 ++++ samples/resource_bservice_group/main.tf | 150 +++++ 40 files changed, 4613 insertions(+), 20 deletions(-) create mode 100644 decort/data_source_bservice.go create mode 100644 decort/data_source_bservice_deleted_list.go create mode 100644 decort/data_source_bservice_group.go create mode 100644 decort/data_source_bservice_list.go create mode 100644 decort/data_source_bservice_snapshot_list.go create mode 100644 decort/data_source_extnet.go create mode 100644 decort/data_source_extnet_computes_list.go create mode 100644 decort/data_source_extnet_default.go create mode 100644 decort/data_source_extnet_list.go create mode 100644 decort/data_source_vins_list.go create mode 100644 decort/resource_bservice.go create mode 100644 decort/resource_bservice_group.go create mode 100644 decort/utility_bservicce_deleted_list.go create mode 100644 decort/utility_bservice.go create mode 100644 decort/utility_bservice_group.go create mode 100644 decort/utility_bservice_list.go create mode 100644 decort/utility_bservice_snapshot_list.go create mode 100644 decort/utility_extnet.go create mode 100644 decort/utility_extnet_computes_list.go create mode 100644 decort/utility_extnet_default.go create mode 100644 decort/utility_extnet_list.go create mode 100644 decort/utility_vins_list.go create mode 100644 samples/data_bservice/main.tf create mode 100644 samples/data_bservice_deleted_list/main.tf create mode 100644 samples/data_bservice_group/main.tf create mode 100644 samples/data_bservice_list/main.tf create mode 100644 samples/data_bservice_snapshot_list/main.tf create mode 100644 samples/data_extnet/main.tf create mode 100644 samples/data_extnet_computes_list/main.tf create mode 100644 samples/data_extnet_default/main.tf create mode 100644 samples/data_extnet_list/main.tf create mode 100644 samples/data_vins_list/main.tf create mode 100644 samples/resource_bservice/main.tf create mode 100644 samples/resource_bservice_group/main.tf diff --git a/README.md b/README.md index a53f213..3981b12 100644 --- a/README.md +++ b/README.md @@ -18,7 +18,8 @@ Terraform provider для платформы Digital Energy Cloud Orchestration - Работа с snapshots, - Работа с pcidevice, - Работа с sep, -- Работа с vgpu. +- Работа с vgpu, +- Работа с bservice. Вики проекта: https://github.com/rudecs/terraform-provider-decort/wiki diff --git a/README_EN.md b/README_EN.md index db2650f..87bcea6 100644 --- a/README_EN.md +++ b/README_EN.md @@ -17,7 +17,8 @@ NOTE: provider rc-1.25 is designed for DECORT API 3.7.x. For older API versions - Work with snapshots, - Work with pcidevice. - Work with sep, -- Work with vgpu. +- Work with vgpu, +- Work with bservice. This provider supports Import operations on pre-existing resources. diff --git a/decort/data_source_bservice.go b/decort/data_source_bservice.go new file mode 100644 index 0000000..a013981 --- /dev/null +++ b/decort/data_source_bservice.go @@ -0,0 +1,293 @@ +/* +Copyright (c) 2019-2022 Digital Energy Cloud Solutions LLC. All Rights Reserved. +Author: Stanislav Solovev, + +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. +*/ + +/* +This file is part of Terraform (by Hashicorp) provider for Digital Energy Cloud Orchestration +Technology platfom. + +Visit https://github.com/rudecs/terraform-provider-decort for full source code package and updates. +*/ + +package decort + +import ( + "github.com/google/uuid" + "github.com/hashicorp/terraform-plugin-sdk/helper/schema" +) + +func dataSourceBasicServiceRead(d *schema.ResourceData, m interface{}) error { + bs, err := utilityBasicServiceCheckPresence(d, m) + if err != nil { + return err + } + + id := uuid.New() + d.SetId(id.String()) + d.Set("account_id", bs.AccountId) + d.Set("account_name", bs.AccountName) + d.Set("base_domain", bs.BaseDomain) + d.Set("computes", flattenBasicServiceComputes(bs.Computes)) + d.Set("cpu_total", bs.CPUTotal) + d.Set("created_by", bs.CreatedBy) + d.Set("created_time", bs.CreatedTime) + d.Set("deleted_by", bs.DeletedBy) + d.Set("deleted_time", bs.DeletedTime) + d.Set("disk_total", bs.DiskTotal) + d.Set("gid", bs.GID) + d.Set("groups", bs.Groups) + d.Set("groups_name", bs.GroupsName) + d.Set("guid", bs.GUID) + d.Set("milestones", bs.Milestones) + d.Set("service_name", bs.Name) + d.Set("parent_srv_id", bs.ParentSrvId) + d.Set("parent_srv_type", bs.ParentSrvType) + d.Set("ram_total", bs.RamTotal) + d.Set("rg_id", bs.RGID) + d.Set("rg_name", bs.RGName) + d.Set("snapshots", flattenBasicServiceSnapshots(bs.Snapshots)) + d.Set("ssh_key", bs.SSHKey) + d.Set("ssh_user", bs.SSHUser) + d.Set("status", bs.Status) + d.Set("tech_status", bs.TechStatus) + d.Set("updated_by", bs.UpdatedBy) + d.Set("updated_time", bs.UpdatedTime) + d.Set("user_managed", bs.UserManaged) + return nil +} + +func flattenBasicServiceComputes(bscs BasicServiceComputes) []map[string]interface{} { + res := make([]map[string]interface{}, 0) + for _, bsc := range bscs { + temp := map[string]interface{}{ + "compgroup_id": bsc.CompGroupId, + "compgroup_name": bsc.CompGroupName, + "compgroup_role": bsc.CompGroupRole, + "id": bsc.ID, + "name": bsc.Name, + } + res = append(res, temp) + } + + return res +} + +func flattenBasicServiceSnapshots(bsrvss BasicServiceSnapshots) []map[string]interface{} { + res := make([]map[string]interface{}, 0) + for _, bsrvs := range bsrvss { + temp := map[string]interface{}{ + "guid": bsrvs.GUID, + "label": bsrvs.Label, + "timestamp": bsrvs.Timestamp, + "valid": bsrvs.Valid, + } + res = append(res, temp) + } + return res +} + +func dataSourceBasicServiceSchemaMake() map[string]*schema.Schema { + res := map[string]*schema.Schema{ + "service_id": { + Type: schema.TypeInt, + Required: true, + }, + "account_id": { + Type: schema.TypeInt, + Computed: true, + }, + "account_name": { + Type: schema.TypeString, + Computed: true, + }, + "base_domain": { + Type: schema.TypeString, + Computed: true, + }, + "computes": { + Type: schema.TypeList, + Computed: true, + Elem: &schema.Resource{ + Schema: map[string]*schema.Schema{ + "compgroup_id": { + Type: schema.TypeInt, + Computed: true, + }, + "compgroup_name": { + Type: schema.TypeString, + Computed: true, + }, + "compgroup_role": { + Type: schema.TypeString, + Computed: true, + }, + "id": { + Type: schema.TypeInt, + Computed: true, + }, + "name": { + Type: schema.TypeString, + Computed: true, + }, + }, + }, + }, + + "cpu_total": { + Type: schema.TypeInt, + Computed: true, + }, + "created_by": { + Type: schema.TypeString, + Computed: true, + }, + "created_time": { + Type: schema.TypeInt, + Computed: true, + }, + "deleted_by": { + Type: schema.TypeString, + Computed: true, + }, + "deleted_time": { + Type: schema.TypeInt, + Computed: true, + }, + "disk_total": { + Type: schema.TypeString, + Computed: true, + }, + "gid": { + Type: schema.TypeInt, + Computed: true, + }, + "groups": { + Type: schema.TypeList, + Computed: true, + Elem: &schema.Schema{ + Type: schema.TypeInt, + }, + }, + "groups_name": { + Type: schema.TypeList, + Computed: true, + Elem: &schema.Schema{ + Type: schema.TypeString, + }, + }, + "guid": { + Type: schema.TypeInt, + Computed: true, + }, + "milestones": { + Type: schema.TypeInt, + Computed: true, + }, + "service_name": { + Type: schema.TypeString, + Computed: true, + }, + "parent_srv_id": { + Type: schema.TypeInt, + Computed: true, + }, + "parent_srv_type": { + Type: schema.TypeString, + Computed: true, + }, + "ram_total": { + Type: schema.TypeInt, + Computed: true, + }, + "rg_id": { + Type: schema.TypeInt, + Computed: true, + }, + "rg_name": { + Type: schema.TypeString, + Computed: true, + }, + "snapshots": { + Type: schema.TypeList, + Computed: true, + Elem: &schema.Resource{ + Schema: map[string]*schema.Schema{ + "guid": { + Type: schema.TypeString, + Computed: true, + }, + "label": { + Type: schema.TypeString, + Computed: true, + }, + "timestamp": { + Type: schema.TypeInt, + Computed: true, + }, + "valid": { + Type: schema.TypeBool, + Computed: true, + }, + }, + }, + }, + + "ssh_key": { + Type: schema.TypeString, + Computed: true, + }, + "ssh_user": { + Type: schema.TypeString, + Computed: true, + }, + "status": { + Type: schema.TypeString, + Computed: true, + }, + "tech_status": { + Type: schema.TypeString, + Computed: true, + }, + "updated_by": { + Type: schema.TypeString, + Computed: true, + }, + "updated_time": { + Type: schema.TypeInt, + Computed: true, + }, + "user_managed": { + Type: schema.TypeBool, + Computed: true, + }, + } + return res +} + +func dataSourceBasicService() *schema.Resource { + return &schema.Resource{ + SchemaVersion: 1, + + Read: dataSourceBasicServiceRead, + + Timeouts: &schema.ResourceTimeout{ + Read: &Timeout30s, + Default: &Timeout60s, + }, + + Schema: dataSourceBasicServiceSchemaMake(), + } +} diff --git a/decort/data_source_bservice_deleted_list.go b/decort/data_source_bservice_deleted_list.go new file mode 100644 index 0000000..3f4dce8 --- /dev/null +++ b/decort/data_source_bservice_deleted_list.go @@ -0,0 +1,58 @@ +/* +Copyright (c) 2019-2022 Digital Energy Cloud Solutions LLC. All Rights Reserved. +Author: Stanislav Solovev, + +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. +*/ + +/* +This file is part of Terraform (by Hashicorp) provider for Digital Energy Cloud Orchestration +Technology platfom. + +Visit https://github.com/rudecs/terraform-provider-decort for full source code package and updates. +*/ + +package decort + +import ( + "github.com/google/uuid" + "github.com/hashicorp/terraform-plugin-sdk/helper/schema" +) + +func dataSourceBasicServiceDeletedListRead(d *schema.ResourceData, m interface{}) error { + basicServiceDeletedList, err := utilityBasicServiceDeletedListCheckPresence(d, m) + if err != nil { + return err + } + + id := uuid.New() + d.SetId(id.String()) + d.Set("items", flattenBasicServiceList(basicServiceDeletedList)) + + return nil +} + +func dataSourceBasicServiceDeletedList() *schema.Resource { + return &schema.Resource{ + SchemaVersion: 1, + + Read: dataSourceBasicServiceDeletedListRead, + + Timeouts: &schema.ResourceTimeout{ + Read: &Timeout30s, + Default: &Timeout60s, + }, + + Schema: dataSourceBasicServiceListSchemaMake(), + } +} diff --git a/decort/data_source_bservice_group.go b/decort/data_source_bservice_group.go new file mode 100644 index 0000000..b8c3d92 --- /dev/null +++ b/decort/data_source_bservice_group.go @@ -0,0 +1,291 @@ +/* +Copyright (c) 2019-2022 Digital Energy Cloud Solutions LLC. All Rights Reserved. +Author: Stanislav Solovev, + +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. +*/ + +/* +This file is part of Terraform (by Hashicorp) provider for Digital Energy Cloud Orchestration +Technology platfom. + +Visit https://github.com/rudecs/terraform-provider-decort for full source code package and updates. +*/ + +package decort + +import ( + "github.com/google/uuid" + "github.com/hashicorp/terraform-plugin-sdk/helper/schema" +) + +func dataSourceBasicServiceGroupRead(d *schema.ResourceData, m interface{}) error { + bsg, err := utilityBasicServiceGroupCheckPresence(d, m) + if err != nil { + return err + } + + id := uuid.New() + d.SetId(id.String()) + d.Set("account_id", bsg.AccountId) + d.Set("account_name", bsg.AccountName) + d.Set("computes", flattenBSGroupComputes(bsg.Computes)) + d.Set("consistency", bsg.Consistency) + d.Set("cpu", bsg.CPU) + d.Set("created_by", bsg.CreatedBy) + d.Set("created_time", bsg.CreatedTime) + d.Set("deleted_by", bsg.DeletedBy) + d.Set("deleted_time", bsg.DeletedTime) + d.Set("disk", bsg.Disk) + d.Set("driver", bsg.Driver) + d.Set("extnets", bsg.Extnets) + d.Set("gid", bsg.GID) + d.Set("guid", bsg.GUID) + d.Set("image_id", bsg.ImageId) + d.Set("milestones", bsg.Milestones) + d.Set("compgroup_name", bsg.Name) + d.Set("parents", bsg.Parents) + d.Set("ram", bsg.RAM) + d.Set("rg_id", bsg.RGID) + d.Set("rg_name", bsg.RGName) + d.Set("role", bsg.Role) + d.Set("sep_id", bsg.SepId) + d.Set("seq_no", bsg.SeqNo) + d.Set("status", bsg.Status) + d.Set("tech_status", bsg.TechStatus) + d.Set("timeout_start", bsg.TimeoutStart) + d.Set("updated_by", bsg.UpdatedBy) + d.Set("updated_time", bsg.UpdatedTime) + d.Set("vinses", bsg.Vinses) + return nil +} + +func flattenBSGroupOSUsers(bsgosus BasicServiceGroupOSUsers) []map[string]interface{} { + res := make([]map[string]interface{}, 0) + for _, bsgosu := range bsgosus { + temp := map[string]interface{}{ + "login": bsgosu.Login, + "password": bsgosu.Password, + } + res = append(res, temp) + } + + return res +} + +func flattenBSGroupComputes(bsgcs BasicServiceGroupComputes) []map[string]interface{} { + res := make([]map[string]interface{}, 0) + for _, bsgc := range bsgcs { + temp := map[string]interface{}{ + "id": bsgc.ID, + "ip_addresses": bsgc.IPAdresses, + "name": bsgc.Name, + "os_users": flattenBSGroupOSUsers(bsgc.OSUsers), + } + res = append(res, temp) + } + return res +} + +func dataSourceBasicServiceGroupSchemaMake() map[string]*schema.Schema { + res := map[string]*schema.Schema{ + "service_id": { + Type: schema.TypeInt, + Required: true, + }, + "compgroup_id": { + Type: schema.TypeInt, + Required: true, + }, + "account_id": { + Type: schema.TypeInt, + Computed: true, + }, + "account_name": { + Type: schema.TypeString, + Computed: true, + }, + "computes": { + Type: schema.TypeList, + Computed: true, + Elem: &schema.Resource{ + Schema: map[string]*schema.Schema{ + "id": { + Type: schema.TypeInt, + Computed: true, + }, + "ip_addresses": { + Type: schema.TypeList, + Computed: true, + Elem: &schema.Schema{ + Type: schema.TypeString, + }, + }, + "name": { + Type: schema.TypeString, + Computed: true, + }, + "os_users": { + Type: schema.TypeList, + Computed: true, + Elem: &schema.Resource{ + Schema: map[string]*schema.Schema{ + "login": { + Type: schema.TypeString, + Computed: true, + }, + "password": { + Type: schema.TypeString, + Computed: true, + }, + }, + }, + }, + }, + }, + }, + "consistency": { + Type: schema.TypeBool, + Computed: true, + }, + "cpu": { + Type: schema.TypeInt, + Computed: true, + }, + "created_by": { + Type: schema.TypeString, + Computed: true, + }, + "created_time": { + Type: schema.TypeInt, + Computed: true, + }, + "deleted_by": { + Type: schema.TypeString, + Computed: true, + }, + "deleted_time": { + Type: schema.TypeInt, + Computed: true, + }, + "disk": { + Type: schema.TypeInt, + Computed: true, + }, + "driver": { + Type: schema.TypeString, + Computed: true, + }, + "extnets": { + Type: schema.TypeList, + Computed: true, + Elem: &schema.Schema{ + Type: schema.TypeInt, + }, + }, + "gid": { + Type: schema.TypeInt, + Computed: true, + }, + "guid": { + Type: schema.TypeInt, + Computed: true, + }, + "image_id": { + Type: schema.TypeInt, + Computed: true, + }, + "milestones": { + Type: schema.TypeInt, + Computed: true, + }, + "compgroup_name": { + Type: schema.TypeString, + Computed: true, + }, + "parents": { + Type: schema.TypeList, + Computed: true, + Elem: &schema.Schema{ + Type: schema.TypeInt, + }, + }, + "ram": { + Type: schema.TypeInt, + Computed: true, + }, + "rg_id": { + Type: schema.TypeInt, + Computed: true, + }, + "rg_name": { + Type: schema.TypeString, + Computed: true, + }, + "role": { + Type: schema.TypeString, + Computed: true, + }, + "sep_id": { + Type: schema.TypeInt, + Computed: true, + }, + "seq_no": { + Type: schema.TypeInt, + Computed: true, + }, + "status": { + Type: schema.TypeString, + Computed: true, + }, + "tech_status": { + Type: schema.TypeString, + Computed: true, + }, + "timeout_start": { + Type: schema.TypeInt, + Computed: true, + }, + "updated_by": { + Type: schema.TypeString, + Computed: true, + }, + "updated_time": { + Type: schema.TypeInt, + Computed: true, + }, + "vinses": { + Type: schema.TypeList, + Computed: true, + Elem: &schema.Schema{ + Type: schema.TypeInt, + }, + }, + } + return res +} + +func dataSourceBasicServiceGroup() *schema.Resource { + return &schema.Resource{ + SchemaVersion: 1, + + Read: dataSourceBasicServiceGroupRead, + + Timeouts: &schema.ResourceTimeout{ + Read: &Timeout30s, + Default: &Timeout60s, + }, + + Schema: dataSourceBasicServiceGroupSchemaMake(), + } +} diff --git a/decort/data_source_bservice_list.go b/decort/data_source_bservice_list.go new file mode 100644 index 0000000..21ead41 --- /dev/null +++ b/decort/data_source_bservice_list.go @@ -0,0 +1,215 @@ +/* +Copyright (c) 2019-2022 Digital Energy Cloud Solutions LLC. All Rights Reserved. +Author: Stanislav Solovev, + +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. +*/ + +/* +This file is part of Terraform (by Hashicorp) provider for Digital Energy Cloud Orchestration +Technology platfom. + +Visit https://github.com/rudecs/terraform-provider-decort for full source code package and updates. +*/ + +package decort + +import ( + "github.com/google/uuid" + "github.com/hashicorp/terraform-plugin-sdk/helper/schema" +) + +func flattenBasicServiceList(bsl BasicServiceList) []map[string]interface{} { + res := make([]map[string]interface{}, 0) + for _, bs := range bsl { + temp := map[string]interface{}{ + "account_id": bs.AccountId, + "account_name": bs.AccountName, + "base_domain": bs.BaseDomain, + "created_by": bs.CreatedBy, + "created_time": bs.CreatedTime, + "deleted_by": bs.DeletedBy, + "deleted_time": bs.DeletedTime, + "gid": bs.GID, + "groups": bs.Groups, + "guid": bs.GUID, + "service_id": bs.ID, + "service_name": bs.Name, + "parent_srv_id": bs.ParentSrvId, + "parent_srv_type": bs.ParentSrvType, + "rg_id": bs.RGID, + "rg_name": bs.RGName, + "ssh_user": bs.SSHUser, + "status": bs.Status, + "tech_status": bs.TechStatus, + "updated_by": bs.UpdatedBy, + "updated_time": bs.UpdatedTime, + "user_managed": bs.UserManaged, + } + res = append(res, temp) + } + return res +} + +func dataSourceBasicServiceListRead(d *schema.ResourceData, m interface{}) error { + basicServiceList, err := utilityBasicServiceListCheckPresence(d, m) + if err != nil { + return err + } + + id := uuid.New() + d.SetId(id.String()) + d.Set("items", flattenBasicServiceList(basicServiceList)) + + return nil +} + +func dataSourceBasicServiceListSchemaMake() map[string]*schema.Schema { + res := map[string]*schema.Schema{ + "account_id": { + Type: schema.TypeInt, + Optional: true, + Description: "ID of the account to query for BasicService instances", + }, + "rg_id": { + Type: schema.TypeInt, + Optional: true, + Description: "ID of the resource group to query for BasicService instances", + }, + "page": { + Type: schema.TypeInt, + Optional: true, + Description: "Page number", + }, + "size": { + Type: schema.TypeInt, + Optional: true, + Description: "Page size", + }, + "items": { + Type: schema.TypeList, + Computed: true, + Elem: &schema.Resource{ + Schema: map[string]*schema.Schema{ + "account_id": { + Type: schema.TypeInt, + Computed: true, + }, + "account_name": { + Type: schema.TypeString, + Computed: true, + }, + "base_domain": { + Type: schema.TypeString, + Computed: true, + }, + "created_by": { + Type: schema.TypeString, + Computed: true, + }, + "created_time": { + Type: schema.TypeInt, + Computed: true, + }, + "deleted_by": { + Type: schema.TypeString, + Computed: true, + }, + "deleted_time": { + Type: schema.TypeInt, + Computed: true, + }, + "gid": { + Type: schema.TypeInt, + Computed: true, + }, + "groups": { + Type: schema.TypeList, + Computed: true, + Elem: &schema.Schema{ + Type: schema.TypeInt, + }, + }, + "guid": { + Type: schema.TypeInt, + Computed: true, + }, + "service_id": { + Type: schema.TypeInt, + Computed: true, + }, + "service_name": { + Type: schema.TypeString, + Computed: true, + }, + "parent_srv_id": { + Type: schema.TypeInt, + Computed: true, + }, + "parent_srv_type": { + Type: schema.TypeString, + Computed: true, + }, + "rg_id": { + Type: schema.TypeInt, + Computed: true, + }, + "rg_name": { + Type: schema.TypeString, + Computed: true, + }, + "ssh_user": { + Type: schema.TypeString, + Computed: true, + }, + "status": { + Type: schema.TypeString, + Computed: true, + }, + "tech_status": { + Type: schema.TypeString, + Computed: true, + }, + "updated_by": { + Type: schema.TypeString, + Computed: true, + }, + "updated_time": { + Type: schema.TypeInt, + Computed: true, + }, + "user_managed": { + Type: schema.TypeBool, + Computed: true, + }, + }, + }, + }, + } + return res +} + +func dataSourceBasicServiceList() *schema.Resource { + return &schema.Resource{ + SchemaVersion: 1, + + Read: dataSourceBasicServiceListRead, + + Timeouts: &schema.ResourceTimeout{ + Read: &Timeout30s, + Default: &Timeout60s, + }, + + Schema: dataSourceBasicServiceListSchemaMake(), + } +} diff --git a/decort/data_source_bservice_snapshot_list.go b/decort/data_source_bservice_snapshot_list.go new file mode 100644 index 0000000..306ce99 --- /dev/null +++ b/decort/data_source_bservice_snapshot_list.go @@ -0,0 +1,93 @@ +/* +Copyright (c) 2019-2022 Digital Energy Cloud Solutions LLC. All Rights Reserved. +Author: Stanislav Solovev, + +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. +*/ + +/* +This file is part of Terraform (by Hashicorp) provider for Digital Energy Cloud Orchestration +Technology platfom. + +Visit https://github.com/rudecs/terraform-provider-decort for full source code package and updates. +*/ + +package decort + +import ( + "github.com/google/uuid" + "github.com/hashicorp/terraform-plugin-sdk/helper/schema" +) + +func dataSourceBasicServiceSnapshotListRead(d *schema.ResourceData, m interface{}) error { + basicServiceSnapshotList, err := utilityBasicServiceSnapshotListCheckPresence(d, m) + if err != nil { + return err + } + + id := uuid.New() + d.SetId(id.String()) + d.Set("items", flattenBasicServiceSnapshots(basicServiceSnapshotList)) + + return nil +} + +func dataSourceBasicServiceSnapshotListSchemaMake() map[string]*schema.Schema { + res := map[string]*schema.Schema{ + "service_id": { + Type: schema.TypeInt, + Required: true, + Description: "ID of the BasicService instance", + }, + "items": { + Type: schema.TypeList, + Computed: true, + Elem: &schema.Resource{ + Schema: map[string]*schema.Schema{ + "guid": { + Type: schema.TypeString, + Computed: true, + }, + "label": { + Type: schema.TypeString, + Computed: true, + }, + "timestamp": { + Type: schema.TypeInt, + Computed: true, + }, + "valid": { + Type: schema.TypeBool, + Computed: true, + }, + }, + }, + }, + } + return res +} + +func dataSourceBasicServiceSnapshotList() *schema.Resource { + return &schema.Resource{ + SchemaVersion: 1, + + Read: dataSourceBasicServiceSnapshotListRead, + + Timeouts: &schema.ResourceTimeout{ + Read: &Timeout30s, + Default: &Timeout60s, + }, + + Schema: dataSourceBasicServiceSnapshotListSchemaMake(), + } +} diff --git a/decort/data_source_extnet.go b/decort/data_source_extnet.go new file mode 100644 index 0000000..e28445f --- /dev/null +++ b/decort/data_source_extnet.go @@ -0,0 +1,321 @@ +/* +Copyright (c) 2019-2022 Digital Energy Cloud Solutions LLC. All Rights Reserved. +Author: Stanislav Solovev, + +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. +*/ + +/* +This file is part of Terraform (by Hashicorp) provider for Digital Energy Cloud Orchestration +Technology platfom. + +Visit https://github.com/rudecs/terraform-provider-decort for full source code package and updates. +*/ + +package decort + +import ( + "github.com/google/uuid" + "github.com/hashicorp/terraform-plugin-sdk/helper/schema" +) + +func dataSourceExtnetRead(d *schema.ResourceData, m interface{}) error { + e, err := utilityExtnetCheckPresence(d, m) + if err != nil { + return err + } + + id := uuid.New() + d.SetId(id.String()) + d.Set("ckey", e.CKey) + d.Set("meta", flattenMeta(e.Meta)) + d.Set("check__ips", e.CheckIPs) + d.Set("check_ips", e.CheckIps) + d.Set("default", e.Default) + d.Set("default_qos", flattenExtnetDefaultQos(e.DefaultQos)) + d.Set("desc", e.Desc) + d.Set("dns", e.Dns) + d.Set("excluded", e.Excluded) + d.Set("free_ips", e.FreeIps) + d.Set("gateway", e.Gateway) + d.Set("gid", e.GID) + d.Set("guid", e.GUID) + d.Set("ipcidr", e.IPCidr) + d.Set("milestones", e.Milestones) + d.Set("net_name", e.Name) + d.Set("network", e.Network) + d.Set("network_id", e.NetworkId) + d.Set("pre_reservations_num", e.PreReservationsNum) + d.Set("prefix", e.Prefix) + d.Set("pri_vnf_dev_id", e.PriVnfDevId) + d.Set("reservations", flattenExtnetReservations(e.Reservations)) + d.Set("shared_with", e.SharedWith) + d.Set("status", e.Status) + d.Set("vlan_id", e.VlanID) + d.Set("vnfs", flattenExtnetVNFS(e.VNFS)) + return nil +} + +func flattenExtnetReservations(ers ExtnetReservations) []map[string]interface{} { + res := make([]map[string]interface{}, 0) + for _, er := range ers { + temp := map[string]interface{}{ + "client_type": er.ClientType, + "domainname": er.DomainName, + "hostname": er.HostName, + "desc": er.Desc, + "ip": er.IP, + "mac": er.MAC, + "type": er.Type, + "vm_id": er.VMID, + } + res = append(res, temp) + } + + return res +} + +func flattenExtnetDefaultQos(edqos ExtnetQos) []map[string]interface{} { + res := make([]map[string]interface{}, 0) + temp := map[string]interface{}{ + "e_rate": edqos.ERate, + "guid": edqos.GUID, + "in_burst": edqos.InBurst, + "in_rate": edqos.InRate, + } + res = append(res, temp) + return res +} + +func flattenExtnetVNFS(evnfs ExtnetVNFS) []map[string]interface{} { + res := make([]map[string]interface{}, 0) + temp := map[string]interface{}{ + "dhcp": evnfs.DHCP, + } + res = append(res, temp) + return res +} + +func dataSourceExtnetSchemaMake() map[string]*schema.Schema { + res := map[string]*schema.Schema{ + "net_id": { + Type: schema.TypeInt, + Required: true, + }, + "ckey": { + Type: schema.TypeString, + Computed: true, + }, + "meta": { + Type: schema.TypeList, + Computed: true, + Elem: &schema.Schema{ + Type: schema.TypeString, + }, + Description: "meta", + }, + "check__ips": { + Type: schema.TypeList, + Computed: true, + Elem: &schema.Schema{ + Type: schema.TypeString, + }, + }, + "check_ips": { + Type: schema.TypeList, + Computed: true, + Elem: &schema.Schema{ + Type: schema.TypeString, + }, + }, + "default": { + Type: schema.TypeBool, + Computed: true, + }, + "default_qos": { + Type: schema.TypeList, + MaxItems: 1, + Computed: true, + Elem: &schema.Resource{ + Schema: map[string]*schema.Schema{ + "e_rate": { + Type: schema.TypeInt, + Computed: true, + }, + "guid": { + Type: schema.TypeString, + Computed: true, + }, + "in_burst": { + Type: schema.TypeInt, + Computed: true, + }, + "in_rate": { + Type: schema.TypeInt, + Computed: true, + }, + }, + }, + }, + "desc": { + Type: schema.TypeString, + Computed: true, + }, + "dns": { + Type: schema.TypeList, + Computed: true, + Elem: &schema.Schema{ + Type: schema.TypeString, + }, + }, + "excluded": { + Type: schema.TypeList, + Computed: true, + Elem: &schema.Schema{ + Type: schema.TypeString, + }, + }, + "free_ips": { + Type: schema.TypeInt, + Computed: true, + }, + "gateway": { + Type: schema.TypeString, + Computed: true, + }, + "gid": { + Type: schema.TypeInt, + Computed: true, + }, + "guid": { + Type: schema.TypeInt, + Computed: true, + }, + "ipcidr": { + Type: schema.TypeString, + Computed: true, + }, + "milestones": { + Type: schema.TypeInt, + Computed: true, + }, + "net_name": { + Type: schema.TypeString, + Computed: true, + }, + "network": { + Type: schema.TypeString, + Computed: true, + }, + "network_id": { + Type: schema.TypeInt, + Computed: true, + }, + "pre_reservations_num": { + Type: schema.TypeInt, + Computed: true, + }, + "prefix": { + Type: schema.TypeInt, + Computed: true, + }, + "pri_vnf_dev_id": { + Type: schema.TypeInt, + Computed: true, + }, + "reservations": { + Type: schema.TypeList, + Computed: true, + Elem: &schema.Resource{ + Schema: map[string]*schema.Schema{ + "client_type": { + Type: schema.TypeString, + Computed: true, + }, + "domainname": { + Type: schema.TypeString, + Computed: true, + }, + "hostname": { + Type: schema.TypeString, + Computed: true, + }, + "desc": { + Type: schema.TypeString, + Computed: true, + }, + "ip": { + Type: schema.TypeString, + Computed: true, + }, + "mac": { + Type: schema.TypeString, + Computed: true, + }, + "type": { + Type: schema.TypeString, + Computed: true, + }, + "vm_id": { + Type: schema.TypeInt, + Computed: true, + }, + }, + }, + }, + "shared_with": { + Type: schema.TypeList, + Computed: true, + Elem: &schema.Schema{ + Type: schema.TypeInt, + }, + }, + "status": { + Type: schema.TypeString, + Computed: true, + }, + "vlan_id": { + Type: schema.TypeInt, + Computed: true, + }, + "vnfs": { + Type: schema.TypeList, + MaxItems: 1, + Computed: true, + Elem: &schema.Resource{ + Schema: map[string]*schema.Schema{ + "dhcp": { + Type: schema.TypeInt, + Computed: true, + }, + }, + }, + }, + } + return res +} + +func dataSourceExtnet() *schema.Resource { + return &schema.Resource{ + SchemaVersion: 1, + + Read: dataSourceExtnetRead, + + Timeouts: &schema.ResourceTimeout{ + Read: &Timeout30s, + Default: &Timeout60s, + }, + + Schema: dataSourceExtnetSchemaMake(), + } +} diff --git a/decort/data_source_extnet_computes_list.go b/decort/data_source_extnet_computes_list.go new file mode 100644 index 0000000..c963a61 --- /dev/null +++ b/decort/data_source_extnet_computes_list.go @@ -0,0 +1,156 @@ +/* +Copyright (c) 2019-2022 Digital Energy Cloud Solutions LLC. All Rights Reserved. +Author: Stanislav Solovev, + +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. +*/ + +/* +This file is part of Terraform (by Hashicorp) provider for Digital Energy Cloud Orchestration +Technology platfom. + +Visit https://github.com/rudecs/terraform-provider-decort for full source code package and updates. +*/ + +package decort + +import ( + "github.com/google/uuid" + "github.com/hashicorp/terraform-plugin-sdk/helper/schema" +) + +func flattenExtnetsComputes(ecs ExtnetExtendList) []map[string]interface{} { + res := make([]map[string]interface{}, 0) + for _, ec := range ecs { + temp := map[string]interface{}{ + "net_id": ec.ID, + "ipaddr": ec.IPAddr, + "ipcidr": ec.IPCidr, + "name": ec.Name, + } + res = append(res, temp) + } + return res +} + +func flattenExtnetComputesList(ecl ExtnetComputesList) []map[string]interface{} { + res := make([]map[string]interface{}, 0) + for _, ec := range ecl { + temp := map[string]interface{}{ + "account_id": ec.AccountId, + "account_name": ec.AccountName, + "extnets": flattenExtnetsComputes(ec.Extnets), + "id": ec.ID, + "name": ec.Name, + "rg_id": ec.RGID, + "rg_name": ec.RGName, + } + res = append(res, temp) + } + return res +} + +func dataSourceExtnetComputesListRead(d *schema.ResourceData, m interface{}) error { + extnetComputesList, err := utilityExtnetComputesListCheckPresence(d, m) + if err != nil { + return err + } + + id := uuid.New() + d.SetId(id.String()) + d.Set("items", flattenExtnetComputesList(extnetComputesList)) + + return nil +} + +func dataSourceExtnetComputesListSchemaMake() map[string]*schema.Schema { + res := map[string]*schema.Schema{ + "account_id": { + Type: schema.TypeInt, + Required: true, + Description: "filter by account ID", + }, + "items": { + Type: schema.TypeList, + Computed: true, + Elem: &schema.Resource{ + Schema: map[string]*schema.Schema{ + "account_id": { + Type: schema.TypeInt, + Computed: true, + }, + "account_name": { + Type: schema.TypeString, + Computed: true, + }, + "extnets": { + Type: schema.TypeList, + Computed: true, + Elem: &schema.Resource{ + Schema: map[string]*schema.Schema{ + "net_id": { + Type: schema.TypeInt, + Computed: true, + }, + "ipaddr": { + Type: schema.TypeString, + Computed: true, + }, + "ipcidr": { + Type: schema.TypeString, + Computed: true, + }, + "name": { + Type: schema.TypeString, + Computed: true, + }, + }, + }, + }, + "id": { + Type: schema.TypeInt, + Computed: true, + }, + "name": { + Type: schema.TypeString, + Computed: true, + }, + "rg_id": { + Type: schema.TypeInt, + Computed: true, + }, + "rg_name": { + Type: schema.TypeString, + Computed: true, + }, + }, + }, + }, + } + return res +} + +func dataSourceExtnetComputesList() *schema.Resource { + return &schema.Resource{ + SchemaVersion: 1, + + Read: dataSourceExtnetComputesListRead, + + Timeouts: &schema.ResourceTimeout{ + Read: &Timeout30s, + Default: &Timeout60s, + }, + + Schema: dataSourceExtnetComputesListSchemaMake(), + } +} diff --git a/decort/data_source_extnet_default.go b/decort/data_source_extnet_default.go new file mode 100644 index 0000000..de5585f --- /dev/null +++ b/decort/data_source_extnet_default.go @@ -0,0 +1,74 @@ +/* +Copyright (c) 2019-2022 Digital Energy Cloud Solutions LLC. All Rights Reserved. +Author: Stanislav Solovev, + +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. +*/ + +/* +This file is part of Terraform (by Hashicorp) provider for Digital Energy Cloud Orchestration +Technology platfom. + +Visit https://github.com/rudecs/terraform-provider-decort for full source code package and updates. +*/ + +package decort + +import ( + "strconv" + + "github.com/google/uuid" + "github.com/hashicorp/terraform-plugin-sdk/helper/schema" +) + +func dataSourceExtnetDefaultRead(d *schema.ResourceData, m interface{}) error { + extnetId, err := utilityExtnetDefaultCheckPresence(d, m) + if err != nil { + return err + } + + id := uuid.New() + d.SetId(id.String()) + extnetIdInt, err := strconv.ParseInt(extnetId, 10, 32) + if err != nil { + return err + } + d.Set("net_id", extnetIdInt) + + return nil +} + +func dataSourceExtnetDefaultSchemaMake() map[string]*schema.Schema { + res := map[string]*schema.Schema{ + "net_id": { + Type: schema.TypeInt, + Computed: true, + }, + } + return res +} + +func dataSourceExtnetDefault() *schema.Resource { + return &schema.Resource{ + SchemaVersion: 1, + + Read: dataSourceExtnetDefaultRead, + + Timeouts: &schema.ResourceTimeout{ + Read: &Timeout30s, + Default: &Timeout60s, + }, + + Schema: dataSourceExtnetDefaultSchemaMake(), + } +} diff --git a/decort/data_source_extnet_list.go b/decort/data_source_extnet_list.go new file mode 100644 index 0000000..4789f33 --- /dev/null +++ b/decort/data_source_extnet_list.go @@ -0,0 +1,112 @@ +/* +Copyright (c) 2019-2022 Digital Energy Cloud Solutions LLC. All Rights Reserved. +Author: Stanislav Solovev, + +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. +*/ + +/* +This file is part of Terraform (by Hashicorp) provider for Digital Energy Cloud Orchestration +Technology platfom. + +Visit https://github.com/rudecs/terraform-provider-decort for full source code package and updates. +*/ + +package decort + +import ( + "github.com/google/uuid" + "github.com/hashicorp/terraform-plugin-sdk/helper/schema" +) + +func flattenExtnetList(el ExtnetList) []map[string]interface{} { + res := make([]map[string]interface{}, 0) + for _, e := range el { + temp := map[string]interface{}{ + "net_id": e.ID, + "ipcidr": e.IPCidr, + "name": e.Name, + } + res = append(res, temp) + } + return res +} + +func dataSourceExtnetListRead(d *schema.ResourceData, m interface{}) error { + extnetList, err := utilityExtnetListCheckPresence(d, m) + if err != nil { + return err + } + + id := uuid.New() + d.SetId(id.String()) + d.Set("items", flattenExtnetList(extnetList)) + + return nil +} + +func dataSourceExtnetListSchemaMake() map[string]*schema.Schema { + res := map[string]*schema.Schema{ + "account_id": { + Type: schema.TypeInt, + Optional: true, + Description: "filter by account ID", + }, + "page": { + Type: schema.TypeInt, + Optional: true, + Description: "Page number", + }, + "size": { + Type: schema.TypeInt, + Optional: true, + Description: "Page size", + }, + "items": { + Type: schema.TypeList, + Computed: true, + Elem: &schema.Resource{ + Schema: map[string]*schema.Schema{ + "net_id": { + Type: schema.TypeInt, + Computed: true, + }, + "ipcidr": { + Type: schema.TypeString, + Computed: true, + }, + "name": { + Type: schema.TypeString, + Computed: true, + }, + }, + }, + }, + } + return res +} + +func dataSourceExtnetList() *schema.Resource { + return &schema.Resource{ + SchemaVersion: 1, + + Read: dataSourceExtnetListRead, + + Timeouts: &schema.ResourceTimeout{ + Read: &Timeout30s, + Default: &Timeout60s, + }, + + Schema: dataSourceExtnetListSchemaMake(), + } +} diff --git a/decort/data_source_vins_list.go b/decort/data_source_vins_list.go new file mode 100644 index 0000000..84a2c0b --- /dev/null +++ b/decort/data_source_vins_list.go @@ -0,0 +1,178 @@ +/* +Copyright (c) 2019-2022 Digital Energy Cloud Solutions LLC. All Rights Reserved. +Author: Stanislav Solovev, + +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. +*/ + +/* +This file is part of Terraform (by Hashicorp) provider for Digital Energy Cloud Orchestration +Technology platfom. + +Visit https://github.com/rudecs/terraform-provider-decort for full source code package and updates. +*/ + +package decort + +import ( + "github.com/google/uuid" + "github.com/hashicorp/terraform-plugin-sdk/helper/schema" +) + +func flattenVinsList(vl VinsList) []map[string]interface{} { + res := make([]map[string]interface{}, 0) + for _, v := range vl { + temp := map[string]interface{}{ + "account_id": v.AccountId, + "account_name": v.AccountName, + "created_by": v.CreatedBy, + "created_time": v.CreatedTime, + "deleted_by": v.DeletedBy, + "deleted_time": v.DeletedTime, + "external_ip": v.ExternalIP, + "vins_id": v.ID, + "vins_name": v.Name, + "network": v.Network, + "rg_id": v.RGID, + "rg_name": v.RGName, + "status": v.Status, + "updated_by": v.UpdatedBy, + "updated_time": v.UpdatedTime, + "vxlan_id": v.VXLanID, + } + res = append(res, temp) + } + return res +} + +func dataSourceVinsListRead(d *schema.ResourceData, m interface{}) error { + vinsList, err := utilityVinsListCheckPresence(d, m) + if err != nil { + return err + } + + id := uuid.New() + d.SetId(id.String()) + d.Set("items", flattenVinsList(vinsList)) + + return nil +} + +func dataSourceVinsListSchemaMake() map[string]*schema.Schema { + res := map[string]*schema.Schema{ + "include_deleted": { + Type: schema.TypeBool, + Optional: true, + Default: false, + Description: "include deleted computes", + }, + "page": { + Type: schema.TypeInt, + Optional: true, + Description: "Page number", + }, + "size": { + Type: schema.TypeInt, + Optional: true, + Description: "Page size", + }, + "items": { + Type: schema.TypeList, + Computed: true, + Elem: &schema.Resource{ + Schema: map[string]*schema.Schema{ + "account_id": { + Type: schema.TypeInt, + Computed: true, + }, + "account_name": { + Type: schema.TypeString, + Computed: true, + }, + "created_by": { + Type: schema.TypeString, + Computed: true, + }, + "created_time": { + Type: schema.TypeInt, + Computed: true, + }, + "deleted_by": { + Type: schema.TypeString, + Computed: true, + }, + "deleted_time": { + Type: schema.TypeInt, + Computed: true, + }, + "external_ip": { + Type: schema.TypeString, + Computed: true, + }, + "vins_id": { + Type: schema.TypeInt, + Computed: true, + }, + "vins_name": { + Type: schema.TypeString, + Computed: true, + }, + "network": { + Type: schema.TypeString, + Computed: true, + }, + "rg_id": { + Type: schema.TypeInt, + Computed: true, + }, + "rg_name": { + Type: schema.TypeString, + Computed: true, + }, + "status": { + Type: schema.TypeString, + Computed: true, + }, + "updated_by": { + Type: schema.TypeString, + Computed: true, + }, + "updated_time": { + Type: schema.TypeInt, + Computed: true, + }, + "vxlan_id": { + Type: schema.TypeInt, + Computed: true, + }, + }, + }, + }, + } + return res +} + +func dataSourceVinsList() *schema.Resource { + return &schema.Resource{ + SchemaVersion: 1, + + Read: dataSourceVinsListRead, + + Timeouts: &schema.ResourceTimeout{ + Read: &Timeout30s, + Default: &Timeout60s, + }, + + Schema: dataSourceVinsListSchemaMake(), + } +} diff --git a/decort/models_api.go b/decort/models_api.go index 119f11e..89e8676 100644 --- a/decort/models_api.go +++ b/decort/models_api.go @@ -1226,3 +1226,261 @@ type AccountFlipGroup struct { } type AccountFlipGroupsList []AccountFlipGroup + +//////////////////// +//// BSERVICE //// +//////////////////// + +const bserviceCreateAPI = "/restmachine/cloudapi/bservice/create" +const bserviceDeleteAPI = "/restmachine/cloudapi/bservice/delete" +const bserviceDisableAPI = "/restmachine/cloudapi/bservice/disable" +const bserviceEnableAPI = "/restmachine/cloudapi/bservice/enable" +const bserviceGetAPI = "/restmachine/cloudapi/bservice/get" +const bserviceGroupAddAPI = "/restmachine/cloudapi/bservice/groupAdd" +const bserviceGroupComputeRemoveAPI = "/restmachine/cloudapi/bservice/groupComputeRemove" +const bserviceGroupGetAPI = "/restmachine/cloudapi/bservice/groupGet" +const bserviceGroupParentAddAPI = "/restmachine/cloudapi/bservice/groupParentAdd" +const bserviceGroupParentRemoveAPI = "/restmachine/cloudapi/bservice/groupParentRemove" +const bserviceGroupRemoveAPI = "/restmachine/cloudapi/bservice/groupRemove" +const bserviceGroupResizeAPI = "/restmachine/cloudapi/bservice/groupResize" +const bserviceGroupStartAPI = "/restmachine/cloudapi/bservice/groupStart" +const bserviceGroupStopAPI = "/restmachine/cloudapi/bservice/groupStop" +const bserviceGroupUpdateAPI = "/restmachine/cloudapi/bservice/groupUpdate" +const bserviceGroupUpdateExtnetAPI = "/restmachine/cloudapi/bservice/groupUpdateExtnet" +const bserviceGroupUpdateVinsAPI = "/restmachine/cloudapi/bservice/groupUpdateVins" +const bserviceListAPI = "/restmachine/cloudapi/bservice/list" +const bserviceListDeletedAPI = "/restmachine/cloudapi/bservice/listDeleted" +const bserviceRestoreAPI = "/restmachine/cloudapi/bservice/restore" +const bserviceSnapshotCreateAPI = "/restmachine/cloudapi/bservice/snapshotCreate" +const bserviceSnapshotDeleteAPI = "/restmachine/cloudapi/bservice/snapshotDelete" +const bserviceSnapshotListAPI = "/restmachine/cloudapi/bservice/snapshotList" +const bserviceSnapshotRollbackAPI = "/restmachine/cloudapi/bservice/snapshotRollback" +const bserviceStartAPI = "/restmachine/cloudapi/bservice/start" +const bserviceStopAPI = "/restmachine/cloudapi/bservice/stop" + +///Structs + +type BasicServiceCompute struct { + CompGroupId int `json:"compgroupId"` + CompGroupName string `json:"compgroupName"` + CompGroupRole string `json:"compgroupRole"` + ID int `json:"id"` + Name string `json:"name"` +} + +type BasicServiceComputes []BasicServiceCompute + +type BasicServiceSnapshot struct { + GUID string `json:"guid"` + Label string `json:"label"` + Timestamp int `json:"timestamp"` + Valid bool `json:"valid"` +} + +type BasicServiceSnapshots []BasicServiceSnapshot + +type BasicService struct { + AccountId int `json:"accountId"` + AccountName string `json:"accountName"` + BaseDomain string `json:"baseDomain"` + + CreatedBy string `json:"createdBy"` + CreatedTime int `json:"createdTime"` + DeletedBy string `json:"deletedBy"` + DeletedTime int `json:"deletedTime"` + GID int `json:"gid"` + Groups []int `json:"groups"` + GUID int `json:"guid"` + ID int `json:"id"` + Name string `json:"name"` + ParentSrvId int `json:"parentSrvId"` + ParentSrvType string `json:"parentSrvType"` + RGID int `json:"rgId"` + RGName string `json:"rgName"` + SSHUser string `json:"sshUser"` + Status string `json:"status"` + TechStatus string `json:"techStatus"` + UpdatedBy string `json:"updatedBy"` + UpdatedTime int `json:"updatedTime"` + UserManaged bool `json:"userManaged"` +} + +type BasicServiceList []BasicService + +type BasicServiceExtend struct { + BasicService + Computes BasicServiceComputes `json:"computes"` + CPUTotal int `json:"cpuTotal"` + DiskTotal int `json:"diskTotal"` + GroupsName []string `json:"groupsName"` + Milestones int `json:"milestones"` + RamTotal int `json:"ramTotal"` + Snapshots BasicServiceSnapshots `json:"snapshots"` + SSHKey string `json:"sshKey"` +} + +type BasicServiceGroupOSUser struct { + Login string `json:"login"` + Password string `json:"password"` +} + +type BasicServiceGroupOSUsers []BasicServiceGroupOSUser + +type BasicServicceGroupCompute struct { + ID int `json:"id"` + IPAdresses []string `json:"ipAddresses"` + Name string `json:"name"` + OSUsers BasicServiceGroupOSUsers `json:"osUsers"` +} + +type BasicServiceGroupComputes []BasicServicceGroupCompute + +type BasicServiceGroup struct { + AccountId int `json:"accountId"` + AccountName string `json:"accountName"` + Computes BasicServiceGroupComputes `json:"computes"` + Consistency bool `json:"consistency"` + CPU int `json:"cpu"` + CreatedBy string `json:"createdBy"` + CreatedTime int `json:"createdTime"` + DeletedBy string `json:"deletedBy"` + DeletedTime int `json:"deletedTime"` + Disk int `json:"disk"` + Driver string `json:"driver"` + Extnets []int `json:"extnets"` + GID int `json:"gid"` + GUID int `json:"guid"` + ID int `json:"id"` + ImageId int `json:"imageId"` + Milestones int `json:"milestones"` + Name string `json:"name"` + Parents []int `json:"parents"` + RAM int `json:"ram"` + RGID int `json:"rgId"` + RGName string `json:"rgName"` + Role string `json:"role"` + SepId int `json:"sepId"` + SeqNo int `json:"seqNo"` + ServiceId int `json:"serviceId"` + Status string `json:"status"` + TechStatus string `json:"techStatus"` + TimeoutStart int `json:"timeoutStart"` + UpdatedBy string `json:"updatedBy"` + UpdatedTime int `json:"updatedTime"` + Vinses []int `json:"vinses"` +} + +/////////////////// +///// EXTNET ///// +/////////////////// + +const extnetListAPI = "/restmachine/cloudapi/extnet/list" +const extnetListComputesAPI = "/restmachine/cloudapi/extnet/listComputes" +const extnetGetDefaultAPI = "/restmachine/cloudapi/extnet/getDefault" +const extnetGetAPI = "/restmachine/cloudapi/extnet/get" + +type Extnet struct { + ID int `json:"id"` + IPCidr string `json:"ipcidr"` + Name string `json:"name"` +} +type ExtnetExtend struct { + Extnet + IPAddr string `json:"ipaddr"` +} + +type ExtnetList []Extnet +type ExtnetExtendList []ExtnetExtend + +type ExtnetComputes struct { + AccountId int `json:"accountId"` + AccountName string `json:"accountName"` + Extnets ExtnetExtendList `json:"extnets"` + ID int `json:"id"` + Name string `json:"name"` + RGID int `json:"rgId"` + RGName string `json:"rgName"` +} + +type ExtnetComputesList []ExtnetComputes + +type ExtnetQos struct { + ERate int `json:"eRate"` + GUID string `json:"guid"` + InBurst int `json:"inBurst"` + InRate int `json:"inRate"` +} + +type ExtnetReservation struct { + ClientType string `json:"clientType"` + Desc string `json:"desc"` + DomainName string `json:"domainname"` + HostName string `json:"hostname"` + IP string `json:"ip"` + MAC string `json:"mac"` + Type string `json:"type"` + VMID int `json:"vmId"` +} + +type ExtnetReservations []ExtnetReservation + +type ExtnetVNFS struct { + DHCP int `json:"dhcp"` +} + +type ExtnetDetailed struct { + CKey string `json:"_ckey"` + Meta []interface{} `json:"_meta"` + CheckIPs []string `json:"checkIPs"` + CheckIps []string `json:"checkIps"` + Default bool `json:"default"` + DefaultQos ExtnetQos `json:"defaultQos"` + Desc string `json:"desc"` + Dns []string `json:"dns"` + Excluded []string `json:"excluded"` + FreeIps int `json:"free_ips"` + Gateway string `json:"gateway"` + GID int `json:"gid"` + GUID int `json:"guid"` + ID int `json:"id"` + IPCidr string `json:"ipcidr"` + Milestones int `json:"milestones"` + Name string `json:"name"` + Network string `json:"network"` + NetworkId int `json:"networkId"` + PreReservationsNum int `json:"preReservationsNum"` + Prefix int `json:"prefix"` + PriVnfDevId int `json:"priVnfDevId"` + Reservations ExtnetReservations `json:"reservations"` + SharedWith []int `json:"sharedWith"` + Status string `json:"status"` + VlanID int `json:"vlanId"` + VNFS ExtnetVNFS `json:"vnfs"` +} + +////////////// +//// VINS //// +////////////// + +const vinsListAPI = "/restmachine/cloudapi/vins/list" + +type Vins struct { + AccountId int `json:"accountId"` + AccountName string `json:"accountName"` + CreatedBy string `json:"createdBy"` + CreatedTime int `json:"createdTime"` + DeletedBy string `json:"deletedBy"` + DeletedTime int `json:"deletedTime"` + ExternalIP string `json:"externalIP"` + ID int `json:"id"` + Name string `json:"name"` + Network string `json:"network"` + RGID int `json:"rgId"` + RGName string `json:"rgName"` + Status string `json:"status"` + UpdatedBy string `json:"updatedBy"` + UpdatedTime int `json:"updatedTime"` + VXLanID int `json:"vxlanId"` +} + +type VinsList []Vins diff --git a/decort/provider.go b/decort/provider.go index 030b263..eea3dda 100644 --- a/decort/provider.go +++ b/decort/provider.go @@ -99,22 +99,24 @@ func Provider() *schema.Provider { }, ResourcesMap: map[string]*schema.Resource{ - "decort_resgroup": resourceResgroup(), - "decort_kvmvm": resourceCompute(), - "decort_disk": resourceDisk(), - "decort_vins": resourceVins(), - "decort_pfw": resourcePfw(), - "decort_k8s": resourceK8s(), - "decort_k8s_wg": resourceK8sWg(), - "decort_image": resourceImage(), - "decort_virtual_image": resourceVirtualImage(), - "decort_cdrom_image": resourceCDROMImage(), - "decort_delete_images": resourceDeleteImages(), - "decort_snapshot": resourceSnapshot(), - "decort_pcidevice": resourcePcidevice(), - "decort_sep": resourceSep(), - "decort_sep_config": resourceSepConfig(), - "decort_account": resourceAccount(), + "decort_resgroup": resourceResgroup(), + "decort_kvmvm": resourceCompute(), + "decort_disk": resourceDisk(), + "decort_vins": resourceVins(), + "decort_pfw": resourcePfw(), + "decort_k8s": resourceK8s(), + "decort_k8s_wg": resourceK8sWg(), + "decort_image": resourceImage(), + "decort_virtual_image": resourceVirtualImage(), + "decort_cdrom_image": resourceCDROMImage(), + "decort_delete_images": resourceDeleteImages(), + "decort_snapshot": resourceSnapshot(), + "decort_pcidevice": resourcePcidevice(), + "decort_sep": resourceSep(), + "decort_sep_config": resourceSepConfig(), + "decort_account": resourceAccount(), + "decort_bservice": resourceBasicService(), + "decort_bservice_group": resourceBasicServiceGroup(), }, DataSourcesMap: map[string]*schema.Resource{ @@ -152,6 +154,16 @@ func Provider() *schema.Provider { "decort_account_templates_list": dataSourceAccountTemplatessList(), "decort_account_deleted_list": dataSourceAccountDeletedList(), "decort_account_flipgroups_list": dataSourceAccountFlipGroupsList(), + "decort_bservice_list": dataSourceBasicServiceList(), + "decort_bservice": dataSourceBasicService(), + "decort_bservice_snapshot_list": dataSourceBasicServiceSnapshotList(), + "decort_bservice_group": dataSourceBasicServiceGroup(), + "decort_bservice_deleted_list": dataSourceBasicServiceDeletedList(), + "decort_extnet_list": dataSourceExtnetList(), + "decort_extnet_computes_list": dataSourceExtnetComputesList(), + "decort_extnet": dataSourceExtnet(), + "decort_extnet_default": dataSourceExtnetDefault(), + "decort_vins_list": dataSourceVinsList(), // "decort_pfw": dataSourcePfw(), }, diff --git a/decort/resource_account.go b/decort/resource_account.go index a113092..e266560 100644 --- a/decort/resource_account.go +++ b/decort/resource_account.go @@ -51,7 +51,7 @@ func resourceAccountCreate(d *schema.ResourceData, m interface{}) error { return nil } - return errors.New("provided sep id does not exist") + return errors.New("provided account id does not exist") } controller := m.(*ControllerCfg) @@ -142,7 +142,7 @@ func resourceAccountCreate(d *schema.ResourceData, m interface{}) error { } func resourceAccountRead(d *schema.ResourceData, m interface{}) error { - log.Debugf("resourceSepRead") + log.Debugf("resourceAccountRead") acc, err := utilityAccountCheckPresence(d, m) if acc == nil { diff --git a/decort/resource_bservice.go b/decort/resource_bservice.go new file mode 100644 index 0000000..9f0df09 --- /dev/null +++ b/decort/resource_bservice.go @@ -0,0 +1,554 @@ +/* +Copyright (c) 2019-2022 Digital Energy Cloud Solutions LLC. All Rights Reserved. +Author: Stanislav Solovev, + +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. +*/ + +/* +This file is part of Terraform (by Hashicorp) provider for Digital Energy Cloud Orchestration +Technology platfom. + +Visit https://github.com/rudecs/terraform-provider-decort for full source code package and updates. +*/ + +package decort + +import ( + "errors" + "net/url" + "strconv" + + "github.com/google/uuid" + "github.com/hashicorp/terraform-plugin-sdk/helper/schema" + log "github.com/sirupsen/logrus" +) + +func resourceBasicServiceCreate(d *schema.ResourceData, m interface{}) error { + log.Debugf("resourceBasicServiceCreate") + + if serviceId, ok := d.GetOk("service_id"); ok { + if exists, err := resourceBasicServiceExists(d, m); exists { + if err != nil { + return err + } + id := uuid.New() + d.SetId(strconv.Itoa(serviceId.(int))) + d.Set("service_id", strconv.Itoa(serviceId.(int))) + err = resourceBasicServiceRead(d, m) + if err != nil { + return err + } + d.SetId(id.String()) + return nil + } + return errors.New("provided service id does not exist") + } + + controller := m.(*ControllerCfg) + urlValues := &url.Values{} + + urlValues.Add("name", d.Get("service_name").(string)) + urlValues.Add("rgId", strconv.Itoa(d.Get("rg_id").(int))) + + if sshKey, ok := d.GetOk("ssh_key"); ok { + urlValues.Add("sshKey", sshKey.(string)) + } + if sshUser, ok := d.GetOk("ssh_user"); ok { + urlValues.Add("sshUser", sshUser.(string)) + } + + serviceId, err := controller.decortAPICall("POST", bserviceCreateAPI, urlValues) + if err != nil { + return err + } + + id := uuid.New() + d.SetId(serviceId) + d.Set("service_id", serviceId) + + err = resourceBasicServiceRead(d, m) + if err != nil { + return err + } + + d.SetId(id.String()) + + return nil +} + +func resourceBasicServiceRead(d *schema.ResourceData, m interface{}) error { + log.Debugf("resourceBasicServiceRead") + + bs, err := utilityBasicServiceCheckPresence(d, m) + if bs == nil { + d.SetId("") + return err + } + + d.Set("account_id", bs.AccountId) + d.Set("account_name", bs.AccountName) + d.Set("base_domain", bs.BaseDomain) + d.Set("computes", flattenBasicServiceComputes(bs.Computes)) + d.Set("cpu_total", bs.CPUTotal) + d.Set("created_by", bs.CreatedBy) + d.Set("created_time", bs.CreatedTime) + d.Set("deleted_by", bs.DeletedBy) + d.Set("deleted_time", bs.DeletedTime) + d.Set("disk_total", bs.DiskTotal) + d.Set("gid", bs.GID) + d.Set("groups", bs.Groups) + d.Set("groups_name", bs.GroupsName) + d.Set("guid", bs.GUID) + d.Set("milestones", bs.Milestones) + d.Set("service_name", bs.Name) + d.Set("service_id", bs.ID) + d.Set("parent_srv_id", bs.ParentSrvId) + d.Set("parent_srv_type", bs.ParentSrvType) + d.Set("ram_total", bs.RamTotal) + d.Set("rg_id", bs.RGID) + d.Set("rg_name", bs.RGName) + d.Set("snapshots", flattenBasicServiceSnapshots(bs.Snapshots)) + d.Set("ssh_key", bs.SSHKey) + d.Set("ssh_user", bs.SSHUser) + d.Set("status", bs.Status) + d.Set("tech_status", bs.TechStatus) + d.Set("updated_by", bs.UpdatedBy) + d.Set("updated_time", bs.UpdatedTime) + d.Set("user_managed", bs.UserManaged) + + return nil +} + +func resourceBasicServiceDelete(d *schema.ResourceData, m interface{}) error { + log.Debugf("resourceBasicServiceDelete") + + bs, err := utilityBasicServiceCheckPresence(d, m) + if bs == nil { + if err != nil { + return err + } + return nil + } + + controller := m.(*ControllerCfg) + urlValues := &url.Values{} + urlValues.Add("serviceId", strconv.Itoa(d.Get("service_id").(int))) + urlValues.Add("permanently", strconv.FormatBool(d.Get("permanently").(bool))) + + _, err = controller.decortAPICall("POST", bserviceDeleteAPI, urlValues) + if err != nil { + return err + } + d.SetId("") + + return nil +} + +func resourceBasicServiceExists(d *schema.ResourceData, m interface{}) (bool, error) { + log.Debugf("resourceBasicServiceExists") + + bservice, err := utilityBasicServiceCheckPresence(d, m) + if bservice == nil { + if err != nil { + return false, err + } + return false, nil + } + + return true, nil +} + +func resourceBasicServiceEdit(d *schema.ResourceData, m interface{}) error { + log.Debugf("resourceBasicServiceEdit") + c := m.(*ControllerCfg) + + urlValues := &url.Values{} + if d.HasChange("enable") { + api := bserviceDisableAPI + enable := d.Get("enable").(bool) + if enable { + api = bserviceEnableAPI + } + urlValues.Add("serviceId", strconv.Itoa(d.Get("service_id").(int))) + + _, err := c.decortAPICall("POST", api, urlValues) + if err != nil { + return err + } + + urlValues = &url.Values{} + } + + if d.HasChange("restore") { + restore := d.Get("restore").(bool) + if restore { + urlValues.Add("serviceId", strconv.Itoa(d.Get("service_id").(int))) + _, err := c.decortAPICall("POST", bserviceRestoreAPI, urlValues) + if err != nil { + return err + } + + urlValues = &url.Values{} + } + } + + if d.HasChange("start") { + api := bserviceStopAPI + start := d.Get("start").(bool) + if start { + api = bserviceStartAPI + } + urlValues.Add("serviceId", strconv.Itoa(d.Get("service_id").(int))) + + _, err := c.decortAPICall("POST", api, urlValues) + if err != nil { + return err + } + + urlValues = &url.Values{} + } + + if d.HasChange("snapshots") { + deletedSnapshots := make([]interface{}, 0) + addedSnapshots := make([]interface{}, 0) + updatedSnapshots := make([]interface{}, 0) + + old, new := d.GetChange("snapshots") + oldConv := old.([]interface{}) + newConv := new.([]interface{}) + for _, el := range oldConv { + if !isContainsSnapshot(newConv, el) { + deletedSnapshots = append(deletedSnapshots, el) + } + } + for _, el := range newConv { + if !isContainsSnapshot(oldConv, el) { + addedSnapshots = append(addedSnapshots, el) + } else { + if isRollback(oldConv, el) { + updatedSnapshots = append(updatedSnapshots, el) + } + } + } + + if len(deletedSnapshots) > 0 { + for _, snapshot := range deletedSnapshots { + snapshotConv := snapshot.(map[string]interface{}) + urlValues.Add("serviceId", strconv.Itoa(d.Get("service_id").(int))) + urlValues.Add("label", snapshotConv["label"].(string)) + _, err := c.decortAPICall("POST", bserviceSnapshotDeleteAPI, urlValues) + if err != nil { + return err + } + + urlValues = &url.Values{} + } + } + + if len(addedSnapshots) > 0 { + for _, snapshot := range addedSnapshots { + snapshotConv := snapshot.(map[string]interface{}) + urlValues.Add("serviceId", strconv.Itoa(d.Get("service_id").(int))) + urlValues.Add("label", snapshotConv["label"].(string)) + _, err := c.decortAPICall("POST", bserviceSnapshotCreateAPI, urlValues) + if err != nil { + return err + } + + urlValues = &url.Values{} + } + } + + if len(updatedSnapshots) > 0 { + for _, snapshot := range updatedSnapshots { + snapshotConv := snapshot.(map[string]interface{}) + urlValues.Add("serviceId", strconv.Itoa(d.Get("service_id").(int))) + urlValues.Add("label", snapshotConv["label"].(string)) + _, err := c.decortAPICall("POST", bserviceSnapshotRollbackAPI, urlValues) + if err != nil { + return err + } + + urlValues = &url.Values{} + } + } + + } + + return nil +} + +func isContainsSnapshot(els []interface{}, el interface{}) bool { + for _, elOld := range els { + elOldConv := elOld.(map[string]interface{}) + elConv := el.(map[string]interface{}) + if elOldConv["guid"].(string) == elConv["guid"].(string) { + return true + } + } + return false +} + +func isRollback(els []interface{}, el interface{}) bool { + for _, elOld := range els { + elOldConv := elOld.(map[string]interface{}) + elConv := el.(map[string]interface{}) + if elOldConv["guid"].(string) == elConv["guid"].(string) && + elOldConv["rollback"].(bool) != elConv["rollback"].(bool) && + elConv["rollback"].(bool) { + return true + } + } + return false +} + +func resourceBasicServiceSchemaMake() map[string]*schema.Schema { + return map[string]*schema.Schema{ + "service_name": { + Type: schema.TypeString, + Required: true, + Description: "Name of the service", + }, + "rg_id": { + Type: schema.TypeInt, + Required: true, + Description: "ID of the Resource Group where this service will be placed", + }, + "ssh_key": { + Type: schema.TypeString, + Optional: true, + Computed: true, + Description: "SSH key to deploy for the specified user. Same key will be deployed to all computes of the service.", + }, + "ssh_user": { + Type: schema.TypeString, + Optional: true, + Computed: true, + Description: "name of the user to deploy SSH key for. Pass empty string if no SSH key deployment is required", + }, + "permanently": { + Type: schema.TypeBool, + Optional: true, + Default: false, + Description: "if set to False, Basic service will be deleted to recycle bin. Otherwise destroyed immediately", + }, + "enable": { + Type: schema.TypeBool, + Optional: true, + Default: false, + Description: "if set to False, Basic service will be deleted to recycle bin. Otherwise destroyed immediately", + }, + "restore": { + Type: schema.TypeBool, + Optional: true, + Default: false, + Description: "Restores BasicService instance", + }, + "start": { + Type: schema.TypeBool, + Optional: true, + Default: false, + Description: "Start service. Starting a service technically means starting computes from all service groups according to group relations", + }, + "service_id": { + Type: schema.TypeInt, + Optional: true, + Computed: true, + }, + "account_id": { + Type: schema.TypeInt, + Computed: true, + }, + "account_name": { + Type: schema.TypeString, + Computed: true, + }, + "base_domain": { + Type: schema.TypeString, + Computed: true, + }, + "computes": { + Type: schema.TypeList, + Computed: true, + Elem: &schema.Resource{ + Schema: map[string]*schema.Schema{ + "compgroup_id": { + Type: schema.TypeInt, + Computed: true, + }, + "compgroup_name": { + Type: schema.TypeString, + Computed: true, + }, + "compgroup_role": { + Type: schema.TypeString, + Computed: true, + }, + "id": { + Type: schema.TypeInt, + Computed: true, + }, + "name": { + Type: schema.TypeString, + Computed: true, + }, + }, + }, + }, + + "cpu_total": { + Type: schema.TypeInt, + Computed: true, + }, + "created_by": { + Type: schema.TypeString, + Computed: true, + }, + "created_time": { + Type: schema.TypeInt, + Computed: true, + }, + "deleted_by": { + Type: schema.TypeString, + Computed: true, + }, + "deleted_time": { + Type: schema.TypeInt, + Computed: true, + }, + "disk_total": { + Type: schema.TypeString, + Computed: true, + }, + "gid": { + Type: schema.TypeInt, + Computed: true, + }, + "groups": { + Type: schema.TypeList, + Computed: true, + Elem: &schema.Schema{ + Type: schema.TypeInt, + }, + }, + "groups_name": { + Type: schema.TypeList, + Computed: true, + Elem: &schema.Schema{ + Type: schema.TypeString, + }, + }, + "guid": { + Type: schema.TypeInt, + Computed: true, + }, + "milestones": { + Type: schema.TypeInt, + Computed: true, + }, + "parent_srv_id": { + Type: schema.TypeInt, + Computed: true, + }, + "parent_srv_type": { + Type: schema.TypeString, + Computed: true, + }, + "ram_total": { + Type: schema.TypeInt, + Computed: true, + }, + "rg_name": { + Type: schema.TypeString, + Computed: true, + }, + "snapshots": { + Type: schema.TypeList, + Computed: true, + Optional: true, + Elem: &schema.Resource{ + Schema: map[string]*schema.Schema{ + "guid": { + Type: schema.TypeString, + Computed: true, + }, + "label": { + Type: schema.TypeString, + Optional: true, + Computed: true, + }, + "rollback": { + Type: schema.TypeBool, + Optional: true, + Default: false, + }, + "timestamp": { + Type: schema.TypeInt, + Computed: true, + }, + "valid": { + Type: schema.TypeBool, + Computed: true, + }, + }, + }, + }, + "status": { + Type: schema.TypeString, + Computed: true, + }, + "tech_status": { + Type: schema.TypeString, + Computed: true, + }, + "updated_by": { + Type: schema.TypeString, + Computed: true, + }, + "updated_time": { + Type: schema.TypeInt, + Computed: true, + }, + "user_managed": { + Type: schema.TypeBool, + Computed: true, + }, + } +} + +func resourceBasicService() *schema.Resource { + return &schema.Resource{ + SchemaVersion: 1, + + Create: resourceBasicServiceCreate, + Read: resourceBasicServiceRead, + Update: resourceBasicServiceEdit, + Delete: resourceBasicServiceDelete, + Exists: resourceBasicServiceExists, + + Importer: &schema.ResourceImporter{ + State: schema.ImportStatePassthrough, + }, + + Timeouts: &schema.ResourceTimeout{ + Create: &Timeout60s, + Read: &Timeout30s, + Update: &Timeout60s, + Delete: &Timeout60s, + Default: &Timeout60s, + }, + + Schema: resourceBasicServiceSchemaMake(), + } +} diff --git a/decort/resource_bservice_group.go b/decort/resource_bservice_group.go new file mode 100644 index 0000000..7d14e16 --- /dev/null +++ b/decort/resource_bservice_group.go @@ -0,0 +1,660 @@ +/* +Copyright (c) 2019-2022 Digital Energy Cloud Solutions LLC. All Rights Reserved. +Author: Stanislav Solovev, + +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. +*/ + +/* +This file is part of Terraform (by Hashicorp) provider for Digital Energy Cloud Orchestration +Technology platfom. + +Visit https://github.com/rudecs/terraform-provider-decort for full source code package and updates. +*/ + +package decort + +import ( + "errors" + "net/url" + "strconv" + "strings" + + "github.com/google/uuid" + "github.com/hashicorp/terraform-plugin-sdk/helper/schema" + "github.com/hashicorp/terraform-plugin-sdk/helper/validation" + log "github.com/sirupsen/logrus" +) + +func resourceBasicServiceGroupCreate(d *schema.ResourceData, m interface{}) error { + log.Debugf("resourceBasicServiceGroupCreate") + + if compgroupId, ok := d.GetOk("compgroup_id"); ok { + if _, ok := d.GetOk("service_id"); ok { + if exists, err := resourceBasicServiceGroupExists(d, m); exists { + if err != nil { + return err + } + id := uuid.New() + d.SetId(strconv.Itoa(compgroupId.(int))) + d.Set("compgroup_id", strconv.Itoa(compgroupId.(int))) + err = resourceBasicServiceGroupRead(d, m) + if err != nil { + return err + } + d.SetId(id.String()) + return nil + } + return errors.New("provided compgroup id does not exist") + } + } + + controller := m.(*ControllerCfg) + urlValues := &url.Values{} + + urlValues.Add("serviceId", strconv.Itoa(d.Get("service_id").(int))) + urlValues.Add("name", d.Get("compgroup_name").(string)) + + urlValues.Add("count", strconv.Itoa(d.Get("comp_count").(int))) + urlValues.Add("cpu", strconv.Itoa(d.Get("cpu").(int))) + urlValues.Add("ram", strconv.Itoa(d.Get("ram").(int))) + urlValues.Add("disk", strconv.Itoa(d.Get("disk").(int))) + urlValues.Add("imageId", strconv.Itoa(d.Get("image_id").(int))) + urlValues.Add("driver", strings.ToUpper(d.Get("driver").(string))) + + if role, ok := d.GetOk("role"); ok { + urlValues.Add("role", role.(string)) + } + + if timeoutStart, ok := d.GetOk("timeout_start"); ok { + urlValues.Add("timeoutStart", strconv.Itoa(timeoutStart.(int))) + } + + if vinses, ok := d.GetOk("vinses"); ok { + vs := vinses.([]interface{}) + temp := "" + l := len(vs) + for i, v := range vs { + s := strconv.Itoa(v.(int)) + if i != (l - 1) { + s += "," + } + temp = temp + s + } + temp = "[" + temp + "]" + urlValues.Add("vinses", temp) + } + if extnets, ok := d.GetOk("extnets"); ok { + es := extnets.([]interface{}) + temp := "" + l := len(es) + for i, e := range es { + s := strconv.Itoa(e.(int)) + if i != (l - 1) { + s += "," + } + temp = temp + s + } + temp = "[" + temp + "]" + urlValues.Add("extnets", temp) + } + + compgroupId, err := controller.decortAPICall("POST", bserviceGroupAddAPI, urlValues) + if err != nil { + return err + } + + id := uuid.New() + d.SetId(compgroupId) + d.Set("compgroup_id", compgroupId) + + err = resourceBasicServiceGroupRead(d, m) + if err != nil { + return err + } + + d.SetId(id.String()) + + return nil +} + +func resourceBasicServiceGroupRead(d *schema.ResourceData, m interface{}) error { + log.Debugf("resourceBasicServiceGroupRead") + + bsg, err := utilityBasicServiceGroupCheckPresence(d, m) + if bsg == nil { + d.SetId("") + return err + } + + d.Set("account_id", bsg.AccountId) + d.Set("account_name", bsg.AccountName) + d.Set("computes", flattenBSGroupComputes(bsg.Computes)) + d.Set("consistency", bsg.Consistency) + d.Set("cpu", bsg.CPU) + d.Set("created_by", bsg.CreatedBy) + d.Set("created_time", bsg.CreatedTime) + d.Set("deleted_by", bsg.DeletedBy) + d.Set("deleted_time", bsg.DeletedTime) + d.Set("disk", bsg.Disk) + d.Set("driver", bsg.Driver) + d.Set("extnets", bsg.Extnets) + d.Set("gid", bsg.GID) + d.Set("guid", bsg.GUID) + d.Set("image_id", bsg.ImageId) + d.Set("milestones", bsg.Milestones) + d.Set("compgroup_name", bsg.Name) + d.Set("compgroup_id", bsg.ID) + d.Set("parents", bsg.Parents) + d.Set("ram", bsg.RAM) + d.Set("rg_id", bsg.RGID) + d.Set("rg_name", bsg.RGName) + d.Set("role", bsg.Role) + d.Set("sep_id", bsg.SepId) + d.Set("seq_no", bsg.SeqNo) + d.Set("status", bsg.Status) + d.Set("tech_status", bsg.TechStatus) + d.Set("timeout_start", bsg.TimeoutStart) + d.Set("updated_by", bsg.UpdatedBy) + d.Set("updated_time", bsg.UpdatedTime) + d.Set("vinses", bsg.Vinses) + + return nil +} + +func resourceBasicServiceGroupDelete(d *schema.ResourceData, m interface{}) error { + log.Debugf("resourceBasicServiceGroupDelete") + + bsg, err := utilityBasicServiceGroupCheckPresence(d, m) + if bsg == nil { + if err != nil { + return err + } + return nil + } + + controller := m.(*ControllerCfg) + urlValues := &url.Values{} + urlValues.Add("serviceId", strconv.Itoa(d.Get("service_id").(int))) + urlValues.Add("compgroupId", strconv.Itoa(d.Get("compgroup_id").(int))) + + _, err = controller.decortAPICall("POST", bserviceGroupRemoveAPI, urlValues) + if err != nil { + return err + } + d.SetId("") + + return nil +} + +func resourceBasicServiceGroupExists(d *schema.ResourceData, m interface{}) (bool, error) { + log.Debugf("resourceBasicServiceGroupExists") + + bserviceGroup, err := utilityBasicServiceGroupCheckPresence(d, m) + if bserviceGroup == nil { + if err != nil { + return false, err + } + return false, nil + } + + return true, nil +} + +func resourceBasicServiceGroupEdit(d *schema.ResourceData, m interface{}) error { + log.Debugf("resourceBasicServiceGroupEdit") + c := m.(*ControllerCfg) + + urlValues := &url.Values{} + + if d.HasChange("comp_count") { + urlValues.Add("serviceId", strconv.Itoa(d.Get("service_id").(int))) + urlValues.Add("compgroupId", strconv.Itoa(d.Get("compgroup_id").(int))) + urlValues.Add("count", strconv.Itoa(d.Get("comp_count").(int))) + urlValues.Add("mode", strings.ToUpper(d.Get("mode").(string))) + _, err := c.decortAPICall("POST", bserviceGroupResizeAPI, urlValues) + if err != nil { + return err + } + + urlValues = &url.Values{} + } + + if d.HasChange("start") { + api := bserviceGroupStopAPI + start := d.Get("start").(bool) + if start { + api = bserviceGroupStartAPI + } else { + urlValues.Add("force", strconv.FormatBool(d.Get("force_stop").(bool))) + } + urlValues.Add("serviceId", strconv.Itoa(d.Get("service_id").(int))) + urlValues.Add("compgroupId", strconv.Itoa(d.Get("compgroup_id").(int))) + + _, err := c.decortAPICall("POST", api, urlValues) + if err != nil { + return err + } + + urlValues = &url.Values{} + } + + if d.HasChanges("compgroup_name", "ram", "cpu", "disk", "role") { + urlValues.Add("name", d.Get("compgroup_name").(string)) + urlValues.Add("cpu", strconv.Itoa(d.Get("cpu").(int))) + urlValues.Add("ram", strconv.Itoa(d.Get("ram").(int))) + urlValues.Add("disk", strconv.Itoa(d.Get("disk").(int))) + urlValues.Add("role", d.Get("role").(string)) + urlValues.Add("force", strconv.FormatBool(d.Get("force_update").(bool))) + + urlValues.Add("serviceId", strconv.Itoa(d.Get("service_id").(int))) + urlValues.Add("compgroupId", strconv.Itoa(d.Get("compgroup_id").(int))) + + _, err := c.decortAPICall("POST", bserviceGroupUpdateAPI, urlValues) + if err != nil { + return err + } + + urlValues = &url.Values{} + } + + if d.HasChange("extnets") { + extnets := d.Get("extnets").([]interface{}) + temp := "" + l := len(extnets) + for i, e := range extnets { + s := strconv.Itoa(e.(int)) + if i != (l - 1) { + s += ",\n" + } else { + s += "\n" + } + temp = temp + s + } + temp = "[" + temp + "]" + + urlValues.Add("serviceId", strconv.Itoa(d.Get("service_id").(int))) + urlValues.Add("compgroupId", strconv.Itoa(d.Get("compgroup_id").(int))) + urlValues.Add("extnets", temp) + _, err := c.decortAPICall("POST", bserviceGroupUpdateExtnetAPI, urlValues) + if err != nil { + return err + } + + urlValues = &url.Values{} + } + + if d.HasChange("vinses") { + vinses := d.Get("vinses").([]interface{}) + temp := "" + l := len(vinses) + for i, v := range vinses { + s := strconv.Itoa(v.(int)) + if i != (l - 1) { + s += ",\n" + } else { + s += "\n" + } + temp = temp + s + } + temp = "[" + temp + "]" + + urlValues.Add("serviceId", strconv.Itoa(d.Get("service_id").(int))) + urlValues.Add("compgroupId", strconv.Itoa(d.Get("compgroup_id").(int))) + urlValues.Add("vinses", temp) + _, err := c.decortAPICall("POST", bserviceGroupUpdateVinsAPI, urlValues) + if err != nil { + return err + } + + urlValues = &url.Values{} + } + + if d.HasChange("parents") { + deletedParents := make([]interface{}, 0) + addedParents := make([]interface{}, 0) + + old, new := d.GetChange("parents") + oldConv := old.([]interface{}) + newConv := new.([]interface{}) + for _, el := range oldConv { + if !isContainsParent(newConv, el) { + deletedParents = append(deletedParents, el) + } + } + for _, el := range newConv { + if !isContainsParent(oldConv, el) { + addedParents = append(addedParents, el) + } + } + + if len(deletedParents) > 0 { + for _, parent := range deletedParents { + parentConv := parent.(int) + + urlValues.Add("serviceId", strconv.Itoa(d.Get("service_id").(int))) + urlValues.Add("compgroupId", strconv.Itoa(d.Get("compgroup_id").(int))) + urlValues.Add("parentId", strconv.Itoa(parentConv)) + + _, err := c.decortAPICall("POST", bserviceGroupParentRemoveAPI, urlValues) + if err != nil { + return err + } + + urlValues = &url.Values{} + } + } + + if len(addedParents) > 0 { + for _, parent := range addedParents { + parentConv := parent.(int) + urlValues.Add("serviceId", strconv.Itoa(d.Get("service_id").(int))) + urlValues.Add("compgroupId", strconv.Itoa(d.Get("compgroup_id").(int))) + urlValues.Add("parentId", strconv.Itoa(parentConv)) + _, err := c.decortAPICall("POST", bserviceGroupParentAddAPI, urlValues) + if err != nil { + return err + } + + urlValues = &url.Values{} + } + } + } + + if d.HasChange("remove_computes") { + rcs := d.Get("remove_computes").([]interface{}) + if len(rcs) > 0 { + for _, rc := range rcs { + urlValues.Add("serviceId", strconv.Itoa(d.Get("service_id").(int))) + urlValues.Add("compgroupId", strconv.Itoa(d.Get("compgroup_id").(int))) + urlValues.Add("computeId", strconv.Itoa(rc.(int))) + + _, err := c.decortAPICall("POST", bserviceGroupComputeRemoveAPI, urlValues) + if err != nil { + return err + } + + urlValues = &url.Values{} + } + } + } + + return nil +} + +func isContainsParent(els []interface{}, el interface{}) bool { + for _, elOld := range els { + elOldConv := elOld.(int) + elConv := el.(int) + if elOldConv == elConv { + return true + } + } + return false +} + +func resourceBasicServiceGroupSchemaMake() map[string]*schema.Schema { + return map[string]*schema.Schema{ + "service_id": { + Type: schema.TypeInt, + Required: true, + Description: "ID of the Basic Service to add a group to", + }, + "compgroup_name": { + Type: schema.TypeString, + Required: true, + Description: "name of the Compute Group to add", + }, + "comp_count": { + Type: schema.TypeInt, + Required: true, + Description: "computes number. Defines how many computes must be there in the group", + }, + "cpu": { + Type: schema.TypeInt, + Required: true, + Description: "compute CPU number. All computes in the group have the same CPU count", + }, + "ram": { + Type: schema.TypeInt, + Required: true, + Description: "compute RAM volume in MB. All computes in the group have the same RAM volume", + }, + "disk": { + Type: schema.TypeInt, + Required: true, + Description: "compute boot disk size in GB", + }, + "image_id": { + Type: schema.TypeInt, + Required: true, + Description: "OS image ID to create computes from", + }, + "driver": { + Type: schema.TypeString, + Required: true, + Description: "compute driver like a KVM_X86, KVM_PPC, etc.", + }, + "role": { + Type: schema.TypeString, + Optional: true, + Computed: true, + Description: "group role tag. Can be empty string, does not have to be unique", + }, + "timeout_start": { + Type: schema.TypeInt, + Optional: true, + Computed: true, + Description: "time of Compute Group readiness", + }, + "extnets": { + Type: schema.TypeList, + Optional: true, + Computed: true, + Elem: &schema.Schema{ + Type: schema.TypeInt, + }, + Description: "list of external networks to connect computes to", + }, + "vinses": { + Type: schema.TypeList, + Optional: true, + Computed: true, + Elem: &schema.Schema{ + Type: schema.TypeInt, + }, + Description: "list of ViNSes to connect computes to", + }, + "mode": { + Type: schema.TypeString, + Optional: true, + Default: "RELATIVE", + ValidateFunc: validation.StringInSlice([]string{"RELATIVE", "ABSOLUTE"}, false), + Description: "(RELATIVE;ABSOLUTE) either delta or absolute value of computes", + }, + "start": { + Type: schema.TypeBool, + Optional: true, + Default: false, + Description: "Start the specified Compute Group within BasicService", + }, + "force_stop": { + Type: schema.TypeBool, + Optional: true, + Default: false, + Description: "force stop Compute Group", + }, + "force_update": { + Type: schema.TypeBool, + Optional: true, + Default: false, + Description: "force resize Compute Group", + }, + "parents": { + Type: schema.TypeList, + Optional: true, + Computed: true, + Elem: &schema.Schema{ + Type: schema.TypeInt, + }, + }, + "remove_computes": { + Type: schema.TypeList, + Optional: true, + Elem: &schema.Schema{ + Type: schema.TypeInt, + }, + }, + "compgroup_id": { + Type: schema.TypeInt, + Optional: true, + }, + "account_id": { + Type: schema.TypeInt, + Computed: true, + }, + "account_name": { + Type: schema.TypeString, + Computed: true, + }, + "computes": { + Type: schema.TypeList, + Computed: true, + Elem: &schema.Resource{ + Schema: map[string]*schema.Schema{ + "id": { + Type: schema.TypeInt, + Computed: true, + }, + "ip_addresses": { + Type: schema.TypeList, + Computed: true, + Elem: &schema.Schema{ + Type: schema.TypeString, + }, + }, + "name": { + Type: schema.TypeString, + Computed: true, + }, + "os_users": { + Type: schema.TypeList, + Computed: true, + Elem: &schema.Resource{ + Schema: map[string]*schema.Schema{ + "login": { + Type: schema.TypeString, + Computed: true, + }, + "password": { + Type: schema.TypeString, + Computed: true, + }, + }, + }, + }, + }, + }, + }, + "consistency": { + Type: schema.TypeBool, + Computed: true, + }, + "created_by": { + Type: schema.TypeString, + Computed: true, + }, + "created_time": { + Type: schema.TypeInt, + Computed: true, + }, + "deleted_by": { + Type: schema.TypeString, + Computed: true, + }, + "deleted_time": { + Type: schema.TypeInt, + Computed: true, + }, + "gid": { + Type: schema.TypeInt, + Computed: true, + }, + "guid": { + Type: schema.TypeInt, + Computed: true, + }, + "milestones": { + Type: schema.TypeInt, + Computed: true, + }, + "rg_id": { + Type: schema.TypeInt, + Computed: true, + }, + "rg_name": { + Type: schema.TypeString, + Computed: true, + }, + "sep_id": { + Type: schema.TypeInt, + Computed: true, + }, + "seq_no": { + Type: schema.TypeInt, + Computed: true, + }, + "status": { + Type: schema.TypeString, + Computed: true, + }, + "tech_status": { + Type: schema.TypeString, + Computed: true, + }, + "updated_by": { + Type: schema.TypeString, + Computed: true, + }, + "updated_time": { + Type: schema.TypeInt, + Computed: true, + }, + } +} + +func resourceBasicServiceGroup() *schema.Resource { + return &schema.Resource{ + SchemaVersion: 1, + + Create: resourceBasicServiceGroupCreate, + Read: resourceBasicServiceGroupRead, + Update: resourceBasicServiceGroupEdit, + Delete: resourceBasicServiceGroupDelete, + Exists: resourceBasicServiceGroupExists, + + Importer: &schema.ResourceImporter{ + State: schema.ImportStatePassthrough, + }, + + Timeouts: &schema.ResourceTimeout{ + Create: &Timeout60s, + Read: &Timeout30s, + Update: &Timeout60s, + Delete: &Timeout60s, + Default: &Timeout60s, + }, + + Schema: resourceBasicServiceGroupSchemaMake(), + } +} diff --git a/decort/utility_bservicce_deleted_list.go b/decort/utility_bservicce_deleted_list.go new file mode 100644 index 0000000..d52ebee --- /dev/null +++ b/decort/utility_bservicce_deleted_list.go @@ -0,0 +1,67 @@ +/* +Copyright (c) 2019-2022 Digital Energy Cloud Solutions LLC. All Rights Reserved. +Author: Stanislav Solovev, , + +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. +*/ + +/* +This file is part of Terraform (by Hashicorp) provider for Digital Energy Cloud Orchestration +Technology platfom. + +Visit https://github.com/rudecs/terraform-provider-decort for full source code package and updates. +*/ + +package decort + +import ( + "encoding/json" + "net/url" + "strconv" + + log "github.com/sirupsen/logrus" + + "github.com/hashicorp/terraform-plugin-sdk/helper/schema" +) + +func utilityBasicServiceDeletedListCheckPresence(d *schema.ResourceData, m interface{}) (BasicServiceList, error) { + basicServiceDeletedList := BasicServiceList{} + controller := m.(*ControllerCfg) + urlValues := &url.Values{} + + if accountId, ok := d.GetOk("account_id"); ok { + urlValues.Add("accountId", strconv.Itoa(accountId.(int))) + } + if rgId, ok := d.GetOk("rg_id"); ok { + urlValues.Add("rgId", strconv.Itoa(rgId.(int))) + } + if page, ok := d.GetOk("page"); ok { + urlValues.Add("page", strconv.Itoa(page.(int))) + } + if size, ok := d.GetOk("size"); ok { + urlValues.Add("size", strconv.Itoa(size.(int))) + } + + log.Debugf("utilityBasicServiceDeletedListCheckPresence") + basicServiceDeletedListRaw, err := controller.decortAPICall("POST", bserviceListDeletedAPI, urlValues) + if err != nil { + return nil, err + } + + err = json.Unmarshal([]byte(basicServiceDeletedListRaw), &basicServiceDeletedList) + if err != nil { + return nil, err + } + + return basicServiceDeletedList, nil +} diff --git a/decort/utility_bservice.go b/decort/utility_bservice.go new file mode 100644 index 0000000..65c41d8 --- /dev/null +++ b/decort/utility_bservice.go @@ -0,0 +1,60 @@ +/* +Copyright (c) 2019-2022 Digital Energy Cloud Solutions LLC. All Rights Reserved. +Author: Stanislav Solovev, , + +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. +*/ + +/* +This file is part of Terraform (by Hashicorp) provider for Digital Energy Cloud Orchestration +Technology platfom. + +Visit https://github.com/rudecs/terraform-provider-decort for full source code package and updates. +*/ + +package decort + +import ( + "encoding/json" + "net/url" + "strconv" + + log "github.com/sirupsen/logrus" + + "github.com/hashicorp/terraform-plugin-sdk/helper/schema" +) + +func utilityBasicServiceCheckPresence(d *schema.ResourceData, m interface{}) (*BasicServiceExtend, error) { + bservice := &BasicServiceExtend{} + controller := m.(*ControllerCfg) + urlValues := &url.Values{} + + if (strconv.Itoa(d.Get("service_id").(int))) != "0" { + urlValues.Add("serviceId", strconv.Itoa(d.Get("service_id").(int))) + } else { + urlValues.Add("serviceId", d.Id()) + } + + log.Debugf("utilityBasicServiceCheckPresence") + bserviceRaw, err := controller.decortAPICall("POST", bserviceGetAPI, urlValues) + if err != nil { + return nil, err + } + + err = json.Unmarshal([]byte(bserviceRaw), &bservice) + if err != nil { + return nil, err + } + + return bservice, nil +} diff --git a/decort/utility_bservice_group.go b/decort/utility_bservice_group.go new file mode 100644 index 0000000..6f75dc0 --- /dev/null +++ b/decort/utility_bservice_group.go @@ -0,0 +1,61 @@ +/* +Copyright (c) 2019-2022 Digital Energy Cloud Solutions LLC. All Rights Reserved. +Author: Stanislav Solovev, , + +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. +*/ + +/* +This file is part of Terraform (by Hashicorp) provider for Digital Energy Cloud Orchestration +Technology platfom. + +Visit https://github.com/rudecs/terraform-provider-decort for full source code package and updates. +*/ + +package decort + +import ( + "encoding/json" + "net/url" + "strconv" + + log "github.com/sirupsen/logrus" + + "github.com/hashicorp/terraform-plugin-sdk/helper/schema" +) + +func utilityBasicServiceGroupCheckPresence(d *schema.ResourceData, m interface{}) (*BasicServiceGroup, error) { + bserviceGroup := &BasicServiceGroup{} + controller := m.(*ControllerCfg) + urlValues := &url.Values{} + + urlValues.Add("serviceId", strconv.Itoa(d.Get("service_id").(int))) + if (strconv.Itoa(d.Get("compgroup_id").(int))) != "0" { + urlValues.Add("compgroupId", strconv.Itoa(d.Get("compgroup_id").(int))) + } else { + urlValues.Add("compgroupId", d.Id()) + } + + log.Debugf("utilityBasicServiceGroupCheckPresence") + bserviceGroupRaw, err := controller.decortAPICall("POST", bserviceGroupGetAPI, urlValues) + if err != nil { + return nil, err + } + + err = json.Unmarshal([]byte(bserviceGroupRaw), &bserviceGroup) + if err != nil { + return nil, err + } + + return bserviceGroup, nil +} diff --git a/decort/utility_bservice_list.go b/decort/utility_bservice_list.go new file mode 100644 index 0000000..efbe623 --- /dev/null +++ b/decort/utility_bservice_list.go @@ -0,0 +1,67 @@ +/* +Copyright (c) 2019-2022 Digital Energy Cloud Solutions LLC. All Rights Reserved. +Author: Stanislav Solovev, , + +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. +*/ + +/* +This file is part of Terraform (by Hashicorp) provider for Digital Energy Cloud Orchestration +Technology platfom. + +Visit https://github.com/rudecs/terraform-provider-decort for full source code package and updates. +*/ + +package decort + +import ( + "encoding/json" + "net/url" + "strconv" + + log "github.com/sirupsen/logrus" + + "github.com/hashicorp/terraform-plugin-sdk/helper/schema" +) + +func utilityBasicServiceListCheckPresence(d *schema.ResourceData, m interface{}) (BasicServiceList, error) { + basicServiceList := BasicServiceList{} + controller := m.(*ControllerCfg) + urlValues := &url.Values{} + + if accountId, ok := d.GetOk("account_id"); ok { + urlValues.Add("accountId", strconv.Itoa(accountId.(int))) + } + if rgId, ok := d.GetOk("rg_id"); ok { + urlValues.Add("rgId", strconv.Itoa(rgId.(int))) + } + if page, ok := d.GetOk("page"); ok { + urlValues.Add("page", strconv.Itoa(page.(int))) + } + if size, ok := d.GetOk("size"); ok { + urlValues.Add("size", strconv.Itoa(size.(int))) + } + + log.Debugf("utilityBasicServiceListCheckPresence") + basicServiceListRaw, err := controller.decortAPICall("POST", bserviceListAPI, urlValues) + if err != nil { + return nil, err + } + + err = json.Unmarshal([]byte(basicServiceListRaw), &basicServiceList) + if err != nil { + return nil, err + } + + return basicServiceList, nil +} diff --git a/decort/utility_bservice_snapshot_list.go b/decort/utility_bservice_snapshot_list.go new file mode 100644 index 0000000..1f310f3 --- /dev/null +++ b/decort/utility_bservice_snapshot_list.go @@ -0,0 +1,58 @@ +/* +Copyright (c) 2019-2022 Digital Energy Cloud Solutions LLC. All Rights Reserved. +Author: Stanislav Solovev, , + +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. +*/ + +/* +This file is part of Terraform (by Hashicorp) provider for Digital Energy Cloud Orchestration +Technology platfom. + +Visit https://github.com/rudecs/terraform-provider-decort for full source code package and updates. +*/ + +package decort + +import ( + "encoding/json" + "net/url" + "strconv" + + log "github.com/sirupsen/logrus" + + "github.com/hashicorp/terraform-plugin-sdk/helper/schema" +) + +func utilityBasicServiceSnapshotListCheckPresence(d *schema.ResourceData, m interface{}) (BasicServiceSnapshots, error) { + basicServiceSnapshotList := BasicServiceSnapshots{} + controller := m.(*ControllerCfg) + urlValues := &url.Values{} + + if serviceId, ok := d.GetOk("service_id"); ok { + urlValues.Add("serviceId", strconv.Itoa(serviceId.(int))) + } + + log.Debugf("utilityBasicServiceSnapshotListCheckPresence") + basicServiceSnapshotListRaw, err := controller.decortAPICall("POST", bserviceSnapshotListAPI, urlValues) + if err != nil { + return nil, err + } + + err = json.Unmarshal([]byte(basicServiceSnapshotListRaw), &basicServiceSnapshotList) + if err != nil { + return nil, err + } + + return basicServiceSnapshotList, nil +} diff --git a/decort/utility_extnet.go b/decort/utility_extnet.go new file mode 100644 index 0000000..f7cb0b4 --- /dev/null +++ b/decort/utility_extnet.go @@ -0,0 +1,56 @@ +/* +Copyright (c) 2019-2022 Digital Energy Cloud Solutions LLC. All Rights Reserved. +Author: Stanislav Solovev, , + +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. +*/ + +/* +This file is part of Terraform (by Hashicorp) provider for Digital Energy Cloud Orchestration +Technology platfom. + +Visit https://github.com/rudecs/terraform-provider-decort for full source code package and updates. +*/ + +package decort + +import ( + "encoding/json" + "net/url" + "strconv" + + log "github.com/sirupsen/logrus" + + "github.com/hashicorp/terraform-plugin-sdk/helper/schema" +) + +func utilityExtnetCheckPresence(d *schema.ResourceData, m interface{}) (*ExtnetDetailed, error) { + extnet := &ExtnetDetailed{} + controller := m.(*ControllerCfg) + urlValues := &url.Values{} + + urlValues.Add("net_id", strconv.Itoa(d.Get("net_id").(int))) + + log.Debugf("utilityExtnetCheckPresence") + extnetRaw, err := controller.decortAPICall("POST", extnetGetAPI, urlValues) + if err != nil { + return nil, err + } + + err = json.Unmarshal([]byte(extnetRaw), &extnet) + if err != nil { + return nil, err + } + + return extnet, nil +} diff --git a/decort/utility_extnet_computes_list.go b/decort/utility_extnet_computes_list.go new file mode 100644 index 0000000..2f5c629 --- /dev/null +++ b/decort/utility_extnet_computes_list.go @@ -0,0 +1,56 @@ +/* +Copyright (c) 2019-2022 Digital Energy Cloud Solutions LLC. All Rights Reserved. +Author: Stanislav Solovev, , + +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. +*/ + +/* +This file is part of Terraform (by Hashicorp) provider for Digital Energy Cloud Orchestration +Technology platfom. + +Visit https://github.com/rudecs/terraform-provider-decort for full source code package and updates. +*/ + +package decort + +import ( + "encoding/json" + "net/url" + "strconv" + + log "github.com/sirupsen/logrus" + + "github.com/hashicorp/terraform-plugin-sdk/helper/schema" +) + +func utilityExtnetComputesListCheckPresence(d *schema.ResourceData, m interface{}) (ExtnetComputesList, error) { + extnetComputesList := ExtnetComputesList{} + controller := m.(*ControllerCfg) + urlValues := &url.Values{} + + urlValues.Add("accountId", strconv.Itoa(d.Get("account_id").(int))) + + log.Debugf("utilityExtnetComputesListCheckPresence") + extnetComputesListRaw, err := controller.decortAPICall("POST", extnetListComputesAPI, urlValues) + if err != nil { + return nil, err + } + + err = json.Unmarshal([]byte(extnetComputesListRaw), &extnetComputesList) + if err != nil { + return nil, err + } + + return extnetComputesList, nil +} diff --git a/decort/utility_extnet_default.go b/decort/utility_extnet_default.go new file mode 100644 index 0000000..d07f306 --- /dev/null +++ b/decort/utility_extnet_default.go @@ -0,0 +1,46 @@ +/* +Copyright (c) 2019-2022 Digital Energy Cloud Solutions LLC. All Rights Reserved. +Author: Stanislav Solovev, , + +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. +*/ + +/* +This file is part of Terraform (by Hashicorp) provider for Digital Energy Cloud Orchestration +Technology platfom. + +Visit https://github.com/rudecs/terraform-provider-decort for full source code package and updates. +*/ + +package decort + +import ( + "net/url" + + log "github.com/sirupsen/logrus" + + "github.com/hashicorp/terraform-plugin-sdk/helper/schema" +) + +func utilityExtnetDefaultCheckPresence(d *schema.ResourceData, m interface{}) (string, error) { + controller := m.(*ControllerCfg) + urlValues := &url.Values{} + + log.Debugf("utilityExtnetDefaultCheckPresence") + res, err := controller.decortAPICall("POST", extnetGetDefaultAPI, urlValues) + if err != nil { + return "", err + } + + return res, nil +} diff --git a/decort/utility_extnet_list.go b/decort/utility_extnet_list.go new file mode 100644 index 0000000..a0abe60 --- /dev/null +++ b/decort/utility_extnet_list.go @@ -0,0 +1,64 @@ +/* +Copyright (c) 2019-2022 Digital Energy Cloud Solutions LLC. All Rights Reserved. +Author: Stanislav Solovev, , + +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. +*/ + +/* +This file is part of Terraform (by Hashicorp) provider for Digital Energy Cloud Orchestration +Technology platfom. + +Visit https://github.com/rudecs/terraform-provider-decort for full source code package and updates. +*/ + +package decort + +import ( + "encoding/json" + "net/url" + "strconv" + + log "github.com/sirupsen/logrus" + + "github.com/hashicorp/terraform-plugin-sdk/helper/schema" +) + +func utilityExtnetListCheckPresence(d *schema.ResourceData, m interface{}) (ExtnetList, error) { + extnetList := ExtnetList{} + controller := m.(*ControllerCfg) + urlValues := &url.Values{} + + if accountId, ok := d.GetOk("account_id"); ok { + urlValues.Add("accountId", strconv.Itoa(accountId.(int))) + } + if page, ok := d.GetOk("page"); ok { + urlValues.Add("page", strconv.Itoa(page.(int))) + } + if size, ok := d.GetOk("size"); ok { + urlValues.Add("size", strconv.Itoa(size.(int))) + } + + log.Debugf("utilityExtnetListCheckPresence") + extnetListRaw, err := controller.decortAPICall("POST", extnetListAPI, urlValues) + if err != nil { + return nil, err + } + + err = json.Unmarshal([]byte(extnetListRaw), &extnetList) + if err != nil { + return nil, err + } + + return extnetList, nil +} diff --git a/decort/utility_vins_list.go b/decort/utility_vins_list.go new file mode 100644 index 0000000..7bdf083 --- /dev/null +++ b/decort/utility_vins_list.go @@ -0,0 +1,64 @@ +/* +Copyright (c) 2019-2022 Digital Energy Cloud Solutions LLC. All Rights Reserved. +Author: Stanislav Solovev, , + +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. +*/ + +/* +This file is part of Terraform (by Hashicorp) provider for Digital Energy Cloud Orchestration +Technology platfom. + +Visit https://github.com/rudecs/terraform-provider-decort for full source code package and updates. +*/ + +package decort + +import ( + "encoding/json" + "net/url" + "strconv" + + log "github.com/sirupsen/logrus" + + "github.com/hashicorp/terraform-plugin-sdk/helper/schema" +) + +func utilityVinsListCheckPresence(d *schema.ResourceData, m interface{}) (VinsList, error) { + vinsList := VinsList{} + controller := m.(*ControllerCfg) + urlValues := &url.Values{} + + if includeDeleted, ok := d.GetOk("include_deleted"); ok { + urlValues.Add("includeDeleted", strconv.FormatBool(includeDeleted.(bool))) + } + if page, ok := d.GetOk("page"); ok { + urlValues.Add("page", strconv.Itoa(page.(int))) + } + if size, ok := d.GetOk("size"); ok { + urlValues.Add("size", strconv.Itoa(size.(int))) + } + + log.Debugf("utilityVinsListCheckPresence") + vinsListRaw, err := controller.decortAPICall("POST", vinsListAPI, urlValues) + if err != nil { + return nil, err + } + + err = json.Unmarshal([]byte(vinsListRaw), &vinsList) + if err != nil { + return nil, err + } + + return vinsList, nil +} diff --git a/samples/README.md b/samples/README.md index db5b79e..1e8d2a4 100644 --- a/samples/README.md +++ b/samples/README.md @@ -32,6 +32,14 @@ - account_reserved_units - account_templates_list - account_deleted_list + - bservice_list + - bservice + - bservice_group + - extnet_default + - extnet_list + - extnet + - extnet_computes_list + - vins_list - resources: - image - virtual_image @@ -44,6 +52,8 @@ - sep - sep_config - account + - bservice + - bservice_group ## Как пользоваться примерами 1. Установить terraform diff --git a/samples/data_bservice/main.tf b/samples/data_bservice/main.tf new file mode 100644 index 0000000..1b82faf --- /dev/null +++ b/samples/data_bservice/main.tf @@ -0,0 +1,39 @@ +/* +Пример использования +Получение информации о basic service + +*/ +#Расскомментируйте этот код, +#и внесите необходимые правки в версию и путь, +#чтобы работать с установленным вручную (не через hashicorp provider registry) провайдером +/* +terraform { + required_providers { + decort = { + version = "1.1" + source = "digitalenergy.online/decort/decort" + } + } +} +*/ + +provider "decort" { + authenticator = "oauth2" + #controller_url = + controller_url = "https://ds1.digitalenergy.online" + #oauth2_url = + oauth2_url = "https://sso.digitalenergy.online" + allow_unverified_ssl = true +} + +data "decort_bservice" "b" { + #id сервиса + #обязательный параметр + #тип - число + service_id = 11111 + +} + +output "test" { + value = data.decort_bservice.b +} diff --git a/samples/data_bservice_deleted_list/main.tf b/samples/data_bservice_deleted_list/main.tf new file mode 100644 index 0000000..6a0a7d6 --- /dev/null +++ b/samples/data_bservice_deleted_list/main.tf @@ -0,0 +1,57 @@ +/* +Пример использования +Получение списка удаленных basic service +*/ +#Расскомментируйте этот код, +#и внесите необходимые правки в версию и путь, +#чтобы работать с установленным вручную (не через hashicorp provider registry) провайдером +/* +terraform { + required_providers { + decort = { + version = "1.1" + source = "digitalenergy.online/decort/decort" + } + } +} +*/ + +provider "decort" { + authenticator = "oauth2" + #controller_url = + controller_url = "https://ds1.digitalenergy.online" + #oauth2_url = + oauth2_url = "https://sso.digitalenergy.online" + allow_unverified_ssl = true +} + +data "decort_bservice_deleted_list" "bsdl" { + #id аккаунта для фильтрации данных + #опциональный параметр + #тип - число + #если не задан - выводятся все доступные данные + #account_id = 11111 + + #id ресурсной группы, используется для фильтрации + #опциональный параметр + #тип - число + #если не задан - выводятся все доступные данные + #rg_id = 11111 + + #номер страницы для отображения + #опциональный параметр + #тип - число + #если не задан - выводятся все доступные данные + #page = 2 + + #размер страницы + #опциональный параметр + #тип - число + #если не задан - выводятся все доступные данные + #size = 3 + +} + +output "test" { + value = data.decort_bservice_deleted_list.bsdl +} diff --git a/samples/data_bservice_group/main.tf b/samples/data_bservice_group/main.tf new file mode 100644 index 0000000..d859c3e --- /dev/null +++ b/samples/data_bservice_group/main.tf @@ -0,0 +1,44 @@ +/* +Пример использования +Получение информации о вычислительной группе, принадлежащей basic service + +*/ +#Расскомментируйте этот код, +#и внесите необходимые правки в версию и путь, +#чтобы работать с установленным вручную (не через hashicorp provider registry) провайдером +/* +terraform { + required_providers { + decort = { + version = "1.1" + source = "digitalenergy.online/decort/decort" + } + } +} +*/ + +provider "decort" { + authenticator = "oauth2" + #controller_url = + controller_url = "https://ds1.digitalenergy.online" + #oauth2_url = + oauth2_url = "https://sso.digitalenergy.online" + allow_unverified_ssl = true +} + +data "decort_bservice_group" "bsg" { + #id сервиса + #обязательный параметр + #тип - число + service_id = 11111 + + #id вычислительной группы + #обязательный параметр + #тип - число + compgroup_id = 12121 + +} + +output "test" { + value = data.decort_bservice_group.bsg +} diff --git a/samples/data_bservice_list/main.tf b/samples/data_bservice_list/main.tf new file mode 100644 index 0000000..c87579c --- /dev/null +++ b/samples/data_bservice_list/main.tf @@ -0,0 +1,58 @@ +/* +Пример использования +Получение списка доступных базовых сервисов + +*/ +#Расскомментируйте этот код, +#и внесите необходимые правки в версию и путь, +#чтобы работать с установленным вручную (не через hashicorp provider registry) провайдером +/* +terraform { + required_providers { + decort = { + version = "1.1" + source = "digitalenergy.online/decort/decort" + } + } +} +*/ + +provider "decort" { + authenticator = "oauth2" + #controller_url = + controller_url = "https://ds1.digitalenergy.online" + #oauth2_url = + oauth2_url = "https://sso.digitalenergy.online" + allow_unverified_ssl = true +} + +data "decort_bservice_list" "bsl" { + #id аккаунта для фильтрации данных + #опциональный параметр + #тип - число + #если не задан - выводятся все доступные данные + #account_id = 11111 + + #id ресурсной группы, используется для фильтрации + #опциональный параметр + #тип - число + #если не задан - выводятся все доступные данные + #rg_id = 11111 + + #номер страницы для отображения + #опциональный параметр + #тип - число + #если не задан - выводятся все доступные данные + #page = 2 + + #размер страницы + #опциональный параметр + #тип - число + #если не задан - выводятся все доступные данные + #size = 3 + +} + +output "test" { + value = data.decort_bservice_list.bsl +} diff --git a/samples/data_bservice_snapshot_list/main.tf b/samples/data_bservice_snapshot_list/main.tf new file mode 100644 index 0000000..96cb9c5 --- /dev/null +++ b/samples/data_bservice_snapshot_list/main.tf @@ -0,0 +1,39 @@ +/* +Пример использования +Получение списка снимков состояний basic service + +*/ +#Расскомментируйте этот код, +#и внесите необходимые правки в версию и путь, +#чтобы работать с установленным вручную (не через hashicorp provider registry) провайдером +/* +terraform { + required_providers { + decort = { + version = "1.1" + source = "digitalenergy.online/decort/decort" + } + } +} +*/ + + +provider "decort" { + authenticator = "oauth2" + #controller_url = + controller_url = "https://ds1.digitalenergy.online" + #oauth2_url = + oauth2_url = "https://sso.digitalenergy.online" + allow_unverified_ssl = true +} + +data "decort_bservice_snapshot_list" "bsl" { + #id back service + #обязательный параметр + #тип - число + service_id = 11111 +} + +output "test" { + value = data.decort_bservice_snapshot_list.bsl +} diff --git a/samples/data_extnet/main.tf b/samples/data_extnet/main.tf new file mode 100644 index 0000000..2694c76 --- /dev/null +++ b/samples/data_extnet/main.tf @@ -0,0 +1,38 @@ +/* +Пример использования +Получение информации о сети +*/ +#Расскомментируйте этот код, +#и внесите необходимые правки в версию и путь, +#чтобы работать с установленным вручную (не через hashicorp provider registry) провайдером +/* +terraform { + required_providers { + decort = { + version = "1.1" + source = "digitalenergy.online/decort/decort" + } + } +} +*/ + + +provider "decort" { + authenticator = "oauth2" + #controller_url = + controller_url = "https://ds1.digitalenergy.online" + #oauth2_url = + oauth2_url = "https://sso.digitalenergy.online" + allow_unverified_ssl = true +} + +data "decort_extnet" "e" { + #идентификатор сети + #обязательный параметр + #тип - число + net_id = 1111 +} + +output "test" { + value = data.decort_extnet.e +} diff --git a/samples/data_extnet_computes_list/main.tf b/samples/data_extnet_computes_list/main.tf new file mode 100644 index 0000000..1879d37 --- /dev/null +++ b/samples/data_extnet_computes_list/main.tf @@ -0,0 +1,37 @@ +/* +Пример использования +Получение информации о вычислительных ресурсах, использующих сеть аккаунта +*/ +#Расскомментируйте этот код, +#и внесите необходимые правки в версию и путь, +#чтобы работать с установленным вручную (не через hashicorp provider registry) провайдером +/* +terraform { + required_providers { + decort = { + version = "1.1" + source = "digitalenergy.online/decort/decort" + } + } +} +*/ + +provider "decort" { + authenticator = "oauth2" + #controller_url = + controller_url = "https://ds1.digitalenergy.online" + #oauth2_url = + oauth2_url = "https://sso.digitalenergy.online" + allow_unverified_ssl = true +} + +data "decort_extnet_computes_list" "ecl" { + #идентификатор аккаунта + #обязательный параметр + #тип - число + account_id = 1111 +} + +output "test" { + value = data.decort_extnet_computes_list.ecl +} diff --git a/samples/data_extnet_default/main.tf b/samples/data_extnet_default/main.tf new file mode 100644 index 0000000..cf91c79 --- /dev/null +++ b/samples/data_extnet_default/main.tf @@ -0,0 +1,36 @@ +/* +Пример использования +Получение информации о сети по-умолчанию + +*/ +#Расскомментируйте этот код, +#и внесите необходимые правки в версию и путь, +#чтобы работать с установленным вручную (не через hashicorp provider registry) провайдером +/* +terraform { + required_providers { + decort = { + version = "1.1" + source = "digitalenergy.online/decort/decort" + } + } +} +*/ + + +provider "decort" { + authenticator = "oauth2" + #controller_url = + controller_url = "https://ds1.digitalenergy.online" + #oauth2_url = + oauth2_url = "https://sso.digitalenergy.online" + allow_unverified_ssl = true +} + +data "decort_extnet_default" "ed" { + +} + +output "test" { + value = data.decort_extnet_default.ed +} diff --git a/samples/data_extnet_list/main.tf b/samples/data_extnet_list/main.tf new file mode 100644 index 0000000..355a699 --- /dev/null +++ b/samples/data_extnet_list/main.tf @@ -0,0 +1,48 @@ +/* +Пример использования +Получение списка сетей + +*/ +#Расскомментируйте этот код, +#и внесите необходимые правки в версию и путь, +#чтобы работать с установленным вручную (не через hashicorp provider registry) провайдером +/* +terraform { + required_providers { + decort = { + version = "1.1" + source = "digitalenergy.online/decort/decort" + } + } +} +*/ + +provider "decort" { + authenticator = "oauth2" + #controller_url = + controller_url = "https://ds1.digitalenergy.online" + #oauth2_url = + oauth2_url = "https://sso.digitalenergy.online" + allow_unverified_ssl = true +} + +data "decort_extnet_list" "el" { + #id аккаунта для фильтрации результата + #необязательный параметр + #тип - число + #account_id = 1111111 + + #кол-во страниц для вывода + #опицональный параметр + #тип - число + #page = 1 + + #размер страницы + #опицональный параметр + #тип - число + #size = 1 +} + +output "test" { + value = data.decort_extnet_list.el +} diff --git a/samples/data_vins_list/main.tf b/samples/data_vins_list/main.tf new file mode 100644 index 0000000..0f44b92 --- /dev/null +++ b/samples/data_vins_list/main.tf @@ -0,0 +1,51 @@ +/* +Пример использования +Получение списка vins +*/ +#Расскомментируйте этот код, +#и внесите необходимые правки в версию и путь, +#чтобы работать с установленным вручную (не через hashicorp provider registry) провайдером +/* +terraform { + required_providers { + decort = { + version = "1.1" + source = "digitalenergy.online/decort/decort" + } + } +} +*/ + +provider "decort" { + authenticator = "oauth2" + #controller_url = + controller_url = "https://ds1.digitalenergy.online" + #oauth2_url = + oauth2_url = "https://sso.digitalenergy.online" + allow_unverified_ssl = true +} + +data "decort_vins_list" "vl" { + #включение удаленных vins в результат + #опциональный параметр + #тип - будев тип + #если не задан - выводятся все неудаленные данные + #include_deleted = true + + #номер страницы для отображения + #опциональный параметр + #тип - число + #если не задан - выводятся все доступные данные + #page = 1 + + #размер страницы + #опциональный параметр + #тип - число + #если не задан - выводятся все доступные данные + #size = 1 + +} + +output "test" { + value = data.decort_vins_list.vl +} diff --git a/samples/resource_bservice/main.tf b/samples/resource_bservice/main.tf new file mode 100644 index 0000000..b2b592a --- /dev/null +++ b/samples/resource_bservice/main.tf @@ -0,0 +1,110 @@ +/* +Пример использования +Ресурса cdrom image +Ресурс позволяет: +1. Создавать basic service +2. Редактировать basic service +3. Удалять basic service +4. Создавать снимки состояний basic service +5. Совершать восстановление по снимкам состояний +6. Удалять снимки состояний + +*/ +#Расскомментируйте этот код, +#и внесите необходимые правки в версию и путь, +#чтобы работать с установленным вручную (не через hashicorp provider registry) провайдером +/* +terraform { + required_providers { + decort = { + version = "1.1" + source = "digitalenergy.online/decort/decort" + } + } +} +*/ + +provider "decort" { + authenticator = "oauth2" + #controller_url = + controller_url = "https://ds1.digitalenergy.online" + #oauth2_url = + oauth2_url = "https://sso.digitalenergy.online" + allow_unverified_ssl = true +} + +resource "decort_bservice" "b" { + #имя сервиса + #обязательный параметр + #тип - строка + service_name = "my_test_bservice_sn" + + #id ресурсной группы + #обязательный параметр + #тип - число + rg_id = 11111 + + #доступность сервиса + #необязательный параметр + #тип - булев тип + #используется при редактировании ресурса + #по-умолачанию - false + #enable = true + + #снимок состояния + #необязательный параметр + #тип - объект + #используется при редактировании ресурса + #может быть несколько в ресурсе + /* + snapshots { + #имя снимка состояния + #обязательный параметр + #тип - строка + label = "test_snapshot" + + #восстановление сервиса из снимка состояния + #необязательный параметр + #тип - булев тип + #по-умолчанию - false + #восстановление происходит только при переключении с false на true + rollback = false + } + snapshots { + label = "test_snapshot_1" + } + */ + + #старт сервиса + #необязательный параметр + #тип - булев тип + #используется при редактировании ресурса + #по-умолачанию - false + #start = false + + #восстановление сервиса после удаления + #необязательный параметр + #тип - булев тип + #используется при редактировании ресурса + #по-умолачанию - false + #restore = true + + #мгновенное удаление сервиса без права восстановления + #необязательный параметр + #тип - булев тип + #используется при удалении ресурса + #по-умолачанию - false + #permanently = true + + #id сервиса, позволяет сформировать .tfstate, если сервис есть в платформе + #необязательный параметр + #тип - булев тип + #используется при создании ресурса + #service_id = 11111 + + +} + +output "test" { + value = decort_bservice.b +} diff --git a/samples/resource_bservice_group/main.tf b/samples/resource_bservice_group/main.tf new file mode 100644 index 0000000..70cb5ad --- /dev/null +++ b/samples/resource_bservice_group/main.tf @@ -0,0 +1,150 @@ +/* +Пример использования +Работы с ресурсом basic service group +Ресурс позволяет: +1. Создавать группы +2. Редактировать группы +3. Удалять группы +*/ +#Расскомментируйте этот код, +#и внесите необходимые правки в версию и путь, +#чтобы работать с установленным вручную (не через hashicorp provider registry) провайдером +/* +terraform { + required_providers { + decort = { + version = "1.1" + source = "digitalenergy.online/decort/decort" + } + } +} +*/ + +provider "decort" { + authenticator = "oauth2" + #controller_url = + controller_url = "https://ds1.digitalenergy.online" + #oauth2_url = + oauth2_url = "https://sso.digitalenergy.online" + allow_unverified_ssl = true +} + +resource "decort_bservice_group" "bsg" { + #id back service + #обязательный параметр + #тип - число + service_id = 444444 + + #название группы + #обязательный параметр + #тип - строка + compgroup_name = "tf_group_rename" + + #id группы + #необязательный параметр + #тип - число + #применяется при редактировании группы, либо при создании .tfstate - файла, если группа имеется в плафторме + compgroup_id = 33333 + + #кол-во вычислительных ресурсов + #обязательный параметр + #тип - число + #используется так же для редактирования группы + comp_count = 1 + + #кол-во ядер на выч. ресурс + #обязательный параметр + #тип - число + #используется так же для редактирования группы + cpu = 2 + + #кол-во оперативной памяти на выч. ресурс, в МБ + #обязательный параметр + #тип - число + #используется так же для редактирования группы + ram = 256 + + #размер диска для выч. ресурса, в ГБ + #обязательный параметр + #тип - число + #используется так же для редактирования группы + disk = 11 + + #id образа диска + #обязательный параметр + #тип - число + image_id = 2222 + + #драйвер + #обязательный параметр + #тип - число + driver = "kvm_x86" + + #id сетей extnet + #обязательный параметр + #тип - массив чисел + #должен быть использован vins или extnets + extnets = [1111] + + #id сетей vinses + #обязательный параметр + #тип - массив чисел + #должен быть использован vins или extnets + #vinses = [1111, 2222] + + #время таймуата перед стартом + #необязательный параметр + #тип - число + #используется при создании ресурса + #timeout_start = 0 + + #тег группы + #необязательный параметр + #тип - строка + #используется при создании и редактировании ресурса + # role = "tf_test_changed" + + #id групп родителей + #необязательный параметр + #тип - массив чисел + #используется при редактировании ресурса + #parents = [] + + #принудительное обновление параметров выч. мощностей (ram,disk,cpu) и имени группы + #необязательный параметр + #тип - булев тип + #используется при редактировании + #force_update = true + + #старт/стоп вычислительных мощностей + #необязательный параметр + #тип - булев тип + #используется при редактировании + #по-умолчанию - false + #start = false + + #принудительная остановка вычислительных мощностей + #необязательный параметр + #тип - булев тип + #используется при редактировании и остановке группы + #по-умолчанию - false + #force_stop = false + + #удаление вычислительных мощностей + #необязательный параметр + #тип - массив чисел + #используется при редактировании + #remove_computes = [32287] + + #режим увеличения числа выч. мощностей + #необязательный параметр + #тип - число + #используется в связке с comp_count при редактировании группы + #возможные варианты - RELATIVE и ABSOLUTE + #mode = "RELATIVE" + +} + +output "test" { + value = decort_bservice_group.bsg +} From c7b54717a153dc2ad18c70e0df53b28a2f82a0d8 Mon Sep 17 00:00:00 2001 From: stSolo Date: Tue, 7 Jun 2022 18:59:19 +0300 Subject: [PATCH 27/51] Fix erratas --- README.md | 3 +- README_EN.md | 3 +- decort/resource_bservice_group.go | 1 + samples/data_account/main.tf | 2 +- samples/data_account_audits_list/main.tf | 2 +- samples/data_account_consumed_units/main.tf | 2 +- .../main.tf | 6 ++-- samples/data_account_disks_list/main.tf | 2 +- samples/data_account_reserved_units/main.tf | 2 +- samples/data_account_rg_list/main.tf | 2 +- samples/data_account_vins_list/main.tf | 2 +- samples/data_bservice_snapshot_list/main.tf | 2 +- samples/resource_account/main.tf | 28 +++++++++---------- samples/resource_bservice_group/main.tf | 4 +-- 14 files changed, 31 insertions(+), 30 deletions(-) diff --git a/README.md b/README.md index 3981b12..36687f1 100644 --- a/README.md +++ b/README.md @@ -19,7 +19,8 @@ Terraform provider для платформы Digital Energy Cloud Orchestration - Работа с pcidevice, - Работа с sep, - Работа с vgpu, -- Работа с bservice. +- Работа с bservice, +- Работа с extnets. Вики проекта: https://github.com/rudecs/terraform-provider-decort/wiki diff --git a/README_EN.md b/README_EN.md index 87bcea6..396d151 100644 --- a/README_EN.md +++ b/README_EN.md @@ -18,7 +18,8 @@ NOTE: provider rc-1.25 is designed for DECORT API 3.7.x. For older API versions - Work with pcidevice. - Work with sep, - Work with vgpu, -- Work with bservice. +- Work with bservice, +- Work with extnets. This provider supports Import operations on pre-existing resources. diff --git a/decort/resource_bservice_group.go b/decort/resource_bservice_group.go index 7d14e16..6bbff5a 100644 --- a/decort/resource_bservice_group.go +++ b/decort/resource_bservice_group.go @@ -518,6 +518,7 @@ func resourceBasicServiceGroupSchemaMake() map[string]*schema.Schema { "compgroup_id": { Type: schema.TypeInt, Optional: true, + Computed: true, }, "account_id": { Type: schema.TypeInt, diff --git a/samples/data_account/main.tf b/samples/data_account/main.tf index 1cc63dc..af70baa 100644 --- a/samples/data_account/main.tf +++ b/samples/data_account/main.tf @@ -30,7 +30,7 @@ data "decort_account" "a" { #id аккаунта #обязательный параметр #тип - число - account_id = 28096 + account_id = 11111 } diff --git a/samples/data_account_audits_list/main.tf b/samples/data_account_audits_list/main.tf index a30b152..1cd48f5 100644 --- a/samples/data_account_audits_list/main.tf +++ b/samples/data_account_audits_list/main.tf @@ -31,7 +31,7 @@ data "decort_account_audits_list" "aal" { #id аккаунта #обязательный параметр #тип - число - account_id = 28096 + account_id = 11111 } diff --git a/samples/data_account_consumed_units/main.tf b/samples/data_account_consumed_units/main.tf index b12b1df..bfe2c2b 100644 --- a/samples/data_account_consumed_units/main.tf +++ b/samples/data_account_consumed_units/main.tf @@ -29,7 +29,7 @@ data "decort_account_consumed_units" "acu" { #id аккаунта #обязательный параметр #тип - число - account_id = 88366 + account_id = 22222 } output "test" { diff --git a/samples/data_account_consumed_units_by_type/main.tf b/samples/data_account_consumed_units_by_type/main.tf index 67d3043..35ed80b 100644 --- a/samples/data_account_consumed_units_by_type/main.tf +++ b/samples/data_account_consumed_units_by_type/main.tf @@ -34,9 +34,9 @@ data "decort_account_consumed_units_by_type" "acubt" { #id аккаунта #обязательный параметр #тип - число - account_id = 88366 + account_id = 33333 - #тип вычислительной еденицы + #тип вычислительной единицы #обязательный параметр #тип - строка #значения: @@ -46,7 +46,7 @@ data "decort_account_consumed_units_by_type" "acubt" { #cu_i - кол-во публичных ip адресов #cu_np - кол-во полученного/отданного трафика, в ГБ #gpu_units - кол-во gpu ядер - cu_type = "cu_a" + cu_type = "cu_с" } output "test" { diff --git a/samples/data_account_disks_list/main.tf b/samples/data_account_disks_list/main.tf index ff6b4fa..c0ac605 100644 --- a/samples/data_account_disks_list/main.tf +++ b/samples/data_account_disks_list/main.tf @@ -30,7 +30,7 @@ data "decort_account_disks_list" "adl" { #id аккаунта #обязательный параметр #тип - число - account_id = 28096 + account_id = 11111 } diff --git a/samples/data_account_reserved_units/main.tf b/samples/data_account_reserved_units/main.tf index f86a3dc..5421b3a 100644 --- a/samples/data_account_reserved_units/main.tf +++ b/samples/data_account_reserved_units/main.tf @@ -30,7 +30,7 @@ data "decort_account_reserved_units" "aru" { #id аккаунта #обязательный параметр #тип - число - account_id = 88366 + account_id = 11111 } output "test" { diff --git a/samples/data_account_rg_list/main.tf b/samples/data_account_rg_list/main.tf index 48d5418..13fbb6d 100644 --- a/samples/data_account_rg_list/main.tf +++ b/samples/data_account_rg_list/main.tf @@ -29,7 +29,7 @@ data "decort_account_rg_list" "argl" { #id аккаунта #обязательный параметр #тип - число - account_id = 88366 + account_id = 66666 } output "test" { diff --git a/samples/data_account_vins_list/main.tf b/samples/data_account_vins_list/main.tf index da28996..e0e8eda 100644 --- a/samples/data_account_vins_list/main.tf +++ b/samples/data_account_vins_list/main.tf @@ -30,7 +30,7 @@ data "decort_account_vins_list" "avl" { #id аккаунта #обязательный параметр #тип - число - account_id = 28096 + account_id = 22222 } diff --git a/samples/data_bservice_snapshot_list/main.tf b/samples/data_bservice_snapshot_list/main.tf index 96cb9c5..a24097c 100644 --- a/samples/data_bservice_snapshot_list/main.tf +++ b/samples/data_bservice_snapshot_list/main.tf @@ -28,7 +28,7 @@ provider "decort" { } data "decort_bservice_snapshot_list" "bsl" { - #id back service + #id basic service #обязательный параметр #тип - число service_id = 11111 diff --git a/samples/resource_account/main.tf b/samples/resource_account/main.tf index f8bcf72..86bd361 100644 --- a/samples/resource_account/main.tf +++ b/samples/resource_account/main.tf @@ -44,7 +44,7 @@ resource "decort_account" "a" { #доступность аккаунта #необязательный параметр - #тип - будев тип + #тип - булев тип #может применяться при редактировании аккаунта enable = true @@ -102,38 +102,38 @@ resource "decort_account" "a" { resource_limits { #кол-во используемых ядер cpu #необязательный параметр - #тип - ичсло - #если установлена -1 - кол-во неограичено + #тип - число + #если установлена -1 - кол-во неограиченно cu_c = 2 #кол-во используемой RAM в МБ #необязательный параметр - #тип - ичсло - #если установлена -1 - кол-во неограичено + #тип - число + #если установлена -1 - кол-во неограиченно cu_m = 1024 #размер дисков, в ГБ #необязательный параметр - #тип - ичсло + #тип - число #если установлена -1 - размер неограичен cu_d = 23 #кол-во используемых публичных IP #необязательный параметр - #тип - ичсло - #если установлена -1 - кол-во неограичено + #тип - число + #если установлена -1 - кол-во неограиченно cu_i = 2 #ограничения на кол-во передачи данных, в ГБ #необязательный параметр - #тип - ичсло - #если установлена -1 - кол-во неограичено + #тип - число + #если установлена -1 - кол-во неограиченно cu_np = 2 #кол-во графических процессоров #необязательный параметр - #тип - ичсло - #если установлена -1 - кол-во неограичено + #тип - число + #если установлена -1 - кол-во неограиченно gpu_units = 2 } @@ -142,7 +142,7 @@ resource "decort_account" "a" { #тип - булев тип #применяется к удаленным аккаунтам #по-умолчанию - false - #retore = false + #restore = false #мгновеное удаление аккаунта, если да - то аккаунт невозможно будет восстановить #необязательный параметр @@ -150,8 +150,6 @@ resource "decort_account" "a" { #используется при удалении аккаунта #по-умолчанию - false #permanently = true - - } output "test" { diff --git a/samples/resource_bservice_group/main.tf b/samples/resource_bservice_group/main.tf index 70cb5ad..4b9b5f1 100644 --- a/samples/resource_bservice_group/main.tf +++ b/samples/resource_bservice_group/main.tf @@ -30,7 +30,7 @@ provider "decort" { } resource "decort_bservice_group" "bsg" { - #id back service + #id basic service #обязательный параметр #тип - число service_id = 444444 @@ -138,7 +138,7 @@ resource "decort_bservice_group" "bsg" { #режим увеличения числа выч. мощностей #необязательный параметр - #тип - число + #тип - строка #используется в связке с comp_count при редактировании группы #возможные варианты - RELATIVE и ABSOLUTE #mode = "RELATIVE" From 5aa436cfb86036a25a2cf3f60f6ce54e8cfa5588 Mon Sep 17 00:00:00 2001 From: kjubybot Date: Thu, 19 May 2022 19:05:38 +0300 Subject: [PATCH 28/51] refactored overcomplicated code; deleted some unused functions; added golangci-lint config --- .golangci.yml | 33 +++ decort/controller.go | 7 +- decort/data_source_compute.go | 150 ----------- decort/data_source_grid.go | 1 - decort/data_source_image.go | 1 - decort/data_source_image_list_stacks.go | 2 +- decort/data_source_vins.go | 14 +- decort/disk_subresource.go | 86 ------ decort/interface_subresource.go | 331 ------------------------ decort/network_subresource.go | 31 +-- decort/provider.go | 2 - decort/quota_subresource.go | 4 +- decort/resource_cdrom_image.go | 25 +- decort/resource_compute.go | 43 +-- decort/resource_disk.go | 81 +++--- decort/resource_image.go | 28 +- decort/resource_k8s.go | 6 +- decort/resource_k8s_wg.go | 6 +- decort/resource_rg.go | 13 +- decort/resource_sep.go | 22 +- decort/resource_sep_config.go | 4 +- decort/resource_snapshot.go | 2 +- decort/resource_vins.go | 71 ++--- decort/resource_virtual_image.go | 30 +-- decort/utility_compute.go | 48 ++-- decort/utility_general.go | 48 ---- decort/utility_grid.go | 3 +- decort/utility_pcidevice.go | 13 +- decort/utility_pcidevice_list.go | 2 +- decort/utility_rg.go | 42 +-- decort/utility_vins.go | 40 +-- 31 files changed, 221 insertions(+), 968 deletions(-) create mode 100644 .golangci.yml delete mode 100644 decort/disk_subresource.go delete mode 100644 decort/interface_subresource.go delete mode 100644 decort/utility_general.go diff --git a/.golangci.yml b/.golangci.yml new file mode 100644 index 0000000..49ad9be --- /dev/null +++ b/.golangci.yml @@ -0,0 +1,33 @@ +linters: + enable: + - bodyclose + - decorder + - dogsled + - errorlint + - exportloopref + - gocognit + - goconst + - gocyclo + - gosec + - ifshort + - makezero + - nestif + - nilerr + - prealloc + - unconvert + - unparam + +linters-settings: + errcheck: + exclude-functions: + - (*github.com/hashicorp/terraform-plugin-sdk/helper/schema.ResourceData).Set + staticcheck: + go: "1.18" + checks: + - all + - -SA1019 + nestif: + min-complexity: 7 + +issues: + max-same-issues: 0 diff --git a/decort/controller.go b/decort/controller.go index addc6e3..25e27ea 100644 --- a/decort/controller.go +++ b/decort/controller.go @@ -94,8 +94,7 @@ func ControllerConfigure(d *schema.ResourceData) (*ControllerCfg, error) { decort_username: "", } - var allow_unverified_ssl bool - allow_unverified_ssl = d.Get("allow_unverified_ssl").(bool) + allow_unverified_ssl := d.Get("allow_unverified_ssl").(bool) if ret_config.controller_url == "" { return nil, fmt.Errorf("Empty DECORT cloud controller URL provided.") @@ -138,7 +137,7 @@ func ControllerConfigure(d *schema.ResourceData) (*ControllerCfg, error) { if allow_unverified_ssl { log.Warn("ControllerConfigure: allow_unverified_ssl is set - will not check certificates!") - transCfg := &http.Transport{TLSClientConfig: &tls.Config{InsecureSkipVerify: true}} + transCfg := &http.Transport{TLSClientConfig: &tls.Config{InsecureSkipVerify: true}} //nolint:gosec ret_config.cc_client = &http.Client{ Transport: transCfg, Timeout: Timeout180s, @@ -336,7 +335,7 @@ func (config *ControllerCfg) validateLegacyUser() (bool, error) { return true, nil } -func (config *ControllerCfg) decortAPICall(method string, api_name string, url_values *url.Values) (json_resp string, err error) { +func (config *ControllerCfg) decortAPICall(method string, api_name string, url_values *url.Values) (json_resp string, err error) { //nolint:unparam // This is a convenience wrapper around standard HTTP request methods that is aware of the // authorization mode for which the provider was initialized and compiles request accordingly. diff --git a/decort/data_source_compute.go b/decort/data_source_compute.go index 8800308..e1b4169 100644 --- a/decort/data_source_compute.go +++ b/decort/data_source_compute.go @@ -66,60 +66,6 @@ func parseComputeDisksToExtraDisks(disks []DiskRecord) []interface{} { return result } -// NOTE: this is a legacy function, which is not used as of rc-1.10 -// Use "parseComputeDisksToExtraDisks" instead -func parseComputeDisks(disks []DiskRecord) []interface{} { - // Return value was designed to d.Set("disks",) item of dataSourceCompute schema - // However, this item was excluded from the schema as it is not directly - // managed through Terraform - length := len(disks) - log.Debugf("parseComputeDisks: called for %d disks", length) - - /* - if length == 1 && disks[0].Type == "B" { - // there is only one disk in the list and it is a boot disk - // as we skip boot disks, the result will be of 0 lenght - length = 0 - } - */ - - result := []interface{}{} - - if length == 0 { - return result - } - - for _, value := range disks { - /* - if value.Type == "B" { - // skip boot disk when parsing the list of disks - continue - } - */ - elem := make(map[string]interface{}) - // keys in this map should correspond to the Schema definition - // as returned by dataSourceDiskSchemaMake() - elem["name"] = value.Name - elem["disk_id"] = value.ID - elem["account_id"] = value.AccountID - elem["account_name"] = value.AccountName - elem["description"] = value.Desc - elem["image_id"] = value.ImageID - elem["size"] = value.SizeMax - elem["type"] = value.Type - elem["sep_id"] = value.SepID - elem["sep_type"] = value.SepType - elem["pool"] = value.Pool - // elem["status"] = value.Status - // elem["tech_status"] = value.TechStatus - elem["compute_id"] = value.ComputeID - - result = append(result, elem) - } - - return result -} - func parseBootDiskSize(disks []DiskRecord) int { // this return value will be used to d.Set("boot_disk_size",) item of dataSourceCompute schema if len(disks) == 0 { @@ -176,71 +122,6 @@ func parseComputeInterfacesToNetworks(ifaces []InterfaceRecord) []interface{} { return result } -/* -func parseComputeInterfacesToNetworks(ifaces []InterfaceRecord) []map[string]interface{} { - // return value will be used to d.Set("network") item of dataSourceCompute schema - length := len(ifaces) - log.Debugf("parseComputeInterfacesToNetworks: called for %d ifaces", length) - - result := make([]map[string]interface{}, length, length) - - for i, value := range ifaces { - elem := make(map[string]interface{}) - // Keys in this map should correspond to the Schema definition - // as returned by networkSubresourceSchemaMake() - elem["net_id"] = value.NetID - elem["net_type"] = value.NetType - elem["ip_address"] = value.IPAddress - elem["mac"] = value.MAC - - // log.Debugf(" element %d: net_id=%d, net_type=%s", i, value.NetID, value.NetType) - - result[i] = elem - } - - return result -} -*/ - -// NOTE: this function is retained for historical purposes and actually not used as of rc-1.10 -func parseComputeInterfaces(ifaces []InterfaceRecord) []map[string]interface{} { - // return value was designed to d.Set("interfaces",) item of dataSourceCompute schema - // However, this item was excluded from the schema as it is not directly - // managed through Terraform - length := len(ifaces) - log.Debugf("parseComputeInterfaces: called for %d ifaces", length) - - result := make([]map[string]interface{}, length, length) - - for i, value := range ifaces { - // Keys in this map should correspond to the Schema definition - // as returned by dataSourceInterfaceSchemaMake() - elem := make(map[string]interface{}) - - elem["net_id"] = value.NetID - elem["net_type"] = value.NetType - elem["ip_address"] = value.IPAddress - elem["netmask"] = value.NetMask - elem["mac"] = value.MAC - elem["default_gw"] = value.DefaultGW - elem["name"] = value.Name - elem["connection_id"] = value.ConnID - elem["connection_type"] = value.ConnType - - /* TODO: add code to parse QoS - qos_schema := interfaceQosSubresourceSchemaMake() - qos_schema.Set("egress_rate", value.QOS.ERate) - qos_schema.Set("ingress_rate", value.QOS.InRate) - qos_schema.Set("ingress_burst", value.QOS.InBurst) - elem["qos"] = qos_schema - */ - - result[i] = elem - } - - return result -} - func flattenCompute(d *schema.ResourceData, compFacts string) error { // This function expects that compFacts string contains response from API compute/get, // i.e. detailed information about compute instance. @@ -440,17 +321,6 @@ func dataSourceCompute() *schema.Resource { Description: "Network connection(s) for this compute.", }, - /* - "interfaces": { - Type: schema.TypeList, - Computed: true, - Elem: &schema.Resource{ - Schema: interfaceSubresourceSchemaMake(), - }, - Description: "Specification for the virtual NICs configured on this compute instance.", - }, - */ - "os_users": { Type: schema.TypeList, Computed: true, @@ -478,26 +348,6 @@ func dataSourceCompute() *schema.Resource { Default: true, Description: "Is compute started.", }, - - /* - "status": { - Type: schema.TypeString, - Computed: true, - Description: "Current model status of this compute instance.", - }, - - "tech_status": { - Type: schema.TypeString, - Computed: true, - Description: "Current technical status of this compute instance.", - }, - - "internal_ip": { - Type: schema.TypeString, - Computed: true, - Description: "Internal IP address of this Compute.", - }, - */ }, } } diff --git a/decort/data_source_grid.go b/decort/data_source_grid.go index cba38ed..2529e3f 100644 --- a/decort/data_source_grid.go +++ b/decort/data_source_grid.go @@ -37,7 +37,6 @@ func flattenGrid(d *schema.ResourceData, grid *Grid) { d.Set("guid", grid.Guid) d.Set("location_code", grid.LocationCode) d.Set("id", grid.Id) - return } func dataSourceGridRead(d *schema.ResourceData, m interface{}) error { diff --git a/decort/data_source_image.go b/decort/data_source_image.go index c7e7bd6..9a218e9 100644 --- a/decort/data_source_image.go +++ b/decort/data_source_image.go @@ -69,7 +69,6 @@ func flattenImage(d *schema.ResourceData, image *Image) { d.Set("meta", flattenMeta(image.Meta)) d.Set("desc", image.Desc) d.Set("shared_with", image.SharedWith) - return } func dataSourceImageRead(d *schema.ResourceData, m interface{}) error { diff --git a/decort/data_source_image_list_stacks.go b/decort/data_source_image_list_stacks.go index 508c7fd..7b37371 100644 --- a/decort/data_source_image_list_stacks.go +++ b/decort/data_source_image_list_stacks.go @@ -29,7 +29,7 @@ import ( "github.com/hashicorp/terraform-plugin-sdk/helper/schema" ) -func flattenImageListStacks(d *schema.ResourceData, stack ImageListStacks) []map[string]interface{} { +func flattenImageListStacks(_ *schema.ResourceData, stack ImageListStacks) []map[string]interface{} { temp := make([]map[string]interface{}, 0) for _, item := range stack { t := map[string]interface{}{ diff --git a/decort/data_source_vins.go b/decort/data_source_vins.go index 2fd712b..61fd3c5 100644 --- a/decort/data_source_vins.go +++ b/decort/data_source_vins.go @@ -48,13 +48,13 @@ func flattenVins(d *schema.ResourceData, vins_facts string) error { } log.Debugf("flattenVins: decoded ViNS name:ID %s:%d, account ID %d, RG ID %d", - vinsRecord.Name, vinsRecord.ID, vinsRecord.AccountID, vinsRecord.RgID) + vinsRecord.Name, vinsRecord.ID, vinsRecord.AccountID, vinsRecord.RgID) d.SetId(fmt.Sprintf("%d", vinsRecord.ID)) d.Set("name", vinsRecord.Name) d.Set("account_id", vinsRecord.AccountID) d.Set("account_name", vinsRecord.AccountName) - err = d.Set("rg_id", vinsRecord.RgID) + d.Set("rg_id", vinsRecord.RgID) d.Set("description", vinsRecord.Desc) d.Set("ipcidr", vinsRecord.IPCidr) @@ -117,11 +117,11 @@ func dataSourceVins() *schema.Resource { }, /* - "vins_id": { - Type: schema.TypeInt, - Optional: true, - Description: "Unique ID of the ViNS. If ViNS ID is specified, then ViNS name, rg_id and account_id are ignored.", - }, + "vins_id": { + Type: schema.TypeInt, + Optional: true, + Description: "Unique ID of the ViNS. If ViNS ID is specified, then ViNS name, rg_id and account_id are ignored.", + }, */ "rg_id": { diff --git a/decort/disk_subresource.go b/decort/disk_subresource.go deleted file mode 100644 index cf3a5c5..0000000 --- a/decort/disk_subresource.go +++ /dev/null @@ -1,86 +0,0 @@ -/* -Copyright (c) 2019-2021 Digital Energy Cloud Solutions LLC. All Rights Reserved. -Author: Sergey Shubin, , - -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. -*/ - -package decort - -import ( - // log "github.com/sirupsen/logrus" - - "github.com/hashicorp/terraform-plugin-sdk/helper/schema" - "github.com/hashicorp/terraform-plugin-sdk/helper/validation" -) - - -// ID, type, name, size, account ID, SEP ID, SEP type, pool, status, tech status, compute ID, image ID -func diskSubresourceSchemaMake() map[string]*schema.Schema { - rets := map[string]*schema.Schema{ - "name": { - Type: schema.TypeString, - Required: true, - Description: "Name of this disk.", - }, - - "size": { - Type: schema.TypeInt, - Required: true, - ValidateFunc: validation.IntAtLeast(1), - Description: "Size of the disk in GB.", - }, - - "account_id": { - Type: schema.TypeInt, - Computed: true, - ValidateFunc: validation.IntAtLeast(1), - Description: "ID of the account this disk belongs to.", - }, - - "type": { - Type: schema.TypeString, - Optional: true, - Description: "Type of this disk.", - }, - - "sep_id": { - Type: schema.TypeString, - Optional: true, - Default: "default", - Description: "ID of the storage end-point provider serving this disk.", - }, - - "sep_type": { - Type: schema.TypeString, - Optional: true, - Default: "default", - Description: "Type of the storage provider serving this disk.", - }, - - "pool": { - Type: schema.TypeString, - Optional: true, - Default: "default", - Description: "Pool on the storage where this disk is located.", - }, - - "image_id": { - Type: schema.TypeInt, - Computed: true, - Description: "ID of the binary Image this disk resource is cloned from (if any).", - }, - } - - return rets -} diff --git a/decort/interface_subresource.go b/decort/interface_subresource.go deleted file mode 100644 index d6f8a9b..0000000 --- a/decort/interface_subresource.go +++ /dev/null @@ -1,331 +0,0 @@ -/* -Copyright (c) 2019-2021 Digital Energy Cloud Solutions LLC. All Rights Reserved. -Author: Sergey Shubin, , - -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. -*/ - -/* - This file contains definitions and code for handling Interface component of Compute schema -*/ - -package decort - -import ( - /* - "log" - "strconv" - "strings" - */ - - "github.com/hashicorp/terraform-plugin-sdk/helper/schema" - // "github.com/hashicorp/terraform-plugin-sdk/helper/validation" -) - -func interfaceSubresourceSchemaMake() map[string]*schema.Schema { - rets := map[string]*schema.Schema{ - "net_id": { - Type: schema.TypeInt, - Computed: true, - Description: "ID of the network entity this interface is connected to.", - }, - - "net_type": { - Type: schema.TypeString, - Computed: true, - Description: "Type of the network entity this interface is connected to.", - }, - - "ip_address": { - Type: schema.TypeString, - Computed: true, - Description: "IP addresses assigned to this interface.", - }, - - "netmask": { - Type: schema.TypeInt, - Computed: true, - Description: "Network mask to be used with this interface.", - }, - - "mac": { - Type: schema.TypeString, - Computed: true, - Description: "MAC address of this interface.", - }, - - "default_gw": { - Type: schema.TypeString, - Computed: true, - Description: "Default gateway associated with this interface.", - }, - - "name": { - Type: schema.TypeString, - Computed: true, - Description: "Interface name.", - }, - - "connection_id": { - Type: schema.TypeInt, - Computed: true, - Description: "VxLAN or VLAN ID this interface is connected to.", - }, - - "connection_type": { - Type: schema.TypeString, - Computed: true, - Description: "Type of the segment (VLAN or VxLAN) this interface is connected to.", - }, - - "qos": { - Type: schema.TypeList, - Computed: true, - Elem: &schema.Resource{ - Schema: interfaceQosSubresourceSchemaMake(), - }, - Description: "QoS settings for this interface.", - }, - } - - return rets -} - -func interfaceQosSubresourceSchemaMake() map[string]*schema.Schema { - rets := map[string]*schema.Schema{ - "egress_rate": { - Type: schema.TypeInt, - Computed: true, - Description: "Egress rate limit on this interface.", - }, - - "ingress_burst": { - Type: schema.TypeInt, - Computed: true, - Description: "Ingress burst limit on this interface.", - }, - - "ingress_rate": { - Type: schema.TypeInt, - Computed: true, - Description: "Ingress rate limit on this interface.", - }, - - "guid": { - Type: schema.TypeString, - Computed: true, - Description: "GUID of this QoS record.", - }, - } - - return rets -} - -/* -func flattenNetworks(nets []NicRecord) []interface{} { - // this function expects an array of NicRecord as returned by machines/get API call - // NOTE: it does NOT expect a strucutre as returned by externalnetwork/list - var length = 0 - var strarray []string - - for _, value := range nets { - if value.NicType == "PUBLIC" { - length += 1 - } - } - log.Debugf("flattenNetworks: found %d NICs with PUBLIC type", length) - - result := make([]interface{}, length) - if length == 0 { - return result - } - - elem := make(map[string]interface{}) - - var subindex = 0 - for index, value := range nets { - if value.NicType == "PUBLIC" { - // this will be changed as network segments entity - // value.Params for ext net comes in a form "gateway:176.118.165.1 externalnetworkId:6" - // for network_id we need to extract from this string - strarray = strings.Split(value.Params, " ") - substr := strings.Split(strarray[1], ":") - elem["network_id"], _ = strconv.Atoi(substr[1]) - elem["ip_range"] = value.IPAddress - // elem["label"] = ... - should be uncommented for the future release - log.Debugf("flattenNetworks: parsed element %d - network_id %d, ip_range %s", - index, elem["network_id"].(int), value.IPAddress) - result[subindex] = elem - subindex += 1 - } - } - - return result -} - -func makePortforwardsConfig(arg_list []interface{}) (pfws []PortforwardConfig, count int) { - count = len(arg_list) - if count < 1 { - return nil, 0 - } - - pfws = make([]PortforwardConfig, count) - var subres_data map[string]interface{} - for index, value := range arg_list { - subres_data = value.(map[string]interface{}) - // pfws[index].Label = subres_data["label"].(string) - should be uncommented for future release - pfws[index].ExtPort = subres_data["ext_port"].(int) - pfws[index].IntPort = subres_data["int_port"].(int) - pfws[index].Proto = subres_data["proto"].(string) - } - - return pfws, count -} - -func flattenPortforwards(pfws []PortforwardRecord) []interface{} { - result := make([]interface{}, len(pfws)) - elem := make(map[string]interface{}) - var port_num int - - for index, value := range pfws { - // elem["label"] = ... - should be uncommented for the future release - - // external port field is of TypeInt in the portforwardSubresourceSchema, but string is returned - // by portforwards/list API, so we need conversion here - port_num, _ = strconv.Atoi(value.ExtPort) - elem["ext_port"] = port_num - // internal port field is of TypeInt in the portforwardSubresourceSchema, but string is returned - // by portforwards/list API, so we need conversion here - port_num, _ = strconv.Atoi(value.IntPort) - elem["int_port"] = port_num - elem["proto"] = value.Proto - elem["ext_ip"] = value.ExtIP - elem["int_ip"] = value.IntIP - result[index] = elem - } - - return result -} - -func portforwardSubresourceSchema() map[string]*schema.Schema { - rets := map[string]*schema.Schema{ - "label": { - Type: schema.TypeString, - Required: true, - Description: "Unique label of this network connection to identify it amnong other connections for this VM.", - }, - - "ext_port": { - Type: schema.TypeInt, - Required: true, - ValidateFunc: validation.IntBetween(1, 65535), - Description: "External port number for this port forwarding rule.", - }, - - "int_port": { - Type: schema.TypeInt, - Required: true, - ValidateFunc: validation.IntBetween(1, 65535), - Description: "Internal port number for this port forwarding rule.", - }, - - "proto": { - Type: schema.TypeString, - Required: true, - // ValidateFunc: validation.IntBetween(1, ), - Description: "Protocol type for this port forwarding rule. Should be either 'tcp' or 'udp'.", - }, - - "ext_ip": { - Type: schema.TypeString, - Computed: true, - Description: ".", - }, - - "int_ip": { - Type: schema.TypeString, - Computed: true, - Description: ".", - }, - } - - return rets -} - -func flattenNICs(nics []NicRecord) []interface{} { - var result = make([]interface{}, len(nics)) - elem := make(map[string]interface{}) - - for index, value := range nics { - elem["status"] = value.Status - elem["type"] = value.NicType - elem["mac"] = value.MacAddress - elem["ip_address"] = value.IPAddress - elem["parameters"] = value.Params - elem["reference_id"] = value.ReferenceID - elem["network_id"] = value.NetworkID - result[index] = elem - } - - return result -} - -func nicSubresourceSchema() map[string]*schema.Schema { - rets := map[string]*schema.Schema{ - "status": { - Type: schema.TypeString, - Computed: true, - Description: "Current status of this NIC.", - }, - - "type": { - Type: schema.TypeString, - Computed: true, - Description: "Type of this NIC.", - }, - - "mac": { - Type: schema.TypeString, - Computed: true, - Description: "MAC address assigned to this NIC.", - }, - - "ip_address": { - Type: schema.TypeString, - Computed: true, - Description: "IP address assigned to this NIC.", - }, - - "parameters": { - Type: schema.TypeString, - Computed: true, - Description: "Additional NIC parameters.", - }, - - "reference_id": { - Type: schema.TypeString, - Computed: true, - Description: "Reference ID of this NIC.", - }, - - "network_id": { - Type: schema.TypeInt, - Computed: true, - Description: "Network ID which this NIC is connected to.", - }, - } - - return rets -} - -*/ diff --git a/decort/network_subresource.go b/decort/network_subresource.go index 2e8ca3d..183fe5a 100644 --- a/decort/network_subresource.go +++ b/decort/network_subresource.go @@ -23,7 +23,9 @@ import ( // "fmt" "bytes" "hash/fnv" - log "github.com/sirupsen/logrus" + + log "github.com/sirupsen/logrus" + // "net/url" "sort" @@ -43,19 +45,19 @@ func networkSubresIPAddreDiffSupperss(key, oldVal, newVal string, d *schema.Reso return true // suppress difference } -// This function is based on the original Terraform SerializeResourceForHash found +// This function is based on the original Terraform SerializeResourceForHash found // in helper/schema/serialize.go -// It skips network subresource attributes, which are irrelevant for identification +// It skips network subresource attributes, which are irrelevant for identification // of unique network blocks func networkSubresourceSerialize(output *bytes.Buffer, val interface{}, resource *schema.Resource) { if val == nil { return } - + rs := resource.Schema m := val.(map[string]interface{}) - var keys []string + keys := make([]string, 0, len(rs)) allComputed := true for k, val := range rs { @@ -96,7 +98,7 @@ func networkSubresourceSerialize(output *bytes.Buffer, val interface{}, resource // from network subresource (e.g. in flattenCompute) // // This function is based on the original Terraform function HashResource from -// helper/schema/set.go +// helper/schema/set.go func HashNetworkSubresource(resource *schema.Resource) schema.SchemaSetFunc { return func(v interface{}) int { var serialized bytes.Buffer @@ -111,11 +113,11 @@ func HashNetworkSubresource(resource *schema.Resource) schema.SchemaSetFunc { func networkSubresourceSchemaMake() map[string]*schema.Schema { rets := map[string]*schema.Schema{ "net_type": { - Type: schema.TypeString, - Required: true, - StateFunc: stateFuncToUpper, + Type: schema.TypeString, + Required: true, + StateFunc: stateFuncToUpper, ValidateFunc: validation.StringInSlice([]string{"EXTNET", "VINS"}, false), // observe case while validating - Description: "Type of the network for this connection, either EXTNET or VINS.", + Description: "Type of the network for this connection, either EXTNET or VINS.", }, "net_id": { @@ -125,11 +127,11 @@ func networkSubresourceSchemaMake() map[string]*schema.Schema { }, "ip_address": { - Type: schema.TypeString, - Optional: true, - Computed: true, + Type: schema.TypeString, + Optional: true, + Computed: true, DiffSuppressFunc: networkSubresIPAddreDiffSupperss, - Description: "Optional IP address to assign to this connection. This IP should belong to the selected network and free for use.", + Description: "Optional IP address to assign to this connection. This IP should belong to the selected network and free for use.", }, "mac": { @@ -137,7 +139,6 @@ func networkSubresourceSchemaMake() map[string]*schema.Schema { Computed: true, Description: "MAC address associated with this connection. MAC address is assigned automatically.", }, - } return rets } diff --git a/decort/provider.go b/decort/provider.go index 2d9e3a9..8b5cff8 100644 --- a/decort/provider.go +++ b/decort/provider.go @@ -26,8 +26,6 @@ import ( // "github.com/hashicorp/terraform-plugin-sdk/terraform" ) -var decsController *ControllerCfg - func Provider() *schema.Provider { return &schema.Provider{ Schema: map[string]*schema.Schema{ diff --git a/decort/quota_subresource.go b/decort/quota_subresource.go index 7395f7d..f6e2fc1 100644 --- a/decort/quota_subresource.go +++ b/decort/quota_subresource.go @@ -28,7 +28,7 @@ import ( // "github.com/hashicorp/terraform-plugin-sdk/helper/validation" ) -func makeQuotaRecord(arg_list []interface{}) (QuotaRecord, int) { +func makeQuotaRecord(arg_list []interface{}) QuotaRecord { quota := QuotaRecord{ Cpu: -1, Ram: -1., // this is float64, but may change in the future @@ -63,7 +63,7 @@ func makeQuotaRecord(arg_list []interface{}) (QuotaRecord, int) { quota.GpuUnits = subres_data["gpu_units"].(int) } - return quota, 1 + return quota } func parseQuota(quota QuotaRecord) []interface{} { diff --git a/decort/resource_cdrom_image.go b/decort/resource_cdrom_image.go index 9711bf4..df93a21 100644 --- a/decort/resource_cdrom_image.go +++ b/decort/resource_cdrom_image.go @@ -385,16 +385,10 @@ func resourceCDROMImage() *schema.Resource { CustomizeDiff: customdiff.All( customdiff.IfValueChange("enabled", func(old, new, meta interface{}) bool { - if old.(bool) != new.(bool) { - return true - } - return false + return old.(bool) != new.(bool) }, resourceImageChangeEnabled), customdiff.IfValueChange("name", func(old, new, meta interface{}) bool { - if old.(string) != new.(string) && old.(string) != "" { - return true - } - return false + return old.(string) != new.(string) && old.(string) != "" }, resourceImageEditName), customdiff.IfValueChange("shared_with", func(old, new, meta interface{}) bool { o := old.([]interface{}) @@ -411,16 +405,10 @@ func resourceCDROMImage() *schema.Resource { count++ } } - if count == 0 { - return true - } - return false + return count == 0 }, resourceImageShare), customdiff.IfValueChange("computeci_id", func(old, new, meta interface{}) bool { - if old.(int) != new.(int) { - return true - } - return false + return old.(int) != new.(int) }, resourceImageChangeComputeci), customdiff.IfValueChange("enabled_stacks", func(old, new, meta interface{}) bool { o := old.([]interface{}) @@ -437,10 +425,7 @@ func resourceCDROMImage() *schema.Resource { count++ } } - if count == 0 { - return true - } - return false + return count == 0 }, resourceImageUpdateNodes), ), diff --git a/decort/resource_compute.go b/decort/resource_compute.go index b61d8b6..ea43785 100644 --- a/decort/resource_compute.go +++ b/decort/resource_compute.go @@ -132,7 +132,7 @@ func resourceComputeCreate(d *schema.ResourceData, m interface{}) error { log.Debugf("resourceComputeCreate: calling utilityComputeExtraDisksConfigure to attach %d extra disk(s)", argVal.(*schema.Set).Len()) err = controller.utilityComputeExtraDisksConfigure(d, false) // do_delta=false, as we are working on a new compute if err != nil { - log.Errorf("resourceComputeCreate: error when attaching extra disk(s) to a new Compute ID %s: %s", compId, err) + log.Errorf("resourceComputeCreate: error when attaching extra disk(s) to a new Compute ID %d: %v", compId, err) extraDisksOk = false } } @@ -167,8 +167,7 @@ func resourceComputeCreate(d *schema.ResourceData, m interface{}) error { reqValues := &url.Values{} reqValues.Add("computeId", fmt.Sprintf("%d", compId)) log.Debugf("resourceComputeCreate: starting Compute ID %d after completing its resource configuration", compId) - apiResp, err = controller.decortAPICall("POST", ComputeStartAPI, reqValues) - if err != nil { + if _, err := controller.decortAPICall("POST", ComputeStartAPI, reqValues); err != nil { return err } } @@ -269,7 +268,7 @@ func resourceComputeUpdate(d *schema.ResourceData, m interface{}) error { } d.SetPartial("boot_disk_size") } else if oldSize.(int) > newSize.(int) { - log.Warnf("resourceComputeUpdate: compute ID %d - shrinking boot disk is not allowed", d.Id()) + log.Warnf("resourceComputeUpdate: compute ID %s - shrinking boot disk is not allowed", d.Id()) } // 3. Calculate and apply changes to data disks @@ -320,6 +319,9 @@ func resourceComputeDelete(d *schema.ResourceData, m interface{}) error { compFacts, err := utilityComputeCheckPresence(d, m) if compFacts == "" { + if err != nil { + return err + } // the target Compute does not exist - in this case according to Terraform best practice // we exit from Destroy method without error return nil @@ -540,39 +542,6 @@ func resourceCompute() *schema.Resource { Default: true, Description: "Is compute started.", }, - - /* - "disks": { - Type: schema.TypeList, - Computed: true, - Elem: &schema.Resource{ - Schema: dataSourceDiskSchemaMake(), // ID, type, name, size, account ID, SEP ID, SEP type, pool, status, tech status, compute ID, image ID - }, - Description: "Detailed specification for all disks attached to this compute instance (including bood disk).", - }, - - "interfaces": { - Type: schema.TypeList, - Computed: true, - Elem: &schema.Resource{ - Schema: interfaceSubresourceSchemaMake(), - }, - Description: "Specification for the virtual NICs configured on this compute instance.", - }, - - - "status": { - Type: schema.TypeString, - Computed: true, - Description: "Current model status of this compute instance.", - }, - - "tech_status": { - Type: schema.TypeString, - Computed: true, - Description: "Current technical status of this compute instance.", - }, - */ }, } } diff --git a/decort/resource_disk.go b/decort/resource_disk.go index a19bf08..0177879 100644 --- a/decort/resource_disk.go +++ b/decort/resource_disk.go @@ -49,11 +49,11 @@ func resourceDiskCreate(d *schema.ResourceData, m interface{}) error { urlValues.Add("type", "D") // NOTE: only disks of Data type are managed via plugin urlValues.Add("sep_id", fmt.Sprintf("%d", d.Get("sep_id").(int))) urlValues.Add("pool", d.Get("pool").(string)) - + argVal, argSet := d.GetOk("description") if argSet { urlValues.Add("description", argVal.(string)) - } + } apiResp, err := controller.decortAPICall("POST", DisksCreateAPI, urlValues) if err != nil { @@ -65,9 +65,9 @@ func resourceDiskCreate(d *schema.ResourceData, m interface{}) error { log.Debugf("resourceDiskCreate: new Disk ID / name %d / %s creation sequence complete", diskId, d.Get("name").(string)) - // We may reuse dataSourceDiskRead here as we maintain similarity + // We may reuse dataSourceDiskRead here as we maintain similarity // between Disk resource and Disk data source schemas - // Disk resource read function will also update resource ID on success, so that Terraform + // Disk resource read function will also update resource ID on success, so that Terraform // will know the resource exists (however, we already did it a few lines before) return dataSourceDiskRead(d, m) } @@ -100,8 +100,8 @@ func resourceDiskUpdate(d *schema.ResourceData, m interface{}) error { oldSize, newSize := d.GetChange("size") if oldSize.(int) < newSize.(int) { - log.Debugf("resourceDiskUpdate: resizing disk ID %s - %d GB -> %d GB", - d.Id(), oldSize.(int), newSize.(int)) + log.Debugf("resourceDiskUpdate: resizing disk ID %s - %d GB -> %d GB", + d.Id(), oldSize.(int), newSize.(int)) sizeParams := &url.Values{} sizeParams.Add("diskId", d.Id()) sizeParams.Add("size", fmt.Sprintf("%d", newSize.(int))) @@ -116,8 +116,8 @@ func resourceDiskUpdate(d *schema.ResourceData, m interface{}) error { oldName, newName := d.GetChange("name") if oldName.(string) != newName.(string) { - log.Debugf("resourceDiskUpdate: renaming disk ID %d - %s -> %s", - d.Get("disk_id").(int), oldName.(string), newName.(string)) + log.Debugf("resourceDiskUpdate: renaming disk ID %d - %s -> %s", + d.Get("disk_id").(int), oldName.(string), newName.(string)) renameParams := &url.Values{} renameParams.Add("diskId", d.Id()) renameParams.Add("name", newName.(string)) @@ -129,24 +129,24 @@ func resourceDiskUpdate(d *schema.ResourceData, m interface{}) error { } /* - NOTE: plugin will manage disks of type "Data" only, and type cannot be changed once disk is created + NOTE: plugin will manage disks of type "Data" only, and type cannot be changed once disk is created - oldType, newType := d.GetChange("type") - if oldType.(string) != newType.(string) { - return fmt.Errorf("resourceDiskUpdate: Disk ID %s - changing type of existing disk not allowed", d.Id()) - } + oldType, newType := d.GetChange("type") + if oldType.(string) != newType.(string) { + return fmt.Errorf("resourceDiskUpdate: Disk ID %s - changing type of existing disk not allowed", d.Id()) + } */ d.Partial(false) - // we may reuse dataSourceDiskRead here as we maintain similarity + // we may reuse dataSourceDiskRead here as we maintain similarity // between Compute resource and Compute data source schemas - return dataSourceDiskRead(d, m) + return dataSourceDiskRead(d, m) } func resourceDiskDelete(d *schema.ResourceData, m interface{}) error { - // NOTE: this function tries to detach and destroy target Disk "permanently", so - // there is no way to restore it. + // NOTE: this function tries to detach and destroy target Disk "permanently", so + // there is no way to restore it. // If, however, the disk is attached to a compute, the method will // fail (by failing the underpinning DECORt API call, which is issued with detach=false) log.Debugf("resourceDiskDelete: called for Disk ID / name %d / %s, Account ID %d", @@ -154,6 +154,9 @@ func resourceDiskDelete(d *schema.ResourceData, m interface{}) error { diskFacts, err := utilityDiskCheckPresence(d, m) if diskFacts == "" { + if err != nil { + return err + } // the specified Disk does not exist - in this case according to Terraform best practice // we exit from Destroy method without error return nil @@ -166,8 +169,8 @@ func resourceDiskDelete(d *schema.ResourceData, m interface{}) error { // However, this may change in the future, as TF state management logic may want // to delete disk resource BEFORE it is detached from compute instance, and, while // perfectly OK from data preservation viewpoint, this is breaking expected TF workflow - // in the eyes of an experienced TF user - params.Add("detach", "0") + // in the eyes of an experienced TF user + params.Add("detach", "0") params.Add("permanently", "1") controller := m.(*ControllerCfg) @@ -215,29 +218,29 @@ func resourceDiskSchemaMake() map[string]*schema.Schema { }, "sep_id": { - Type: schema.TypeInt, - Required: true, - ForceNew: true, + Type: schema.TypeInt, + Required: true, + ForceNew: true, ValidateFunc: validation.IntAtLeast(1), - Description: "Storage end-point provider serving this disk. Cannot be changed for existing disk.", + Description: "Storage end-point provider serving this disk. Cannot be changed for existing disk.", }, "pool": { - Type: schema.TypeString, - Required: true, - ForceNew: true, + Type: schema.TypeString, + Required: true, + ForceNew: true, ValidateFunc: validation.StringIsNotEmpty, - Description: "Pool where this disk is located. Cannot be changed for existing disk.", + Description: "Pool where this disk is located. Cannot be changed for existing disk.", }, "size": { - Type: schema.TypeInt, - Required: true, + Type: schema.TypeInt, + Required: true, ValidateFunc: validation.IntAtLeast(1), - Description: "Size of the disk in GB. Note, that existing disks can only be grown in size.", + Description: "Size of the disk in GB. Note, that existing disks can only be grown in size.", }, - /* We moved "type" attribute to computed attributes section, as plugin manages disks of only + /* We moved "type" attribute to computed attributes section, as plugin manages disks of only one type - "D", e.g. data disks. "type": { Type: schema.TypeString, @@ -256,7 +259,7 @@ func resourceDiskSchemaMake() map[string]*schema.Schema { Description: "Optional user-defined text description of this disk.", }, - // The rest of the attributes are all computed + // The rest of the attributes are all computed "account_name": { Type: schema.TypeString, Computed: true, @@ -282,14 +285,14 @@ func resourceDiskSchemaMake() map[string]*schema.Schema { }, /* - "snapshots": { - Type: schema.TypeList, - Computed: true, - Elem: &schema.Resource { - Schema: snapshotSubresourceSchemaMake(), + "snapshots": { + Type: schema.TypeList, + Computed: true, + Elem: &schema.Resource { + Schema: snapshotSubresourceSchemaMake(), + }, + Description: "List of user-created snapshots for this disk." }, - Description: "List of user-created snapshots for this disk." - }, */ } diff --git a/decort/resource_image.go b/decort/resource_image.go index 6e206c4..cd4b970 100644 --- a/decort/resource_image.go +++ b/decort/resource_image.go @@ -87,8 +87,7 @@ func resourceImageCreate(d *schema.ResourceData, m interface{}) error { } api := "" - isSync := d.Get("sync").(bool) - if !isSync { + if isSync := d.Get("sync").(bool); !isSync { api = imageCreateAPI } else { api = imageSyncCreateAPI @@ -640,16 +639,10 @@ func resourceImage() *schema.Resource { }, CustomizeDiff: customdiff.All( customdiff.IfValueChange("enabled", func(old, new, meta interface{}) bool { - if old.(bool) != new.(bool) { - return true - } - return false + return old.(bool) != new.(bool) }, resourceImageChangeEnabled), customdiff.IfValueChange("name", func(old, new, meta interface{}) bool { - if old.(string) != new.(string) && old.(string) != "" { - return true - } - return false + return old.(string) != new.(string) && old.(string) != "" }, resourceImageEditName), customdiff.IfValueChange("shared_with", func(old, new, meta interface{}) bool { o := old.([]interface{}) @@ -667,16 +660,10 @@ func resourceImage() *schema.Resource { count++ } } - if count == 0 { - return true - } - return false + return count == 0 }, resourceImageShare), customdiff.IfValueChange("computeci_id", func(old, new, meta interface{}) bool { - if old.(int) != new.(int) { - return true - } - return false + return old.(int) != new.(int) }, resourceImageChangeComputeci), customdiff.IfValueChange("enabled_stacks", func(old, new, meta interface{}) bool { o := old.([]interface{}) @@ -693,10 +680,7 @@ func resourceImage() *schema.Resource { count++ } } - if count == 0 { - return true - } - return false + return count == 0 }, resourceImageUpdateNodes), ), diff --git a/decort/resource_k8s.go b/decort/resource_k8s.go index 109fc49..e0f3cb0 100644 --- a/decort/resource_k8s.go +++ b/decort/resource_k8s.go @@ -223,15 +223,13 @@ func resourceK8sUpdate(d *schema.ResourceData, m interface{}) error { if newWorkers.Num > wg.Num { urlValues.Add("num", strconv.Itoa(newWorkers.Num-wg.Num)) - _, err := controller.decortAPICall("POST", K8sWorkerAddAPI, urlValues) - if err != nil { + if _, err := controller.decortAPICall("POST", K8sWorkerAddAPI, urlValues); err != nil { return err } } else { for i := wg.Num - 1; i >= newWorkers.Num; i-- { urlValues.Set("workerId", strconv.Itoa(wg.DetailedInfo[i].ID)) - _, err := controller.decortAPICall("POST", K8sWorkerDeleteAPI, urlValues) - if err != nil { + if _, err := controller.decortAPICall("POST", K8sWorkerDeleteAPI, urlValues); err != nil { return err } } diff --git a/decort/resource_k8s_wg.go b/decort/resource_k8s_wg.go index 4ce3a0d..d9f4054 100644 --- a/decort/resource_k8s_wg.go +++ b/decort/resource_k8s_wg.go @@ -108,16 +108,14 @@ func resourceK8sWgUpdate(d *schema.ResourceData, m interface{}) error { wg, err := utilityK8sWgCheckPresence(d, m) if err != nil { - return nil + return err } urlValues := &url.Values{} urlValues.Add("k8sId", strconv.Itoa(d.Get("k8s_id").(int))) urlValues.Add("workersGroupId", d.Id()) - newNum := d.Get("num").(int) - - if newNum > wg.Num { + if newNum := d.Get("num").(int); newNum > wg.Num { urlValues.Add("num", strconv.Itoa(newNum-wg.Num)) _, err := controller.decortAPICall("POST", K8sWorkerAddAPI, urlValues) if err != nil { diff --git a/decort/resource_rg.go b/decort/resource_rg.go index 4a07cb6..b739f76 100644 --- a/decort/resource_rg.go +++ b/decort/resource_rg.go @@ -70,7 +70,7 @@ func resourceResgroupCreate(d *schema.ResourceData, m interface{}) error { arg_value, arg_set := d.GetOk("quota") if arg_set { log.Debugf("resourceResgroupCreate: setting Quota on RG requested") - quota_record, _ = makeQuotaRecord(arg_value.([]interface{})) + quota_record = makeQuotaRecord(arg_value.([]interface{})) set_quota = true } @@ -142,7 +142,7 @@ func resourceResgroupCreate(d *schema.ResourceData, m interface{}) error { } func resourceResgroupRead(d *schema.ResourceData, m interface{}) error { - log.Debugf("resourceResgroupRead: called for RG name %s, account ID %s", + log.Debugf("resourceResgroupRead: called for RG name %s, account ID %d", d.Get("name").(string), d.Get("account_id").(int)) rg_facts, err := utilityResgroupCheckPresence(d, m) @@ -199,9 +199,9 @@ func resourceResgroupUpdate(d *schema.ResourceData, m interface{}) error { quota_value, quota_set := d.GetOk("quota") if quota_set { log.Debugf("resourceResgroupUpdate: quota specified - looking for deltas from the old quota.") - quotarecord_new, _ := makeQuotaRecord(quota_value.([]interface{})) + quotarecord_new := makeQuotaRecord(quota_value.([]interface{})) quota_value_old, _ := d.GetChange("quota") // returns old as 1st, new as 2nd return value - quotarecord_old, _ := makeQuotaRecord(quota_value_old.([]interface{})) + quotarecord_old := makeQuotaRecord(quota_value_old.([]interface{})) if quotarecord_new.Cpu != quotarecord_old.Cpu { do_general_update = true @@ -260,11 +260,14 @@ func resourceResgroupUpdate(d *schema.ResourceData, m interface{}) error { func resourceResgroupDelete(d *schema.ResourceData, m interface{}) error { // NOTE: this method forcibly destroys target resource group with flag "permanently", so there is no way to // restore the destroyed resource group as well all Computes & VINSes that existed in it - log.Debugf("resourceResgroupDelete: called for RG name %s, account ID %s", + log.Debugf("resourceResgroupDelete: called for RG name %s, account ID %d", d.Get("name").(string), d.Get("account_id").(int)) rg_facts, err := utilityResgroupCheckPresence(d, m) if rg_facts == "" { + if err != nil { + return err + } // the target RG does not exist - in this case according to Terraform best practice // we exit from Destroy method without error return nil diff --git a/decort/resource_sep.go b/decort/resource_sep.go index 059198d..d3608e3 100644 --- a/decort/resource_sep.go +++ b/decort/resource_sep.go @@ -243,8 +243,7 @@ func resourceSepEdit(d *schema.ResourceData, m interface{}) error { } urlValues = &url.Values{} - err := resourceSepRead(d, m) - if err != nil { + if err := resourceSepRead(d, m); err != nil { return err } @@ -282,8 +281,6 @@ func resourceSepUpdateNodes(d *schema.ResourceDiff, m interface{}) error { urlValues := &url.Values{} t1, t2 := d.GetChange("consumed_by") - d1 := t1.([]interface{}) - d2 := t2.([]interface{}) urlValues.Add("sep_id", strconv.Itoa(d.Get("sep_id").(int))) @@ -291,7 +288,7 @@ func resourceSepUpdateNodes(d *schema.ResourceDiff, m interface{}) error { temp := "" api := "" - if len(d1) > len(d2) { + if d1, d2 := t1.([]interface{}), t2.([]interface{}); len(d1) > len(d2) { for _, n := range d2 { if !findElInt(d1, n) { consumedIds = append(consumedIds, n) @@ -510,10 +507,7 @@ func resourceSep() *schema.Resource { CustomizeDiff: customdiff.All( customdiff.IfValueChange("enable", func(old, new, meta interface{}) bool { - if old.(bool) != new.(bool) { - return true - } - return false + return old.(bool) != new.(bool) }, resourceSepChangeEnabled), customdiff.IfValueChange("consumed_by", func(old, new, meta interface{}) bool { o := old.([]interface{}) @@ -530,10 +524,7 @@ func resourceSep() *schema.Resource { count++ } } - if count == 0 { - return true - } - return false + return count == 0 }, resourceSepUpdateNodes), customdiff.IfValueChange("provided_by", func(old, new, meta interface{}) bool { o := old.([]interface{}) @@ -550,10 +541,7 @@ func resourceSep() *schema.Resource { count++ } } - if count == 0 { - return true - } - return false + return count == 0 }, resourceSepUpdateProviders), ), } diff --git a/decort/resource_sep_config.go b/decort/resource_sep_config.go index 9663291..c16b0f0 100644 --- a/decort/resource_sep_config.go +++ b/decort/resource_sep_config.go @@ -55,9 +55,7 @@ func resourceSepConfigCreate(d *schema.ResourceData, m interface{}) error { return errors.New("provided sep id config does not exist") } - resourceSepConfigRead(d, m) - - return nil + return resourceSepConfigRead(d, m) } func resourceSepConfigRead(d *schema.ResourceData, m interface{}) error { diff --git a/decort/resource_snapshot.go b/decort/resource_snapshot.go index 75f2b29..7a75867 100644 --- a/decort/resource_snapshot.go +++ b/decort/resource_snapshot.go @@ -191,7 +191,7 @@ func resourceSnapshot() *schema.Resource { CustomizeDiff: customdiff.All( customdiff.IfValueChange("rollback", func(old, new, meta interface{}) bool { o := old.(bool) - if o != new.(bool) && o == false { + if o != new.(bool) && !o { return true } return false diff --git a/decort/resource_vins.go b/decort/resource_vins.go index caa9b58..cdfb5f6 100644 --- a/decort/resource_vins.go +++ b/decort/resource_vins.go @@ -40,7 +40,7 @@ import ( func ipcidrDiffSupperss(key, oldVal, newVal string, d *schema.ResourceData) bool { if oldVal == "" && newVal != "" { // if old value for "ipcidr" resource is empty string, it means that we are creating new ViNS - // and there is a chance that the user will want specific IP address range for this ViNS - + // and there is a chance that the user will want specific IP address range for this ViNS - // check if "ipcidr" is explicitly set in TF file to a non-empty string. log.Debugf("ipcidrDiffSupperss: key=%s, oldVal=%q, newVal=%q -> suppress=FALSE", key, oldVal, newVal) return false // there is a difference between stored and new value @@ -51,7 +51,7 @@ func ipcidrDiffSupperss(key, oldVal, newVal string, d *schema.ResourceData) bool func resourceVinsCreate(d *schema.ResourceData, m interface{}) error { log.Debugf("resourceVinsCreate: called for ViNS name %s, Account ID %d, RG ID %d", - d.Get("name").(string), d.Get("account_id").(int), d.Get("rg_id").(int)) + d.Get("name").(string), d.Get("account_id").(int), d.Get("rg_id").(int)) apiToCall := VinsCreateInAccountAPI @@ -65,7 +65,7 @@ func resourceVinsCreate(d *schema.ResourceData, m interface{}) error { apiToCall = VinsCreateInRgAPI urlValues.Add("rgId", fmt.Sprintf("%d", argVal.(int))) } else { - // RG ID either not set at all or set to 0 - user may want ViNS at account level + // RG ID either not set at all or set to 0 - user may want ViNS at account level argVal, argSet = d.GetOk("account_id") if !argSet || argVal.(int) <= 0 { // No valid Account ID (and no RG ID either) - cannot create ViNS @@ -79,14 +79,14 @@ func resourceVinsCreate(d *schema.ResourceData, m interface{}) error { if argVal.(int) > 0 { // connect to specific external network urlValues.Add("extNetId", fmt.Sprintf("%d", argVal.(int))) - /* - Commented out, as we've made "ext_net_ip" parameter non-configurable via Terraform! - - // in case of specific ext net connection user may also want a particular IP address - argVal, argSet = d.GetOk("ext_net_ip") - if argSet && argVal.(string) != "" { - urlValues.Add("extIp", argVal.(string)) - } + /* + Commented out, as we've made "ext_net_ip" parameter non-configurable via Terraform! + + // in case of specific ext net connection user may also want a particular IP address + argVal, argSet = d.GetOk("ext_net_ip") + if argSet && argVal.(string) != "" { + urlValues.Add("extIp", argVal.(string)) + } */ } else { // ext_net_id is set to a negative value - connect to default external network @@ -100,7 +100,7 @@ func resourceVinsCreate(d *schema.ResourceData, m interface{}) error { log.Debugf("resourceVinsCreate: ipcidr is set to %s", argVal.(string)) urlValues.Add("ipcidr", argVal.(string)) } - + argVal, argSet = d.GetOk("description") if argSet { urlValues.Add("desc", argVal.(string)) @@ -116,9 +116,9 @@ func resourceVinsCreate(d *schema.ResourceData, m interface{}) error { log.Debugf("resourceVinsCreate: new ViNS ID / name %d / %s creation sequence complete", vinsId, d.Get("name").(string)) - // We may reuse dataSourceVinsRead here as we maintain similarity + // We may reuse dataSourceVinsRead here as we maintain similarity // between ViNS resource and ViNS data source schemas - // ViNS resource read function will also update resource ID on success, so that Terraform + // ViNS resource read function will also update resource ID on success, so that Terraform // will know the resource exists (however, we already did it a few lines before) return dataSourceVinsRead(d, m) } @@ -138,12 +138,12 @@ func resourceVinsRead(d *schema.ResourceData, m interface{}) error { func resourceVinsUpdate(d *schema.ResourceData, m interface{}) error { log.Debugf("resourceVinsUpdate: called for ViNS ID / name %s / %s, Account ID %d, RG ID %d", - d.Id(), d.Get("name").(string), d.Get("account_id").(int), d.Get("rg_id").(int)) + d.Id(), d.Get("name").(string), d.Get("account_id").(int), d.Get("rg_id").(int)) controller := m.(*ControllerCfg) d.Partial(true) - + // 1. Handle external network connection change oldExtNetId, newExtNedId := d.GetChange("ext_net_id") if oldExtNetId.(int) != newExtNedId.(int) { @@ -168,15 +168,15 @@ func resourceVinsUpdate(d *schema.ResourceData, m interface{}) error { return err } } - + d.SetPartial("ext_net_id") } d.Partial(false) - // we may reuse dataSourceVinsRead here as we maintain similarity + // we may reuse dataSourceVinsRead here as we maintain similarity // between Compute resource and Compute data source schemas - return dataSourceVinsRead(d, m) + return dataSourceVinsRead(d, m) } func resourceVinsDelete(d *schema.ResourceData, m interface{}) error { @@ -185,6 +185,9 @@ func resourceVinsDelete(d *schema.ResourceData, m interface{}) error { vinsFacts, err := utilityVinsCheckPresence(d, m) if vinsFacts == "" { + if err != nil { + return err + } // the specified ViNS does not exist - in this case according to Terraform best practice // we exit from Destroy method without error return nil @@ -192,8 +195,8 @@ func resourceVinsDelete(d *schema.ResourceData, m interface{}) error { params := &url.Values{} params.Add("vinsId", d.Id()) - params.Add("force", "1") // disconnect all computes before deleting ViNS - params.Add("permanently", "1") // delete ViNS immediately bypassing recycle bin + params.Add("force", "1") // disconnect all computes before deleting ViNS + params.Add("permanently", "1") // delete ViNS immediately bypassing recycle bin controller := m.(*ControllerCfg) _, err = controller.decortAPICall("POST", VinsDeleteAPI, params) @@ -222,10 +225,10 @@ func resourceVinsExists(d *schema.ResourceData, m interface{}) (bool, error) { func resourceVinsSchemaMake() map[string]*schema.Schema { rets := map[string]*schema.Schema{ "name": { - Type: schema.TypeString, - Required: true, + Type: schema.TypeString, + Required: true, ValidateFunc: validation.StringIsNotEmpty, - Description: "Name of the ViNS. Names are case sensitive and unique within the context of an account or resource group.", + Description: "Name of the ViNS. Names are case sensitive and unique within the context of an account or resource group.", }, /* we do not need ViNS ID as an argument because if we already know this ID, it is not practical to call resource provider. @@ -246,25 +249,25 @@ func resourceVinsSchemaMake() map[string]*schema.Schema { }, "account_id": { - Type: schema.TypeInt, - Required: true, - ForceNew: true, + Type: schema.TypeInt, + Required: true, + ForceNew: true, ValidateFunc: validation.IntAtLeast(1), - Description: "ID of the account, which this ViNS belongs to. For ViNS created at account level, resource group ID is 0.", + Description: "ID of the account, which this ViNS belongs to. For ViNS created at account level, resource group ID is 0.", }, "ext_net_id": { - Type: schema.TypeInt, - Required: true, + Type: schema.TypeInt, + Required: true, ValidateFunc: validation.IntAtLeast(0), - Description: "ID of the external network this ViNS is connected to. Pass 0 if no external connection required.", + Description: "ID of the external network this ViNS is connected to. Pass 0 if no external connection required.", }, "ipcidr": { - Type: schema.TypeString, - Optional: true, + Type: schema.TypeString, + Optional: true, DiffSuppressFunc: ipcidrDiffSupperss, - Description: "Network address to use by this ViNS. This parameter is only valid when creating new ViNS.", + Description: "Network address to use by this ViNS. This parameter is only valid when creating new ViNS.", }, "description": { diff --git a/decort/resource_virtual_image.go b/decort/resource_virtual_image.go index b1cec35..5097db1 100644 --- a/decort/resource_virtual_image.go +++ b/decort/resource_virtual_image.go @@ -332,22 +332,13 @@ func resourceVirtualImage() *schema.Resource { CustomizeDiff: customdiff.All( customdiff.IfValueChange("enabled", func(old, new, meta interface{}) bool { - if old.(bool) != new.(bool) { - return true - } - return false + return old.(bool) != new.(bool) }, resourceImageChangeEnabled), customdiff.IfValueChange("link_to", func(old, new, meta interface{}) bool { - if old.(int) != new.(int) { - return true - } - return false + return old.(int) != new.(int) }, resourceImageLink), customdiff.IfValueChange("name", func(old, new, meta interface{}) bool { - if old.(string) != new.(string) && old.(string) != "" { - return true - } - return false + return old.(string) != new.(string) && old.(string) != "" }, resourceImageEditName), customdiff.IfValueChange("shared_with", func(old, new, meta interface{}) bool { o := old.([]interface{}) @@ -364,16 +355,10 @@ func resourceVirtualImage() *schema.Resource { count++ } } - if count == 0 { - return true - } - return false + return count == 0 }, resourceImageShare), customdiff.IfValueChange("computeci_id", func(old, new, meta interface{}) bool { - if old.(int) != new.(int) { - return true - } - return false + return old.(int) != new.(int) }, resourceImageChangeComputeci), customdiff.IfValueChange("enabled_stacks", func(old, new, meta interface{}) bool { o := old.([]interface{}) @@ -390,10 +375,7 @@ func resourceVirtualImage() *schema.Resource { count++ } } - if count == 0 { - return true - } - return false + return count == 0 }, resourceImageUpdateNodes), ), diff --git a/decort/utility_compute.go b/decort/utility_compute.go index 8767a25..d8b559d 100644 --- a/decort/utility_compute.go +++ b/decort/utility_compute.go @@ -38,14 +38,14 @@ import ( func (ctrl *ControllerCfg) utilityComputeExtraDisksConfigure(d *schema.ResourceData, do_delta bool) error { // d is filled with data according to computeResource schema, so extra disks config is retrieved via "extra_disks" key - // If do_delta is true, this function will identify changes between new and existing specs for extra disks and try to + // If do_delta is true, this function will identify changes between new and existing specs for extra disks and try to // update compute configuration accordingly - // Otherwise it will apply whatever is found in the new set of "extra_disks" right away. + // Otherwise it will apply whatever is found in the new set of "extra_disks" right away. // Primary use of do_delta=false is when calling this function from compute Create handler. - // Note that this function will not abort on API errors, but will continue to configure (attach / detach) other individual + // Note that this function will not abort on API errors, but will continue to configure (attach / detach) other individual // disks via atomic API calls. However, it will not retry failed manipulation on the same disk. - log.Debugf("utilityComputeExtraDisksConfigure: called for Compute ID %s with do_delta = %b", d.Id(), do_delta) + log.Debugf("utilityComputeExtraDisksConfigure: called for Compute ID %s with do_delta = %t", d.Id(), do_delta) // NB: as of rc-1.25 "extra_disks" are TypeSet with the elem of TypeInt old_set, new_set := d.GetChange("extra_disks") @@ -71,11 +71,11 @@ func (ctrl *ControllerCfg) utilityComputeExtraDisksConfigure(d *schema.ResourceD } if apiErrCount > 0 { - log.Errorf("utilityComputeExtraDisksConfigure: there were %d error(s) when attaching disks to Compute ID %s. Last error was: %s", - apiErrCount, d.Id(), lastSavedError) + log.Errorf("utilityComputeExtraDisksConfigure: there were %d error(s) when attaching disks to Compute ID %s. Last error was: %s", + apiErrCount, d.Id(), lastSavedError) return lastSavedError } - + return nil } @@ -110,8 +110,8 @@ func (ctrl *ControllerCfg) utilityComputeExtraDisksConfigure(d *schema.ResourceD } if apiErrCount > 0 { - log.Errorf("utilityComputeExtraDisksConfigure: there were %d error(s) when managing disks of Compute ID %s. Last error was: %s", - apiErrCount, d.Id(), lastSavedError) + log.Errorf("utilityComputeExtraDisksConfigure: there were %d error(s) when managing disks of Compute ID %s. Last error was: %s", + apiErrCount, d.Id(), lastSavedError) return lastSavedError } @@ -120,11 +120,11 @@ func (ctrl *ControllerCfg) utilityComputeExtraDisksConfigure(d *schema.ResourceD func (ctrl *ControllerCfg) utilityComputeNetworksConfigure(d *schema.ResourceData, do_delta bool) error { // "d" is filled with data according to computeResource schema, so extra networks config is retrieved via "network" key - // If do_delta is true, this function will identify changes between new and existing specs for network and try to + // If do_delta is true, this function will identify changes between new and existing specs for network and try to // update compute configuration accordingly - // Otherwise it will apply whatever is found in the new set of "network" right away. + // Otherwise it will apply whatever is found in the new set of "network" right away. // Primary use of do_delta=false is when calling this function from compute Create handler. - + old_set, new_set := d.GetChange("network") apiErrCount := 0 @@ -137,7 +137,7 @@ func (ctrl *ControllerCfg) utilityComputeNetworksConfigure(d *schema.ResourceDat for _, runner := range new_set.(*schema.Set).List() { urlValues := &url.Values{} - net_data := runner.(map[string]interface{}) + net_data := runner.(map[string]interface{}) urlValues.Add("computeId", d.Id()) urlValues.Add("netType", net_data["net_type"].(string)) urlValues.Add("netId", fmt.Sprintf("%d", net_data["net_id"].(int))) @@ -154,8 +154,8 @@ func (ctrl *ControllerCfg) utilityComputeNetworksConfigure(d *schema.ResourceDat } if apiErrCount > 0 { - log.Errorf("utilityComputeNetworksConfigure: there were %d error(s) when managing networks of Compute ID %s. Last error was: %s", - apiErrCount, d.Id(), lastSavedError) + log.Errorf("utilityComputeNetworksConfigure: there were %d error(s) when managing networks of Compute ID %s. Last error was: %s", + apiErrCount, d.Id(), lastSavedError) return lastSavedError } return nil @@ -172,8 +172,8 @@ func (ctrl *ControllerCfg) utilityComputeNetworksConfigure(d *schema.ResourceDat _, err := ctrl.decortAPICall("POST", ComputeNetDetachAPI, urlValues) if err != nil { // failed to detach this network - there will be partial resource update - log.Errorf("utilityComputeNetworksConfigure: failed to detach net ID %d of type %s from Compute ID %s: %s", - net_data["net_id"].(int), net_data["net_type"].(string), d.Id(), err) + log.Errorf("utilityComputeNetworksConfigure: failed to detach net ID %d of type %s from Compute ID %s: %s", + net_data["net_id"].(int), net_data["net_type"].(string), d.Id(), err) apiErrCount++ lastSavedError = err } @@ -185,7 +185,7 @@ func (ctrl *ControllerCfg) utilityComputeNetworksConfigure(d *schema.ResourceDat urlValues := &url.Values{} net_data := runner.(map[string]interface{}) urlValues.Add("computeId", d.Id()) - urlValues.Add("netId", fmt.Sprintf("%d",net_data["net_id"].(int))) + urlValues.Add("netId", fmt.Sprintf("%d", net_data["net_id"].(int))) urlValues.Add("netType", net_data["net_type"].(string)) if net_data["ip_address"].(string) != "" { urlValues.Add("ipAddr", net_data["ip_address"].(string)) @@ -193,16 +193,16 @@ func (ctrl *ControllerCfg) utilityComputeNetworksConfigure(d *schema.ResourceDat _, err := ctrl.decortAPICall("POST", ComputeNetAttachAPI, urlValues) if err != nil { // failed to attach this network - there will be partial resource update - log.Errorf("utilityComputeNetworksConfigure: failed to attach net ID %d of type %s to Compute ID %s: %s", - net_data["net_id"].(int), net_data["net_type"].(string), d.Id(), err) + log.Errorf("utilityComputeNetworksConfigure: failed to attach net ID %d of type %s to Compute ID %s: %s", + net_data["net_id"].(int), net_data["net_type"].(string), d.Id(), err) apiErrCount++ lastSavedError = err } } - + if apiErrCount > 0 { - log.Errorf("utilityComputeNetworksConfigure: there were %d error(s) when managing networks of Compute ID %s. Last error was: %s", - apiErrCount, d.Id(), lastSavedError) + log.Errorf("utilityComputeNetworksConfigure: there were %d error(s) when managing networks of Compute ID %s. Last error was: %s", + apiErrCount, d.Id(), lastSavedError) return lastSavedError } @@ -262,7 +262,7 @@ func utilityComputeCheckPresence(d *schema.ResourceData, m interface{}) (string, if !argSet { return "", fmt.Errorf("Cannot locate compute by name %s if no resource group ID is set", computeName.(string)) } - + urlValues.Add("rgId", fmt.Sprintf("%d", rgId)) apiResp, err := controller.decortAPICall("POST", RgListComputesAPI, urlValues) if err != nil { diff --git a/decort/utility_general.go b/decort/utility_general.go deleted file mode 100644 index 4934d0c..0000000 --- a/decort/utility_general.go +++ /dev/null @@ -1,48 +0,0 @@ -/* -Copyright (c) 2019-2021 Digital Energy Cloud Solutions LLC. All Rights Reserved. -Author: Sergey Shubin, , - -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. -*/ - -/* -This file is part of Terraform (by Hashicorp) provider for Digital Energy Cloud Orchestration -Technology platfom. - -Visit https://github.com/rudecs/terraform-provider-decort for full source code package and updates. -*/ - -package decort - -import ( - - "strings" - -) - -func Jo2JSON(arg_str string) string { - // DECORT API historically returns response in the form of Python dictionary, which generally - // looks like JSON, but does not comply with JSON syntax. - // For Golang JSON Unmarshal to work properly we need to pre-process API response as follows: - ret_string := strings.Replace(string(arg_str), "u'", "\"", -1) - ret_string = strings.Replace(ret_string, "'", "\"", -1) - ret_string = strings.Replace(ret_string, ": False", ": false", -1) - ret_string = strings.Replace(ret_string, ": True", ": true", -1) - ret_string = strings.Replace(ret_string, "null", "\"\"", -1) - ret_string = strings.Replace(ret_string, "None", "\"\"", -1) - - // fix for incorrect handling of usage info - // ret_string = strings.Replace(ret_string, "<", "\"", -1) - // ret_string = strings.Replace(ret_string, ">", "\"", -1) - return ret_string -} diff --git a/decort/utility_grid.go b/decort/utility_grid.go index 2131cde..8500a5f 100644 --- a/decort/utility_grid.go +++ b/decort/utility_grid.go @@ -27,7 +27,6 @@ package decort import ( "encoding/json" "errors" - "fmt" "net/url" "strconv" @@ -44,7 +43,7 @@ func utilityGridCheckPresence(d *schema.ResourceData, m interface{}) (*Grid, err if gridId, ok := d.GetOk("grid_id"); ok { urlValues.Add("gridId", strconv.Itoa(gridId.(int))) } else { - return nil, errors.New(fmt.Sprintf("grid_id is required")) + return nil, errors.New("grid_id is required") } log.Debugf("utilityGridCheckPresence: load grid") diff --git a/decort/utility_pcidevice.go b/decort/utility_pcidevice.go index 2782ac1..5709ea0 100644 --- a/decort/utility_pcidevice.go +++ b/decort/utility_pcidevice.go @@ -43,21 +43,12 @@ func utilityPcideviceCheckPresence(d *schema.ResourceData, m interface{}) (*Pcid id, _ := strconv.Atoi(d.Id()) pcideviceId = id } - pcidevice := &Pcidevice{} - - flag := false for _, pd := range pcideviceList { if pd.ID == pcideviceId { - pcidevice = &pd - flag = true - break + return &pd, nil } } - if !flag { - return nil, nil - } - - return pcidevice, nil + return nil, nil } diff --git a/decort/utility_pcidevice_list.go b/decort/utility_pcidevice_list.go index 6767c7d..e4f7580 100644 --- a/decort/utility_pcidevice_list.go +++ b/decort/utility_pcidevice_list.go @@ -31,7 +31,7 @@ import ( "github.com/hashicorp/terraform-plugin-sdk/helper/schema" ) -func utilityPcideviceListCheckPresence(d *schema.ResourceData, m interface{}) (PcideviceList, error) { +func utilityPcideviceListCheckPresence(_ *schema.ResourceData, m interface{}) (PcideviceList, error) { pcideviceList := PcideviceList{} controller := m.(*ControllerCfg) urlValues := &url.Values{} diff --git a/decort/utility_rg.go b/decort/utility_rg.go index 371e678..c3c7d2b 100644 --- a/decort/utility_rg.go +++ b/decort/utility_rg.go @@ -36,38 +36,6 @@ import ( // "github.com/hashicorp/terraform-plugin-sdk/helper/validation" ) -func (ctrl *ControllerCfg) utilityResgroupConfigGet(rgid int) (*ResgroupGetResp, error) { - urlValues := &url.Values{} - urlValues.Add("rgId", fmt.Sprintf("%d", rgid)) - rgFacts, err := ctrl.decortAPICall("POST", ResgroupGetAPI, urlValues) - if err != nil { - return nil, err - } - - log.Debugf("utilityResgroupConfigGet: ready to unmarshal string %s", rgFacts) - model := &ResgroupGetResp{} - err = json.Unmarshal([]byte(rgFacts), model) - if err != nil { - return nil, err - } - - /* - ret := &ResgroupConfig{} - ret.AccountID = model.AccountID - ret.Location = model.Location - ret.Name = model.Name - ret.ID = rgid - ret.GridID = model.GridID - ret.ExtIP = model.ExtIP // legacy field for VDC - this will eventually become obsoleted by true Resource Groups - // Quota ResgroupQuotaConfig - // Network NetworkConfig - */ - log.Debugf("utilityResgroupConfigGet: account ID %d, GridID %d, Name %s", - model.AccountID, model.GridID, model.Name) - - return model, nil -} - // On success this function returns a string, as returned by API rg/get, which could be unmarshalled // into ResgroupGetResp structure func utilityResgroupCheckPresence(d *schema.ResourceData, m interface{}) (string, error) { @@ -104,7 +72,7 @@ func utilityResgroupCheckPresence(d *schema.ResourceData, m interface{}) (string } else { idSet = true } - + if idSet { // go straight for the RG by its ID log.Debugf("utilityResgroupCheckPresence: locating RG by its ID %d", theId) @@ -165,11 +133,3 @@ func utilityResgroupCheckPresence(d *schema.ResourceData, m interface{}) (string return "", fmt.Errorf("Cannot find RG name %s owned by account ID %d", rgName, validatedAccountId) } - -func utilityResgroupGetDefaultGridID() (interface{}, error) { - if DefaultGridID > 0 { - return fmt.Sprintf("%d", DefaultGridID), nil - } - - return "", fmt.Errorf("utilityResgroupGetDefaultGridID: invalid default Grid ID %d", DefaultGridID) - } diff --git a/decort/utility_vins.go b/decort/utility_vins.go index f64cc79..03a410c 100644 --- a/decort/utility_vins.go +++ b/decort/utility_vins.go @@ -35,28 +35,6 @@ import ( "github.com/hashicorp/terraform-plugin-sdk/helper/schema" ) -func (ctrl *ControllerCfg) utilityVinsConfigGet(vinsid int) (*VinsRecord, error) { - urlValues := &url.Values{} - urlValues.Add("vinsId", fmt.Sprintf("%d", vinsid)) - vinsFacts, err := ctrl.decortAPICall("POST", VinsGetAPI, urlValues) - if err != nil { - return nil, err - } - - log.Debugf("utilityVinsConfigGet: ready to unmarshal string %q", vinsFacts) - model := &VinsRecord{} - err = json.Unmarshal([]byte(vinsFacts), model) - if err != nil { - return nil, err - } - - log.Debugf("utilityVinsConfigGet: Name %d, account name:ID %s:%d, RG Name:ID %s:%d", - model.Name, model.AccountName, model.AccountID, - model.RgName, model.RgID) - - return model, nil -} - // On success this function returns a string, as returned by API vins/get, which could be unmarshalled // into VinsGetResp structure func utilityVinsCheckPresence(d *schema.ResourceData, m interface{}) (string, error) { @@ -129,7 +107,7 @@ func utilityVinsCheckPresence(d *schema.ResourceData, m interface{}) (string, er if err != nil { return "", err } - + // log.Debugf("%s", apiResp) // log.Debugf("utilityResgroupCheckPresence: ready to decode response body from %s", VinsSearchAPI) model := VinsSearchResp{} @@ -141,24 +119,24 @@ func utilityVinsCheckPresence(d *schema.ResourceData, m interface{}) (string, er log.Debugf("utilityVinsCheckPresence: traversing decoded Json of length %d", len(model)) for index, item := range model { if item.Name == vinsName.(string) { - if ( accountSet && item.AccountID != accountId.(int) ) || - ( rgSet && item.RgID != rgId.(int) ) { - // double check that account ID and Rg ID match, if set in the schema - continue + if (accountSet && item.AccountID != accountId.(int)) || + (rgSet && item.RgID != rgId.(int)) { + // double check that account ID and Rg ID match, if set in the schema + continue } log.Debugf("utilityVinsCheckPresence: match ViNS name %s / ID %d, account ID %d, RG ID %d at index %d", - item.Name, item.ID, item.AccountID, item.RgID, index) + item.Name, item.ID, item.AccountID, item.RgID, index) - // element returned by API vins/search does not contain all information we may need to + // element returned by API vins/search does not contain all information we may need to // manage ViNS, so we have to get detailed info by calling API vins/get rqValues := &url.Values{} - rqValues.Add("vinsId", fmt.Sprintf("%d",item.ID)) + rqValues.Add("vinsId", fmt.Sprintf("%d", item.ID)) vinsGetResp, err := controller.decortAPICall("POST", VinsGetAPI, rqValues) if err != nil { return "", err } - return vinsGetResp, nil + return vinsGetResp, nil } } From 545eac90dfaf654c079d2a4f8dfaf9923424ad92 Mon Sep 17 00:00:00 2001 From: kjubybot Date: Wed, 8 Jun 2022 15:55:16 +0300 Subject: [PATCH 29/51] refactoring; dropped some unused code; configured linters --- .golangci.yml | 2 +- decort/resource_account.go | 2 +- decort/ssh_subresource.go | 104 ------------------------------- decort/utility_extnet_default.go | 2 +- decort/utility_rg.go | 8 --- 5 files changed, 3 insertions(+), 115 deletions(-) delete mode 100644 decort/ssh_subresource.go diff --git a/.golangci.yml b/.golangci.yml index 49ad9be..808f9e1 100644 --- a/.golangci.yml +++ b/.golangci.yml @@ -11,7 +11,7 @@ linters: - gosec - ifshort - makezero - - nestif + #- nestif - disabled till better times - nilerr - prealloc - unconvert diff --git a/decort/resource_account.go b/decort/resource_account.go index e266560..66fc97c 100644 --- a/decort/resource_account.go +++ b/decort/resource_account.go @@ -428,7 +428,7 @@ func isChangedUser(els []interface{}, el interface{}) bool { elOldConv := elOld.(map[string]interface{}) elConv := el.(map[string]interface{}) if elOldConv["user_id"].(string) == elConv["user_id"].(string) && - (strings.ToUpper(elOldConv["access_type"].(string)) != strings.ToUpper(elConv["access_type"].(string)) || + (!strings.EqualFold(elOldConv["access_type"].(string), elConv["access_type"].(string)) || elOldConv["recursive_delete"].(bool) != elConv["recursive_delete"].(bool)) { return true } diff --git a/decort/ssh_subresource.go b/decort/ssh_subresource.go deleted file mode 100644 index 1ac97a4..0000000 --- a/decort/ssh_subresource.go +++ /dev/null @@ -1,104 +0,0 @@ -/* -Copyright (c) 2019-2021 Digital Energy Cloud Solutions LLC. All Rights Reserved. -Author: Sergey Shubin, , - -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. -*/ - -package decort - -import ( - "fmt" - - "github.com/hashicorp/terraform-plugin-sdk/helper/schema" - // "github.com/hashicorp/terraform-plugin-sdk/helper/validation" -) - -/* -func makeSshKeysConfig(arg_list []interface{}) (sshkeys []SshKeyConfig, count int) { - count = len(arg_list) - if count < 1 { - return nil, 0 - } - - sshkeys = make([]SshKeyConfig, count) - var subres_data map[string]interface{} - for index, value := range arg_list { - subres_data = value.(map[string]interface{}) - sshkeys[index].User = subres_data["user"].(string) - sshkeys[index].SshKey = subres_data["public_key"].(string) - sshkeys[index].UserShell = subres_data["shell"].(string) - } - - return sshkeys, count -} -*/ - -func makeSshKeysArgString(arg_list []interface{}) string { - // This function expects arg_list = data.Get("ssh_keys"), where "data" is a populated schema for Compute - // Resource (see func resourceCompute() definition) or Compute Data Source (see func dataSourceCompute()) - - // Prepare a string with username and public ssh key value in a format recognized by cloud-init utility. - // It is designed to be passed as "userdata" argument of virtual machine create API call. - // The following format is expected: - // '{"users": [{"ssh-authorized-keys": ["SSH_PUBCIC_KEY_VALUE"], "shell": "SHELL_VALUE", "name": "USERNAME_VALUE"}, {...}, ]}' - - /* - `%s\n - - name: %s\n - ssh-authorized-keys: - - %s\n - shell: /bin/bash` - */ - - if len(arg_list) < 1 { - return "" - } - - out := `{"users": [` - const UserdataTemplate = `%s{"ssh-authorized-keys": ["%s"], "shell": "%s", "name": "%s"}, ` - const out_suffix = `]}` - - for _, value := range arg_list { - subres_data := value.(map[string]interface{}) - - out = fmt.Sprintf(UserdataTemplate, out, subres_data["public_key"].(string), subres_data["shell"].(string), subres_data["user"].(string)) - } - out = fmt.Sprintf("%s %s", out, out_suffix) - return out -} - -func sshSubresourceSchemaMake() map[string]*schema.Schema { - rets := map[string]*schema.Schema{ - "user": { - Type: schema.TypeString, - Required: true, - Description: "Name of the guest OS user of a new compute, for which the following SSH key will be authorized.", - }, - - "public_key": { - Type: schema.TypeString, - Required: true, - Description: "Public SSH key to authorize to the specified guest OS user on the compute being created.", - }, - - "shell": { - Type: schema.TypeString, - Optional: true, - Default: "/bin/bash", - Description: "Guest user shell. This parameter is optional, default is /bin/bash.", - }, - } - - return rets -} diff --git a/decort/utility_extnet_default.go b/decort/utility_extnet_default.go index d07f306..a76b93c 100644 --- a/decort/utility_extnet_default.go +++ b/decort/utility_extnet_default.go @@ -32,7 +32,7 @@ import ( "github.com/hashicorp/terraform-plugin-sdk/helper/schema" ) -func utilityExtnetDefaultCheckPresence(d *schema.ResourceData, m interface{}) (string, error) { +func utilityExtnetDefaultCheckPresence(_ *schema.ResourceData, m interface{}) (string, error) { controller := m.(*ControllerCfg) urlValues := &url.Values{} diff --git a/decort/utility_rg.go b/decort/utility_rg.go index 803e4e4..118c898 100644 --- a/decort/utility_rg.go +++ b/decort/utility_rg.go @@ -129,11 +129,3 @@ func utilityResgroupCheckPresence(d *schema.ResourceData, m interface{}) (string return "", fmt.Errorf("Cannot find RG name %s owned by account ID %d", rgName, d.Get("account_id").(int)) } - -func utilityResgroupGetDefaultGridID() (interface{}, error) { - if DefaultGridID > 0 { - return fmt.Sprintf("%d", DefaultGridID), nil - } - - return "", fmt.Errorf("utilityResgroupGetDefaultGridID: invalid default Grid ID %d", DefaultGridID) -} From efe2b577b0240d0b1f99883c92a3fa7cb376a0b9 Mon Sep 17 00:00:00 2001 From: kjubybot Date: Thu, 9 Jun 2022 11:17:30 +0300 Subject: [PATCH 30/51] updated docs --- docs/data-sources/account.md | 111 +++++++++++- docs/data-sources/account_audits_list.md | 51 ++++++ docs/data-sources/account_computes_list.md | 66 +++++++ docs/data-sources/account_consumed_units.md | 44 +++++ .../account_consumed_units_by_type.md | 40 +++++ docs/data-sources/account_deleted_list.md | 63 +++++++ docs/data-sources/account_disks_list.md | 52 ++++++ docs/data-sources/account_flipgroups_list.md | 67 +++++++ docs/data-sources/account_list.md | 63 +++++++ docs/data-sources/account_reserved_units.md | 44 +++++ docs/data-sources/account_rg_list.md | 115 ++++++++++++ docs/data-sources/account_templates_list.md | 56 ++++++ docs/data-sources/account_vins_list.md | 63 +++++++ docs/data-sources/bservice.md | 90 ++++++++++ docs/data-sources/bservice_deleted_list.md | 68 ++++++++ docs/data-sources/bservice_group.md | 88 ++++++++++ docs/data-sources/bservice_list.md | 68 ++++++++ docs/data-sources/bservice_snapshot_list.md | 50 ++++++ docs/data-sources/disk_list.md | 105 +++++++++++ docs/data-sources/extnet.md | 98 +++++++++++ docs/data-sources/extnet_computes_list.md | 63 +++++++ docs/data-sources/extnet_default.md | 35 ++++ docs/data-sources/extnet_list.md | 48 +++++ docs/data-sources/pcidevice.md | 49 ++++++ docs/data-sources/pcidevice_list.md | 54 ++++++ docs/data-sources/rg_list.md | 94 ++++++++++ docs/data-sources/sep.md | 51 ++++++ docs/data-sources/sep_config.md | 39 +++++ docs/data-sources/sep_consumption.md | 69 ++++++++ docs/data-sources/sep_disk_list.md | 40 +++++ docs/data-sources/sep_list.md | 58 +++++++ docs/data-sources/sep_pool.md | 40 +++++ docs/data-sources/vgpu.md | 37 ++++ docs/data-sources/vins_list.md | 61 +++++++ docs/resources/account.md | 164 ++++++++++++++++++ docs/resources/bservice.md | 101 +++++++++++ docs/resources/bservice_group.md | 97 +++++++++++ docs/resources/disk.md | 8 +- docs/resources/pcidevice.md | 54 ++++++ docs/resources/sep.md | 69 ++++++++ docs/resources/sep_config.md | 50 ++++++ 41 files changed, 2676 insertions(+), 7 deletions(-) create mode 100644 docs/data-sources/account_audits_list.md create mode 100644 docs/data-sources/account_computes_list.md create mode 100644 docs/data-sources/account_consumed_units.md create mode 100644 docs/data-sources/account_consumed_units_by_type.md create mode 100644 docs/data-sources/account_deleted_list.md create mode 100644 docs/data-sources/account_disks_list.md create mode 100644 docs/data-sources/account_flipgroups_list.md create mode 100644 docs/data-sources/account_list.md create mode 100644 docs/data-sources/account_reserved_units.md create mode 100644 docs/data-sources/account_rg_list.md create mode 100644 docs/data-sources/account_templates_list.md create mode 100644 docs/data-sources/account_vins_list.md create mode 100644 docs/data-sources/bservice.md create mode 100644 docs/data-sources/bservice_deleted_list.md create mode 100644 docs/data-sources/bservice_group.md create mode 100644 docs/data-sources/bservice_list.md create mode 100644 docs/data-sources/bservice_snapshot_list.md create mode 100644 docs/data-sources/disk_list.md create mode 100644 docs/data-sources/extnet.md create mode 100644 docs/data-sources/extnet_computes_list.md create mode 100644 docs/data-sources/extnet_default.md create mode 100644 docs/data-sources/extnet_list.md create mode 100644 docs/data-sources/pcidevice.md create mode 100644 docs/data-sources/pcidevice_list.md create mode 100644 docs/data-sources/rg_list.md create mode 100644 docs/data-sources/sep.md create mode 100644 docs/data-sources/sep_config.md create mode 100644 docs/data-sources/sep_consumption.md create mode 100644 docs/data-sources/sep_disk_list.md create mode 100644 docs/data-sources/sep_list.md create mode 100644 docs/data-sources/sep_pool.md create mode 100644 docs/data-sources/vgpu.md create mode 100644 docs/data-sources/vins_list.md create mode 100644 docs/resources/account.md create mode 100644 docs/resources/bservice.md create mode 100644 docs/resources/bservice_group.md create mode 100644 docs/resources/pcidevice.md create mode 100644 docs/resources/sep.md create mode 100644 docs/resources/sep_config.md diff --git a/docs/data-sources/account.md b/docs/data-sources/account.md index f6b298f..958f041 100644 --- a/docs/data-sources/account.md +++ b/docs/data-sources/account.md @@ -15,16 +15,42 @@ description: |- ## Schema +### Required + +- **account_id** (Number) + ### Optional -- **account_id** (Number) Unique ID of the account. If account ID is specified, then account name is ignored. - **id** (String) The ID of this resource. -- **name** (String) Name of the account. Names are case sensitive and unique. - **timeouts** (Block, Optional) (see [below for nested schema](#nestedblock--timeouts)) ### Read-Only -- **status** (String) Current status of the account. +- **account_name** (String) +- **acl** (List of Object) (see [below for nested schema](#nestedatt--acl)) +- **ckey** (String) +- **company** (String) +- **companyurl** (String) +- **computes** (List of Object) (see [below for nested schema](#nestedatt--computes)) +- **created_by** (String) +- **created_time** (Number) +- **dc_location** (String) +- **deactivation_time** (Number) +- **deleted_by** (String) +- **deleted_time** (Number) +- **displayname** (String) +- **guid** (Number) +- **machines** (List of Object) (see [below for nested schema](#nestedatt--machines)) +- **meta** (List of String) +- **resource_limits** (List of Object) (see [below for nested schema](#nestedatt--resource_limits)) +- **resources** (List of Object) (see [below for nested schema](#nestedatt--resources)) +- **send_access_emails** (Boolean) +- **service_account** (Boolean) +- **status** (String) +- **updated_time** (Number) +- **version** (Number) +- **vins** (List of Number) +- **vinses** (Number) ### Nested Schema for `timeouts` @@ -35,3 +61,82 @@ Optional: - **read** (String) + +### Nested Schema for `acl` + +Read-Only: + +- **can_be_deleted** (Boolean) +- **explicit** (Boolean) +- **guid** (String) +- **right** (String) +- **status** (String) +- **type** (String) +- **user_group_id** (String) + + + +### Nested Schema for `computes` + +Read-Only: + +- **started** (Number) +- **stopped** (Number) + + + +### Nested Schema for `machines` + +Read-Only: + +- **halted** (Number) +- **running** (Number) + + + +### Nested Schema for `resource_limits` + +Read-Only: + +- **cu_c** (Number) +- **cu_d** (Number) +- **cu_i** (Number) +- **cu_m** (Number) +- **cu_np** (Number) +- **gpu_units** (Number) + + + +### Nested Schema for `resources` + +Read-Only: + +- **current** (List of Object) (see [below for nested schema](#nestedobjatt--resources--current)) +- **reserved** (List of Object) (see [below for nested schema](#nestedobjatt--resources--reserved)) + + +### Nested Schema for `resources.current` + +Read-Only: + +- **cpu** (Number) +- **disksize** (Number) +- **extips** (Number) +- **exttraffic** (Number) +- **gpu** (Number) +- **ram** (Number) + + + +### Nested Schema for `resources.reserved` + +Read-Only: + +- **cpu** (Number) +- **disksize** (Number) +- **extips** (Number) +- **exttraffic** (Number) +- **gpu** (Number) +- **ram** (Number) + + diff --git a/docs/data-sources/account_audits_list.md b/docs/data-sources/account_audits_list.md new file mode 100644 index 0000000..34353e7 --- /dev/null +++ b/docs/data-sources/account_audits_list.md @@ -0,0 +1,51 @@ +--- +# generated by https://github.com/hashicorp/terraform-plugin-docs +page_title: "decort_account_audits_list Data Source - terraform-provider-decort" +subcategory: "" +description: |- + +--- + +# decort_account_audits_list (Data Source) + + + + + + +## Schema + +### Required + +- **account_id** (Number) ID of the account + +### Optional + +- **id** (String) The ID of this resource. +- **timeouts** (Block, Optional) (see [below for nested schema](#nestedblock--timeouts)) + +### Read-Only + +- **items** (List of Object) Search Result (see [below for nested schema](#nestedatt--items)) + + +### Nested Schema for `timeouts` + +Optional: + +- **default** (String) +- **read** (String) + + + +### Nested Schema for `items` + +Read-Only: + +- **call** (String) +- **responsetime** (Number) +- **statuscode** (Number) +- **timestamp** (Number) +- **user** (String) + + diff --git a/docs/data-sources/account_computes_list.md b/docs/data-sources/account_computes_list.md new file mode 100644 index 0000000..963108a --- /dev/null +++ b/docs/data-sources/account_computes_list.md @@ -0,0 +1,66 @@ +--- +# generated by https://github.com/hashicorp/terraform-plugin-docs +page_title: "decort_account_computes_list Data Source - terraform-provider-decort" +subcategory: "" +description: |- + +--- + +# decort_account_computes_list (Data Source) + + + + + + +## Schema + +### Required + +- **account_id** (Number) ID of the account + +### Optional + +- **id** (String) The ID of this resource. +- **timeouts** (Block, Optional) (see [below for nested schema](#nestedblock--timeouts)) + +### Read-Only + +- **items** (List of Object) Search Result (see [below for nested schema](#nestedatt--items)) + + +### Nested Schema for `timeouts` + +Optional: + +- **default** (String) +- **read** (String) + + + +### Nested Schema for `items` + +Read-Only: + +- **account_id** (Number) +- **account_name** (String) +- **compute_id** (Number) +- **compute_name** (String) +- **cpus** (Number) +- **created_by** (String) +- **created_time** (Number) +- **deleted_by** (String) +- **deleted_time** (Number) +- **ram** (Number) +- **registered** (Boolean) +- **rg_id** (Number) +- **rg_name** (String) +- **status** (String) +- **tech_status** (String) +- **total_disks_size** (Number) +- **updated_by** (String) +- **updated_time** (Number) +- **user_managed** (Boolean) +- **vins_connected** (Number) + + diff --git a/docs/data-sources/account_consumed_units.md b/docs/data-sources/account_consumed_units.md new file mode 100644 index 0000000..84b0ac5 --- /dev/null +++ b/docs/data-sources/account_consumed_units.md @@ -0,0 +1,44 @@ +--- +# generated by https://github.com/hashicorp/terraform-plugin-docs +page_title: "decort_account_consumed_units Data Source - terraform-provider-decort" +subcategory: "" +description: |- + +--- + +# decort_account_consumed_units (Data Source) + + + + + + +## Schema + +### Required + +- **account_id** (Number) ID of the account + +### Optional + +- **id** (String) The ID of this resource. +- **timeouts** (Block, Optional) (see [below for nested schema](#nestedblock--timeouts)) + +### Read-Only + +- **cu_c** (Number) +- **cu_d** (Number) +- **cu_i** (Number) +- **cu_m** (Number) +- **cu_np** (Number) +- **gpu_units** (Number) + + +### Nested Schema for `timeouts` + +Optional: + +- **default** (String) +- **read** (String) + + diff --git a/docs/data-sources/account_consumed_units_by_type.md b/docs/data-sources/account_consumed_units_by_type.md new file mode 100644 index 0000000..8ad6632 --- /dev/null +++ b/docs/data-sources/account_consumed_units_by_type.md @@ -0,0 +1,40 @@ +--- +# generated by https://github.com/hashicorp/terraform-plugin-docs +page_title: "decort_account_consumed_units_by_type Data Source - terraform-provider-decort" +subcategory: "" +description: |- + +--- + +# decort_account_consumed_units_by_type (Data Source) + + + + + + +## Schema + +### Required + +- **account_id** (Number) ID of the account +- **cu_type** (String) cloud unit resource type + +### Optional + +- **id** (String) The ID of this resource. +- **timeouts** (Block, Optional) (see [below for nested schema](#nestedblock--timeouts)) + +### Read-Only + +- **cu_result** (Number) + + +### Nested Schema for `timeouts` + +Optional: + +- **default** (String) +- **read** (String) + + diff --git a/docs/data-sources/account_deleted_list.md b/docs/data-sources/account_deleted_list.md new file mode 100644 index 0000000..0a321c1 --- /dev/null +++ b/docs/data-sources/account_deleted_list.md @@ -0,0 +1,63 @@ +--- +# generated by https://github.com/hashicorp/terraform-plugin-docs +page_title: "decort_account_deleted_list Data Source - terraform-provider-decort" +subcategory: "" +description: |- + +--- + +# decort_account_deleted_list (Data Source) + + + + + + +## Schema + +### Optional + +- **id** (String) The ID of this resource. +- **page** (Number) Page number +- **size** (Number) Page size +- **timeouts** (Block, Optional) (see [below for nested schema](#nestedblock--timeouts)) + +### Read-Only + +- **items** (List of Object) (see [below for nested schema](#nestedatt--items)) + + +### Nested Schema for `timeouts` + +Optional: + +- **default** (String) +- **read** (String) + + + +### Nested Schema for `items` + +Read-Only: + +- **account_id** (Number) +- **account_name** (String) +- **acl** (List of Object) (see [below for nested schema](#nestedobjatt--items--acl)) +- **created_time** (Number) +- **deleted_time** (Number) +- **status** (String) +- **updated_time** (Number) + + +### Nested Schema for `items.acl` + +Read-Only: + +- **explicit** (Boolean) +- **guid** (String) +- **right** (String) +- **status** (String) +- **type** (String) +- **user_group_id** (String) + + diff --git a/docs/data-sources/account_disks_list.md b/docs/data-sources/account_disks_list.md new file mode 100644 index 0000000..ac8b5ae --- /dev/null +++ b/docs/data-sources/account_disks_list.md @@ -0,0 +1,52 @@ +--- +# generated by https://github.com/hashicorp/terraform-plugin-docs +page_title: "decort_account_disks_list Data Source - terraform-provider-decort" +subcategory: "" +description: |- + +--- + +# decort_account_disks_list (Data Source) + + + + + + +## Schema + +### Required + +- **account_id** (Number) ID of the account + +### Optional + +- **id** (String) The ID of this resource. +- **timeouts** (Block, Optional) (see [below for nested schema](#nestedblock--timeouts)) + +### Read-Only + +- **items** (List of Object) Search Result (see [below for nested schema](#nestedatt--items)) + + +### Nested Schema for `timeouts` + +Optional: + +- **default** (String) +- **read** (String) + + + +### Nested Schema for `items` + +Read-Only: + +- **disk_id** (Number) +- **disk_name** (String) +- **pool** (String) +- **sep_id** (Number) +- **size_max** (Number) +- **type** (String) + + diff --git a/docs/data-sources/account_flipgroups_list.md b/docs/data-sources/account_flipgroups_list.md new file mode 100644 index 0000000..e97a6d6 --- /dev/null +++ b/docs/data-sources/account_flipgroups_list.md @@ -0,0 +1,67 @@ +--- +# generated by https://github.com/hashicorp/terraform-plugin-docs +page_title: "decort_account_flipgroups_list Data Source - terraform-provider-decort" +subcategory: "" +description: |- + +--- + +# decort_account_flipgroups_list (Data Source) + + + + + + +## Schema + +### Required + +- **account_id** (Number) ID of the account + +### Optional + +- **id** (String) The ID of this resource. +- **timeouts** (Block, Optional) (see [below for nested schema](#nestedblock--timeouts)) + +### Read-Only + +- **items** (List of Object) Search Result (see [below for nested schema](#nestedatt--items)) + + +### Nested Schema for `timeouts` + +Optional: + +- **default** (String) +- **read** (String) + + + +### Nested Schema for `items` + +Read-Only: + +- **account_id** (Number) +- **client_type** (String) +- **conn_type** (String) +- **created_by** (String) +- **created_time** (Number) +- **default_gw** (String) +- **deleted_by** (String) +- **deleted_time** (Number) +- **desc** (String) +- **fg_id** (Number) +- **fg_name** (String) +- **gid** (Number) +- **guid** (Number) +- **ip** (String) +- **milestones** (Number) +- **net_id** (Number) +- **net_type** (String) +- **netmask** (Number) +- **status** (String) +- **updated_by** (String) +- **updated_time** (Number) + + diff --git a/docs/data-sources/account_list.md b/docs/data-sources/account_list.md new file mode 100644 index 0000000..de553c0 --- /dev/null +++ b/docs/data-sources/account_list.md @@ -0,0 +1,63 @@ +--- +# generated by https://github.com/hashicorp/terraform-plugin-docs +page_title: "decort_account_list Data Source - terraform-provider-decort" +subcategory: "" +description: |- + +--- + +# decort_account_list (Data Source) + + + + + + +## Schema + +### Optional + +- **id** (String) The ID of this resource. +- **page** (Number) Page number +- **size** (Number) Page size +- **timeouts** (Block, Optional) (see [below for nested schema](#nestedblock--timeouts)) + +### Read-Only + +- **items** (List of Object) (see [below for nested schema](#nestedatt--items)) + + +### Nested Schema for `timeouts` + +Optional: + +- **default** (String) +- **read** (String) + + + +### Nested Schema for `items` + +Read-Only: + +- **account_id** (Number) +- **account_name** (String) +- **acl** (List of Object) (see [below for nested schema](#nestedobjatt--items--acl)) +- **created_time** (Number) +- **deleted_time** (Number) +- **status** (String) +- **updated_time** (Number) + + +### Nested Schema for `items.acl` + +Read-Only: + +- **explicit** (Boolean) +- **guid** (String) +- **right** (String) +- **status** (String) +- **type** (String) +- **user_group_id** (String) + + diff --git a/docs/data-sources/account_reserved_units.md b/docs/data-sources/account_reserved_units.md new file mode 100644 index 0000000..26f3627 --- /dev/null +++ b/docs/data-sources/account_reserved_units.md @@ -0,0 +1,44 @@ +--- +# generated by https://github.com/hashicorp/terraform-plugin-docs +page_title: "decort_account_reserved_units Data Source - terraform-provider-decort" +subcategory: "" +description: |- + +--- + +# decort_account_reserved_units (Data Source) + + + + + + +## Schema + +### Required + +- **account_id** (Number) ID of the account + +### Optional + +- **id** (String) The ID of this resource. +- **timeouts** (Block, Optional) (see [below for nested schema](#nestedblock--timeouts)) + +### Read-Only + +- **cu_c** (Number) +- **cu_d** (Number) +- **cu_i** (Number) +- **cu_m** (Number) +- **cu_np** (Number) +- **gpu_units** (Number) + + +### Nested Schema for `timeouts` + +Optional: + +- **default** (String) +- **read** (String) + + diff --git a/docs/data-sources/account_rg_list.md b/docs/data-sources/account_rg_list.md new file mode 100644 index 0000000..7690a9d --- /dev/null +++ b/docs/data-sources/account_rg_list.md @@ -0,0 +1,115 @@ +--- +# generated by https://github.com/hashicorp/terraform-plugin-docs +page_title: "decort_account_rg_list Data Source - terraform-provider-decort" +subcategory: "" +description: |- + +--- + +# decort_account_rg_list (Data Source) + + + + + + +## Schema + +### Required + +- **account_id** (Number) ID of the account + +### Optional + +- **id** (String) The ID of this resource. +- **timeouts** (Block, Optional) (see [below for nested schema](#nestedblock--timeouts)) + +### Read-Only + +- **items** (List of Object) Search Result (see [below for nested schema](#nestedatt--items)) + + +### Nested Schema for `timeouts` + +Optional: + +- **default** (String) +- **read** (String) + + + +### Nested Schema for `items` + +Read-Only: + +- **computes** (List of Object) (see [below for nested schema](#nestedobjatt--items--computes)) +- **created_by** (String) +- **created_time** (Number) +- **deleted_by** (String) +- **deleted_time** (Number) +- **milestones** (Number) +- **resources** (List of Object) (see [below for nested schema](#nestedobjatt--items--resources)) +- **rg_id** (Number) +- **rg_name** (String) +- **status** (String) +- **updated_by** (String) +- **updated_time** (Number) +- **vinses** (Number) + + +### Nested Schema for `items.computes` + +Read-Only: + +- **started** (Number) +- **stopped** (Number) + + + +### Nested Schema for `items.resources` + +Read-Only: + +- **consumed** (List of Object) (see [below for nested schema](#nestedobjatt--items--resources--consumed)) +- **limits** (List of Object) (see [below for nested schema](#nestedobjatt--items--resources--limits)) +- **reserved** (List of Object) (see [below for nested schema](#nestedobjatt--items--resources--reserved)) + + +### Nested Schema for `items.resources.consumed` + +Read-Only: + +- **cpu** (Number) +- **disksize** (Number) +- **extips** (Number) +- **exttraffic** (Number) +- **gpu** (Number) +- **ram** (Number) + + + +### Nested Schema for `items.resources.limits` + +Read-Only: + +- **cpu** (Number) +- **disksize** (Number) +- **extips** (Number) +- **exttraffic** (Number) +- **gpu** (Number) +- **ram** (Number) + + + +### Nested Schema for `items.resources.reserved` + +Read-Only: + +- **cpu** (Number) +- **disksize** (Number) +- **extips** (Number) +- **exttraffic** (Number) +- **gpu** (Number) +- **ram** (Number) + + diff --git a/docs/data-sources/account_templates_list.md b/docs/data-sources/account_templates_list.md new file mode 100644 index 0000000..690a54d --- /dev/null +++ b/docs/data-sources/account_templates_list.md @@ -0,0 +1,56 @@ +--- +# generated by https://github.com/hashicorp/terraform-plugin-docs +page_title: "decort_account_templates_list Data Source - terraform-provider-decort" +subcategory: "" +description: |- + +--- + +# decort_account_templates_list (Data Source) + + + + + + +## Schema + +### Required + +- **account_id** (Number) ID of the account + +### Optional + +- **id** (String) The ID of this resource. +- **timeouts** (Block, Optional) (see [below for nested schema](#nestedblock--timeouts)) + +### Read-Only + +- **items** (List of Object) Search Result (see [below for nested schema](#nestedatt--items)) + + +### Nested Schema for `timeouts` + +Optional: + +- **default** (String) +- **read** (String) + + + +### Nested Schema for `items` + +Read-Only: + +- **account_id** (Number) +- **desc** (String) +- **public** (Boolean) +- **size** (Number) +- **status** (String) +- **template_id** (Number) +- **template_name** (String) +- **type** (String) +- **unc_path** (String) +- **username** (String) + + diff --git a/docs/data-sources/account_vins_list.md b/docs/data-sources/account_vins_list.md new file mode 100644 index 0000000..c574cda --- /dev/null +++ b/docs/data-sources/account_vins_list.md @@ -0,0 +1,63 @@ +--- +# generated by https://github.com/hashicorp/terraform-plugin-docs +page_title: "decort_account_vins_list Data Source - terraform-provider-decort" +subcategory: "" +description: |- + +--- + +# decort_account_vins_list (Data Source) + + + + + + +## Schema + +### Required + +- **account_id** (Number) ID of the account + +### Optional + +- **id** (String) The ID of this resource. +- **timeouts** (Block, Optional) (see [below for nested schema](#nestedblock--timeouts)) + +### Read-Only + +- **items** (List of Object) Search Result (see [below for nested schema](#nestedatt--items)) + + +### Nested Schema for `timeouts` + +Optional: + +- **default** (String) +- **read** (String) + + + +### Nested Schema for `items` + +Read-Only: + +- **account_id** (Number) +- **account_name** (String) +- **computes** (Number) +- **created_by** (String) +- **created_time** (Number) +- **deleted_by** (String) +- **deleted_time** (Number) +- **external_ip** (String) +- **network** (String) +- **pri_vnf_dev_id** (Number) +- **rg_id** (Number) +- **rg_name** (String) +- **status** (String) +- **updated_by** (String) +- **updated_time** (Number) +- **vin_id** (Number) +- **vin_name** (String) + + diff --git a/docs/data-sources/bservice.md b/docs/data-sources/bservice.md new file mode 100644 index 0000000..c581e67 --- /dev/null +++ b/docs/data-sources/bservice.md @@ -0,0 +1,90 @@ +--- +# generated by https://github.com/hashicorp/terraform-plugin-docs +page_title: "decort_bservice Data Source - terraform-provider-decort" +subcategory: "" +description: |- + +--- + +# decort_bservice (Data Source) + + + + + + +## Schema + +### Required + +- **service_id** (Number) + +### Optional + +- **id** (String) The ID of this resource. +- **timeouts** (Block, Optional) (see [below for nested schema](#nestedblock--timeouts)) + +### Read-Only + +- **account_id** (Number) +- **account_name** (String) +- **base_domain** (String) +- **computes** (List of Object) (see [below for nested schema](#nestedatt--computes)) +- **cpu_total** (Number) +- **created_by** (String) +- **created_time** (Number) +- **deleted_by** (String) +- **deleted_time** (Number) +- **disk_total** (String) +- **gid** (Number) +- **groups** (List of Number) +- **groups_name** (List of String) +- **guid** (Number) +- **milestones** (Number) +- **parent_srv_id** (Number) +- **parent_srv_type** (String) +- **ram_total** (Number) +- **rg_id** (Number) +- **rg_name** (String) +- **service_name** (String) +- **snapshots** (List of Object) (see [below for nested schema](#nestedatt--snapshots)) +- **ssh_key** (String) +- **ssh_user** (String) +- **status** (String) +- **tech_status** (String) +- **updated_by** (String) +- **updated_time** (Number) +- **user_managed** (Boolean) + + +### Nested Schema for `timeouts` + +Optional: + +- **default** (String) +- **read** (String) + + + +### Nested Schema for `computes` + +Read-Only: + +- **compgroup_id** (Number) +- **compgroup_name** (String) +- **compgroup_role** (String) +- **id** (Number) +- **name** (String) + + + +### Nested Schema for `snapshots` + +Read-Only: + +- **guid** (String) +- **label** (String) +- **timestamp** (Number) +- **valid** (Boolean) + + diff --git a/docs/data-sources/bservice_deleted_list.md b/docs/data-sources/bservice_deleted_list.md new file mode 100644 index 0000000..53c980e --- /dev/null +++ b/docs/data-sources/bservice_deleted_list.md @@ -0,0 +1,68 @@ +--- +# generated by https://github.com/hashicorp/terraform-plugin-docs +page_title: "decort_bservice_deleted_list Data Source - terraform-provider-decort" +subcategory: "" +description: |- + +--- + +# decort_bservice_deleted_list (Data Source) + + + + + + +## Schema + +### Optional + +- **account_id** (Number) ID of the account to query for BasicService instances +- **id** (String) The ID of this resource. +- **page** (Number) Page number +- **rg_id** (Number) ID of the resource group to query for BasicService instances +- **size** (Number) Page size +- **timeouts** (Block, Optional) (see [below for nested schema](#nestedblock--timeouts)) + +### Read-Only + +- **items** (List of Object) (see [below for nested schema](#nestedatt--items)) + + +### Nested Schema for `timeouts` + +Optional: + +- **default** (String) +- **read** (String) + + + +### Nested Schema for `items` + +Read-Only: + +- **account_id** (Number) +- **account_name** (String) +- **base_domain** (String) +- **created_by** (String) +- **created_time** (Number) +- **deleted_by** (String) +- **deleted_time** (Number) +- **gid** (Number) +- **groups** (List of Number) +- **guid** (Number) +- **parent_srv_id** (Number) +- **parent_srv_type** (String) +- **rg_id** (Number) +- **rg_name** (String) +- **service_id** (Number) +- **service_name** (String) +- **ssh_user** (String) +- **status** (String) +- **tech_status** (String) +- **updated_by** (String) +- **updated_time** (Number) +- **user_managed** (Boolean) + + diff --git a/docs/data-sources/bservice_group.md b/docs/data-sources/bservice_group.md new file mode 100644 index 0000000..8a90fa6 --- /dev/null +++ b/docs/data-sources/bservice_group.md @@ -0,0 +1,88 @@ +--- +# generated by https://github.com/hashicorp/terraform-plugin-docs +page_title: "decort_bservice_group Data Source - terraform-provider-decort" +subcategory: "" +description: |- + +--- + +# decort_bservice_group (Data Source) + + + + + + +## Schema + +### Required + +- **compgroup_id** (Number) +- **service_id** (Number) + +### Optional + +- **id** (String) The ID of this resource. +- **timeouts** (Block, Optional) (see [below for nested schema](#nestedblock--timeouts)) + +### Read-Only + +- **account_id** (Number) +- **account_name** (String) +- **compgroup_name** (String) +- **computes** (List of Object) (see [below for nested schema](#nestedatt--computes)) +- **consistency** (Boolean) +- **cpu** (Number) +- **created_by** (String) +- **created_time** (Number) +- **deleted_by** (String) +- **deleted_time** (Number) +- **disk** (Number) +- **driver** (String) +- **extnets** (List of Number) +- **gid** (Number) +- **guid** (Number) +- **image_id** (Number) +- **milestones** (Number) +- **parents** (List of Number) +- **ram** (Number) +- **rg_id** (Number) +- **rg_name** (String) +- **role** (String) +- **sep_id** (Number) +- **seq_no** (Number) +- **status** (String) +- **tech_status** (String) +- **timeout_start** (Number) +- **updated_by** (String) +- **updated_time** (Number) +- **vinses** (List of Number) + + +### Nested Schema for `timeouts` + +Optional: + +- **default** (String) +- **read** (String) + + + +### Nested Schema for `computes` + +Read-Only: + +- **id** (Number) +- **ip_addresses** (List of String) +- **name** (String) +- **os_users** (List of Object) (see [below for nested schema](#nestedobjatt--computes--os_users)) + + +### Nested Schema for `computes.os_users` + +Read-Only: + +- **login** (String) +- **password** (String) + + diff --git a/docs/data-sources/bservice_list.md b/docs/data-sources/bservice_list.md new file mode 100644 index 0000000..e464d39 --- /dev/null +++ b/docs/data-sources/bservice_list.md @@ -0,0 +1,68 @@ +--- +# generated by https://github.com/hashicorp/terraform-plugin-docs +page_title: "decort_bservice_list Data Source - terraform-provider-decort" +subcategory: "" +description: |- + +--- + +# decort_bservice_list (Data Source) + + + + + + +## Schema + +### Optional + +- **account_id** (Number) ID of the account to query for BasicService instances +- **id** (String) The ID of this resource. +- **page** (Number) Page number +- **rg_id** (Number) ID of the resource group to query for BasicService instances +- **size** (Number) Page size +- **timeouts** (Block, Optional) (see [below for nested schema](#nestedblock--timeouts)) + +### Read-Only + +- **items** (List of Object) (see [below for nested schema](#nestedatt--items)) + + +### Nested Schema for `timeouts` + +Optional: + +- **default** (String) +- **read** (String) + + + +### Nested Schema for `items` + +Read-Only: + +- **account_id** (Number) +- **account_name** (String) +- **base_domain** (String) +- **created_by** (String) +- **created_time** (Number) +- **deleted_by** (String) +- **deleted_time** (Number) +- **gid** (Number) +- **groups** (List of Number) +- **guid** (Number) +- **parent_srv_id** (Number) +- **parent_srv_type** (String) +- **rg_id** (Number) +- **rg_name** (String) +- **service_id** (Number) +- **service_name** (String) +- **ssh_user** (String) +- **status** (String) +- **tech_status** (String) +- **updated_by** (String) +- **updated_time** (Number) +- **user_managed** (Boolean) + + diff --git a/docs/data-sources/bservice_snapshot_list.md b/docs/data-sources/bservice_snapshot_list.md new file mode 100644 index 0000000..c75cd5f --- /dev/null +++ b/docs/data-sources/bservice_snapshot_list.md @@ -0,0 +1,50 @@ +--- +# generated by https://github.com/hashicorp/terraform-plugin-docs +page_title: "decort_bservice_snapshot_list Data Source - terraform-provider-decort" +subcategory: "" +description: |- + +--- + +# decort_bservice_snapshot_list (Data Source) + + + + + + +## Schema + +### Required + +- **service_id** (Number) ID of the BasicService instance + +### Optional + +- **id** (String) The ID of this resource. +- **timeouts** (Block, Optional) (see [below for nested schema](#nestedblock--timeouts)) + +### Read-Only + +- **items** (List of Object) (see [below for nested schema](#nestedatt--items)) + + +### Nested Schema for `timeouts` + +Optional: + +- **default** (String) +- **read** (String) + + + +### Nested Schema for `items` + +Read-Only: + +- **guid** (String) +- **label** (String) +- **timestamp** (Number) +- **valid** (Boolean) + + diff --git a/docs/data-sources/disk_list.md b/docs/data-sources/disk_list.md new file mode 100644 index 0000000..2095104 --- /dev/null +++ b/docs/data-sources/disk_list.md @@ -0,0 +1,105 @@ +--- +# generated by https://github.com/hashicorp/terraform-plugin-docs +page_title: "decort_disk_list Data Source - terraform-provider-decort" +subcategory: "" +description: |- + +--- + +# decort_disk_list (Data Source) + + + + + + +## Schema + +### Optional + +- **account_id** (Number) ID of the account the disks belong to +- **id** (String) The ID of this resource. +- **page** (Number) Page number +- **size** (Number) Page size +- **timeouts** (Block, Optional) (see [below for nested schema](#nestedblock--timeouts)) +- **type** (String) type of the disks + +### Read-Only + +- **items** (List of Object) (see [below for nested schema](#nestedatt--items)) + + +### Nested Schema for `timeouts` + +Optional: + +- **default** (String) +- **read** (String) + + + +### Nested Schema for `items` + +Read-Only: + +- **account_id** (Number) +- **account_name** (String) +- **acl** (String) +- **boot_partition** (Number) +- **compute_id** (Number) +- **compute_name** (String) +- **created_time** (Number) +- **deleted_time** (Number) +- **desc** (String) +- **destruction_time** (Number) +- **devicename** (String) +- **disk_id** (Number) +- **disk_path** (String) +- **gid** (Number) +- **guid** (Number) +- **image_id** (Number) +- **images** (List of String) +- **iotune** (String) +- **iqn** (String) +- **login** (String) +- **machine_id** (Number) +- **machine_name** (String) +- **milestones** (Number) +- **name** (String) +- **order** (Number) +- **params** (String) +- **parent_id** (Number) +- **passwd** (String) +- **pci_slot** (Number) +- **pool** (String) +- **purge_attempts** (Number) +- **purge_time** (Number) +- **reality_device_number** (Number) +- **reference_id** (String) +- **res_id** (String) +- **res_name** (String) +- **role** (String) +- **sep_id** (Number) +- **sep_type** (String) +- **size_max** (Number) +- **size_used** (Number) +- **snapshots** (List of Object) (see [below for nested schema](#nestedobjatt--items--snapshots)) +- **status** (String) +- **tech_status** (String) +- **type** (String) +- **update_by** (Number) +- **vmid** (Number) + + +### Nested Schema for `items.snapshots` + +Read-Only: + +- **guid** (String) +- **label** (String) +- **res_id** (String) +- **snap_set_guid** (String) +- **snap_set_time** (Number) +- **timestamp** (Number) + + diff --git a/docs/data-sources/extnet.md b/docs/data-sources/extnet.md new file mode 100644 index 0000000..dedadab --- /dev/null +++ b/docs/data-sources/extnet.md @@ -0,0 +1,98 @@ +--- +# generated by https://github.com/hashicorp/terraform-plugin-docs +page_title: "decort_extnet Data Source - terraform-provider-decort" +subcategory: "" +description: |- + +--- + +# decort_extnet (Data Source) + + + + + + +## Schema + +### Required + +- **net_id** (Number) + +### Optional + +- **id** (String) The ID of this resource. +- **timeouts** (Block, Optional) (see [below for nested schema](#nestedblock--timeouts)) + +### Read-Only + +- **check__ips** (List of String) +- **check_ips** (List of String) +- **ckey** (String) +- **default** (Boolean) +- **default_qos** (List of Object) (see [below for nested schema](#nestedatt--default_qos)) +- **desc** (String) +- **dns** (List of String) +- **excluded** (List of String) +- **free_ips** (Number) +- **gateway** (String) +- **gid** (Number) +- **guid** (Number) +- **ipcidr** (String) +- **meta** (List of String) meta +- **milestones** (Number) +- **net_name** (String) +- **network** (String) +- **network_id** (Number) +- **pre_reservations_num** (Number) +- **prefix** (Number) +- **pri_vnf_dev_id** (Number) +- **reservations** (List of Object) (see [below for nested schema](#nestedatt--reservations)) +- **shared_with** (List of Number) +- **status** (String) +- **vlan_id** (Number) +- **vnfs** (List of Object) (see [below for nested schema](#nestedatt--vnfs)) + + +### Nested Schema for `timeouts` + +Optional: + +- **default** (String) +- **read** (String) + + + +### Nested Schema for `default_qos` + +Read-Only: + +- **e_rate** (Number) +- **guid** (String) +- **in_burst** (Number) +- **in_rate** (Number) + + + +### Nested Schema for `reservations` + +Read-Only: + +- **client_type** (String) +- **desc** (String) +- **domainname** (String) +- **hostname** (String) +- **ip** (String) +- **mac** (String) +- **type** (String) +- **vm_id** (Number) + + + +### Nested Schema for `vnfs` + +Read-Only: + +- **dhcp** (Number) + + diff --git a/docs/data-sources/extnet_computes_list.md b/docs/data-sources/extnet_computes_list.md new file mode 100644 index 0000000..76d4161 --- /dev/null +++ b/docs/data-sources/extnet_computes_list.md @@ -0,0 +1,63 @@ +--- +# generated by https://github.com/hashicorp/terraform-plugin-docs +page_title: "decort_extnet_computes_list Data Source - terraform-provider-decort" +subcategory: "" +description: |- + +--- + +# decort_extnet_computes_list (Data Source) + + + + + + +## Schema + +### Required + +- **account_id** (Number) filter by account ID + +### Optional + +- **id** (String) The ID of this resource. +- **timeouts** (Block, Optional) (see [below for nested schema](#nestedblock--timeouts)) + +### Read-Only + +- **items** (List of Object) (see [below for nested schema](#nestedatt--items)) + + +### Nested Schema for `timeouts` + +Optional: + +- **default** (String) +- **read** (String) + + + +### Nested Schema for `items` + +Read-Only: + +- **account_id** (Number) +- **account_name** (String) +- **extnets** (List of Object) (see [below for nested schema](#nestedobjatt--items--extnets)) +- **id** (Number) +- **name** (String) +- **rg_id** (Number) +- **rg_name** (String) + + +### Nested Schema for `items.extnets` + +Read-Only: + +- **ipaddr** (String) +- **ipcidr** (String) +- **name** (String) +- **net_id** (Number) + + diff --git a/docs/data-sources/extnet_default.md b/docs/data-sources/extnet_default.md new file mode 100644 index 0000000..ca7ea93 --- /dev/null +++ b/docs/data-sources/extnet_default.md @@ -0,0 +1,35 @@ +--- +# generated by https://github.com/hashicorp/terraform-plugin-docs +page_title: "decort_extnet_default Data Source - terraform-provider-decort" +subcategory: "" +description: |- + +--- + +# decort_extnet_default (Data Source) + + + + + + +## Schema + +### Optional + +- **id** (String) The ID of this resource. +- **timeouts** (Block, Optional) (see [below for nested schema](#nestedblock--timeouts)) + +### Read-Only + +- **net_id** (Number) + + +### Nested Schema for `timeouts` + +Optional: + +- **default** (String) +- **read** (String) + + diff --git a/docs/data-sources/extnet_list.md b/docs/data-sources/extnet_list.md new file mode 100644 index 0000000..e0bc2c8 --- /dev/null +++ b/docs/data-sources/extnet_list.md @@ -0,0 +1,48 @@ +--- +# generated by https://github.com/hashicorp/terraform-plugin-docs +page_title: "decort_extnet_list Data Source - terraform-provider-decort" +subcategory: "" +description: |- + +--- + +# decort_extnet_list (Data Source) + + + + + + +## Schema + +### Optional + +- **account_id** (Number) filter by account ID +- **id** (String) The ID of this resource. +- **page** (Number) Page number +- **size** (Number) Page size +- **timeouts** (Block, Optional) (see [below for nested schema](#nestedblock--timeouts)) + +### Read-Only + +- **items** (List of Object) (see [below for nested schema](#nestedatt--items)) + + +### Nested Schema for `timeouts` + +Optional: + +- **default** (String) +- **read** (String) + + + +### Nested Schema for `items` + +Read-Only: + +- **ipcidr** (String) +- **name** (String) +- **net_id** (Number) + + diff --git a/docs/data-sources/pcidevice.md b/docs/data-sources/pcidevice.md new file mode 100644 index 0000000..ea44fb4 --- /dev/null +++ b/docs/data-sources/pcidevice.md @@ -0,0 +1,49 @@ +--- +# generated by https://github.com/hashicorp/terraform-plugin-docs +page_title: "decort_pcidevice Data Source - terraform-provider-decort" +subcategory: "" +description: |- + +--- + +# decort_pcidevice (Data Source) + + + + + + +## Schema + +### Required + +- **device_id** (Number) + +### Optional + +- **id** (String) The ID of this resource. +- **timeouts** (Block, Optional) (see [below for nested schema](#nestedblock--timeouts)) + +### Read-Only + +- **ckey** (String) +- **compute_id** (Number) +- **description** (String) +- **guid** (Number) +- **hw_path** (String) +- **meta** (List of String) +- **name** (String) +- **rg_id** (Number) +- **stack_id** (Number) +- **status** (String) +- **system_name** (String) + + +### Nested Schema for `timeouts` + +Optional: + +- **default** (String) +- **read** (String) + + diff --git a/docs/data-sources/pcidevice_list.md b/docs/data-sources/pcidevice_list.md new file mode 100644 index 0000000..ed65321 --- /dev/null +++ b/docs/data-sources/pcidevice_list.md @@ -0,0 +1,54 @@ +--- +# generated by https://github.com/hashicorp/terraform-plugin-docs +page_title: "decort_pcidevice_list Data Source - terraform-provider-decort" +subcategory: "" +description: |- + +--- + +# decort_pcidevice_list (Data Source) + + + + + + +## Schema + +### Optional + +- **id** (String) The ID of this resource. +- **timeouts** (Block, Optional) (see [below for nested schema](#nestedblock--timeouts)) + +### Read-Only + +- **items** (List of Object) pcidevice list (see [below for nested schema](#nestedatt--items)) + + +### Nested Schema for `timeouts` + +Optional: + +- **default** (String) +- **read** (String) + + + +### Nested Schema for `items` + +Read-Only: + +- **ckey** (String) +- **compute_id** (Number) +- **description** (String) +- **device_id** (Number) +- **guid** (Number) +- **hw_path** (String) +- **meta** (List of String) +- **name** (String) +- **rg_id** (Number) +- **stack_id** (Number) +- **status** (String) +- **system_name** (String) + + diff --git a/docs/data-sources/rg_list.md b/docs/data-sources/rg_list.md new file mode 100644 index 0000000..ddaea6d --- /dev/null +++ b/docs/data-sources/rg_list.md @@ -0,0 +1,94 @@ +--- +# generated by https://github.com/hashicorp/terraform-plugin-docs +page_title: "decort_rg_list Data Source - terraform-provider-decort" +subcategory: "" +description: |- + +--- + +# decort_rg_list (Data Source) + + + + + + +## Schema + +### Optional + +- **id** (String) The ID of this resource. +- **includedeleted** (Boolean) included deleted resource groups +- **page** (Number) Page number +- **size** (Number) Page size +- **timeouts** (Block, Optional) (see [below for nested schema](#nestedblock--timeouts)) + +### Read-Only + +- **items** (List of Object) (see [below for nested schema](#nestedatt--items)) + + +### Nested Schema for `timeouts` + +Optional: + +- **default** (String) +- **read** (String) + + + +### Nested Schema for `items` + +Read-Only: + +- **account_id** (Number) +- **account_name** (String) +- **acl** (List of Object) (see [below for nested schema](#nestedobjatt--items--acl)) +- **created_by** (String) +- **created_time** (Number) +- **def_net_id** (Number) +- **def_net_type** (String) +- **deleted_by** (String) +- **deleted_time** (Number) +- **desc** (String) +- **gid** (Number) +- **guid** (Number) +- **lock_status** (String) +- **milestones** (Number) +- **name** (String) +- **register_computes** (Boolean) +- **resource_limits** (List of Object) (see [below for nested schema](#nestedobjatt--items--resource_limits)) +- **rg_id** (Number) +- **secret** (String) +- **status** (String) +- **updated_by** (String) +- **updated_time** (Number) +- **vins** (List of Number) +- **vms** (List of Number) + + +### Nested Schema for `items.acl` + +Read-Only: + +- **explicit** (Boolean) +- **guid** (String) +- **right** (String) +- **status** (String) +- **type** (String) +- **user_group_id** (String) + + + +### Nested Schema for `items.resource_limits` + +Read-Only: + +- **cu_c** (Number) +- **cu_d** (Number) +- **cu_i** (Number) +- **cu_m** (Number) +- **cu_np** (Number) +- **gpu_units** (Number) + + diff --git a/docs/data-sources/sep.md b/docs/data-sources/sep.md new file mode 100644 index 0000000..85d29a2 --- /dev/null +++ b/docs/data-sources/sep.md @@ -0,0 +1,51 @@ +--- +# generated by https://github.com/hashicorp/terraform-plugin-docs +page_title: "decort_sep Data Source - terraform-provider-decort" +subcategory: "" +description: |- + +--- + +# decort_sep (Data Source) + + + + + + +## Schema + +### Required + +- **sep_id** (Number) sep type des id + +### Optional + +- **id** (String) The ID of this resource. +- **timeouts** (Block, Optional) (see [below for nested schema](#nestedblock--timeouts)) + +### Read-Only + +- **ckey** (String) +- **config** (String) +- **consumed_by** (List of Number) +- **desc** (String) +- **gid** (Number) +- **guid** (Number) +- **meta** (List of String) +- **milestones** (Number) +- **name** (String) +- **obj_status** (String) +- **provided_by** (List of Number) +- **tech_status** (String) +- **type** (String) + + +### Nested Schema for `timeouts` + +Optional: + +- **default** (String) +- **read** (String) + + diff --git a/docs/data-sources/sep_config.md b/docs/data-sources/sep_config.md new file mode 100644 index 0000000..a676bdf --- /dev/null +++ b/docs/data-sources/sep_config.md @@ -0,0 +1,39 @@ +--- +# generated by https://github.com/hashicorp/terraform-plugin-docs +page_title: "decort_sep_config Data Source - terraform-provider-decort" +subcategory: "" +description: |- + +--- + +# decort_sep_config (Data Source) + + + + + + +## Schema + +### Required + +- **sep_id** (Number) storage endpoint provider ID + +### Optional + +- **id** (String) The ID of this resource. +- **timeouts** (Block, Optional) (see [below for nested schema](#nestedblock--timeouts)) + +### Read-Only + +- **config** (String) sep config json string + + +### Nested Schema for `timeouts` + +Optional: + +- **default** (String) +- **read** (String) + + diff --git a/docs/data-sources/sep_consumption.md b/docs/data-sources/sep_consumption.md new file mode 100644 index 0000000..6929b1e --- /dev/null +++ b/docs/data-sources/sep_consumption.md @@ -0,0 +1,69 @@ +--- +# generated by https://github.com/hashicorp/terraform-plugin-docs +page_title: "decort_sep_consumption Data Source - terraform-provider-decort" +subcategory: "" +description: |- + +--- + +# decort_sep_consumption (Data Source) + + + + + + +## Schema + +### Required + +- **sep_id** (Number) sep id + +### Optional + +- **id** (String) The ID of this resource. +- **timeouts** (Block, Optional) (see [below for nested schema](#nestedblock--timeouts)) + +### Read-Only + +- **by_pool** (List of Object) consumption divided by pool (see [below for nested schema](#nestedatt--by_pool)) +- **total** (List of Object) total consumption (see [below for nested schema](#nestedatt--total)) +- **type** (String) sep type + + +### Nested Schema for `timeouts` + +Optional: + +- **default** (String) +- **read** (String) + + + +### Nested Schema for `by_pool` + +Read-Only: + +- **disk_count** (Number) +- **disk_usage** (Number) +- **name** (String) +- **snapshot_count** (Number) +- **snapshot_usage** (Number) +- **usage** (Number) +- **usage_limit** (Number) + + + +### Nested Schema for `total` + +Read-Only: + +- **capacity_limit** (Number) +- **disk_count** (Number) +- **disk_usage** (Number) +- **snapshot_count** (Number) +- **snapshot_usage** (Number) +- **usage** (Number) +- **usage_limit** (Number) + + diff --git a/docs/data-sources/sep_disk_list.md b/docs/data-sources/sep_disk_list.md new file mode 100644 index 0000000..827a141 --- /dev/null +++ b/docs/data-sources/sep_disk_list.md @@ -0,0 +1,40 @@ +--- +# generated by https://github.com/hashicorp/terraform-plugin-docs +page_title: "decort_sep_disk_list Data Source - terraform-provider-decort" +subcategory: "" +description: |- + +--- + +# decort_sep_disk_list (Data Source) + + + + + + +## Schema + +### Required + +- **sep_id** (Number) storage endpoint provider ID + +### Optional + +- **id** (String) The ID of this resource. +- **pool_name** (String) pool name +- **timeouts** (Block, Optional) (see [below for nested schema](#nestedblock--timeouts)) + +### Read-Only + +- **items** (List of Number) sep disk list + + +### Nested Schema for `timeouts` + +Optional: + +- **default** (String) +- **read** (String) + + diff --git a/docs/data-sources/sep_list.md b/docs/data-sources/sep_list.md new file mode 100644 index 0000000..caad0b2 --- /dev/null +++ b/docs/data-sources/sep_list.md @@ -0,0 +1,58 @@ +--- +# generated by https://github.com/hashicorp/terraform-plugin-docs +page_title: "decort_sep_list Data Source - terraform-provider-decort" +subcategory: "" +description: |- + +--- + +# decort_sep_list (Data Source) + + + + + + +## Schema + +### Optional + +- **id** (String) The ID of this resource. +- **page** (Number) page number +- **size** (Number) page size +- **timeouts** (Block, Optional) (see [below for nested schema](#nestedblock--timeouts)) + +### Read-Only + +- **items** (List of Object) sep list (see [below for nested schema](#nestedatt--items)) + + +### Nested Schema for `timeouts` + +Optional: + +- **default** (String) +- **read** (String) + + + +### Nested Schema for `items` + +Read-Only: + +- **ckey** (String) +- **config** (String) +- **consumed_by** (List of Number) +- **desc** (String) +- **gid** (Number) +- **guid** (Number) +- **meta** (List of String) +- **milestones** (Number) +- **name** (String) +- **obj_status** (String) +- **provided_by** (List of Number) +- **sep_id** (Number) +- **tech_status** (String) +- **type** (String) + + diff --git a/docs/data-sources/sep_pool.md b/docs/data-sources/sep_pool.md new file mode 100644 index 0000000..a70a366 --- /dev/null +++ b/docs/data-sources/sep_pool.md @@ -0,0 +1,40 @@ +--- +# generated by https://github.com/hashicorp/terraform-plugin-docs +page_title: "decort_sep_pool Data Source - terraform-provider-decort" +subcategory: "" +description: |- + +--- + +# decort_sep_pool (Data Source) + + + + + + +## Schema + +### Required + +- **pool_name** (String) pool name +- **sep_id** (Number) storage endpoint provider ID + +### Optional + +- **id** (String) The ID of this resource. +- **timeouts** (Block, Optional) (see [below for nested schema](#nestedblock--timeouts)) + +### Read-Only + +- **pool** (String) + + +### Nested Schema for `timeouts` + +Optional: + +- **default** (String) +- **read** (String) + + diff --git a/docs/data-sources/vgpu.md b/docs/data-sources/vgpu.md new file mode 100644 index 0000000..853bc45 --- /dev/null +++ b/docs/data-sources/vgpu.md @@ -0,0 +1,37 @@ +--- +# generated by https://github.com/hashicorp/terraform-plugin-docs +page_title: "decort_vgpu Data Source - terraform-provider-decort" +subcategory: "" +description: |- + +--- + +# decort_vgpu (Data Source) + + + + + + +## Schema + +### Required + +- **vgpu_id** (Number) + +### Optional + +- **id** (String) The ID of this resource. + +### Read-Only + +- **account_id** (Number) +- **mode** (String) +- **pgpu** (Number) +- **profile_id** (Number) +- **ram** (Number) +- **status** (String) +- **type** (String) +- **vm_id** (Number) + + diff --git a/docs/data-sources/vins_list.md b/docs/data-sources/vins_list.md new file mode 100644 index 0000000..4268af8 --- /dev/null +++ b/docs/data-sources/vins_list.md @@ -0,0 +1,61 @@ +--- +# generated by https://github.com/hashicorp/terraform-plugin-docs +page_title: "decort_vins_list Data Source - terraform-provider-decort" +subcategory: "" +description: |- + +--- + +# decort_vins_list (Data Source) + + + + + + +## Schema + +### Optional + +- **id** (String) The ID of this resource. +- **include_deleted** (Boolean) include deleted computes +- **page** (Number) Page number +- **size** (Number) Page size +- **timeouts** (Block, Optional) (see [below for nested schema](#nestedblock--timeouts)) + +### Read-Only + +- **items** (List of Object) (see [below for nested schema](#nestedatt--items)) + + +### Nested Schema for `timeouts` + +Optional: + +- **default** (String) +- **read** (String) + + + +### Nested Schema for `items` + +Read-Only: + +- **account_id** (Number) +- **account_name** (String) +- **created_by** (String) +- **created_time** (Number) +- **deleted_by** (String) +- **deleted_time** (Number) +- **external_ip** (String) +- **network** (String) +- **rg_id** (Number) +- **rg_name** (String) +- **status** (String) +- **updated_by** (String) +- **updated_time** (Number) +- **vins_id** (Number) +- **vins_name** (String) +- **vxlan_id** (Number) + + diff --git a/docs/resources/account.md b/docs/resources/account.md new file mode 100644 index 0000000..c0d5edd --- /dev/null +++ b/docs/resources/account.md @@ -0,0 +1,164 @@ +--- +# generated by https://github.com/hashicorp/terraform-plugin-docs +page_title: "decort_account Resource - terraform-provider-decort" +subcategory: "" +description: |- + +--- + +# decort_account (Resource) + + + + + + +## Schema + +### Required + +- **account_name** (String) account name +- **username** (String) username of owner the account + +### Optional + +- **account_id** (Number) +- **emailaddress** (String) email +- **enable** (Boolean) enable/disable account +- **id** (String) The ID of this resource. +- **permanently** (Boolean) whether to completely delete the account +- **resource_limits** (Block List, Max: 1) (see [below for nested schema](#nestedblock--resource_limits)) +- **restore** (Boolean) restore a deleted account +- **send_access_emails** (Boolean) if true send emails when a user is granted access to resources +- **timeouts** (Block, Optional) (see [below for nested schema](#nestedblock--timeouts)) +- **users** (Block List) (see [below for nested schema](#nestedblock--users)) + +### Read-Only + +- **acl** (List of Object) (see [below for nested schema](#nestedatt--acl)) +- **ckey** (String) +- **company** (String) +- **companyurl** (String) +- **computes** (List of Object) (see [below for nested schema](#nestedatt--computes)) +- **created_by** (String) +- **created_time** (Number) +- **dc_location** (String) +- **deactivation_time** (Number) +- **deleted_by** (String) +- **deleted_time** (Number) +- **displayname** (String) +- **guid** (Number) +- **machines** (List of Object) (see [below for nested schema](#nestedatt--machines)) +- **meta** (List of String) +- **resources** (List of Object) (see [below for nested schema](#nestedatt--resources)) +- **service_account** (Boolean) +- **status** (String) +- **updated_time** (Number) +- **version** (Number) +- **vins** (List of Number) +- **vinses** (Number) + + +### Nested Schema for `resource_limits` + +Optional: + +- **cu_c** (Number) +- **cu_d** (Number) +- **cu_i** (Number) +- **cu_m** (Number) +- **cu_np** (Number) +- **gpu_units** (Number) + + + +### Nested Schema for `timeouts` + +Optional: + +- **create** (String) +- **default** (String) +- **delete** (String) +- **read** (String) +- **update** (String) + + + +### Nested Schema for `users` + +Required: + +- **access_type** (String) +- **user_id** (String) + +Optional: + +- **recursive_delete** (Boolean) + + + +### Nested Schema for `acl` + +Read-Only: + +- **can_be_deleted** (Boolean) +- **explicit** (Boolean) +- **guid** (String) +- **right** (String) +- **status** (String) +- **type** (String) +- **user_group_id** (String) + + + +### Nested Schema for `computes` + +Read-Only: + +- **started** (Number) +- **stopped** (Number) + + + +### Nested Schema for `machines` + +Read-Only: + +- **halted** (Number) +- **running** (Number) + + + +### Nested Schema for `resources` + +Read-Only: + +- **current** (List of Object) (see [below for nested schema](#nestedobjatt--resources--current)) +- **reserved** (List of Object) (see [below for nested schema](#nestedobjatt--resources--reserved)) + + +### Nested Schema for `resources.current` + +Read-Only: + +- **cpu** (Number) +- **disksize** (Number) +- **extips** (Number) +- **exttraffic** (Number) +- **gpu** (Number) +- **ram** (Number) + + + +### Nested Schema for `resources.reserved` + +Read-Only: + +- **cpu** (Number) +- **disksize** (Number) +- **extips** (Number) +- **exttraffic** (Number) +- **gpu** (Number) +- **ram** (Number) + + diff --git a/docs/resources/bservice.md b/docs/resources/bservice.md new file mode 100644 index 0000000..0f52bf8 --- /dev/null +++ b/docs/resources/bservice.md @@ -0,0 +1,101 @@ +--- +# generated by https://github.com/hashicorp/terraform-plugin-docs +page_title: "decort_bservice Resource - terraform-provider-decort" +subcategory: "" +description: |- + +--- + +# decort_bservice (Resource) + + + + + + +## Schema + +### Required + +- **rg_id** (Number) ID of the Resource Group where this service will be placed +- **service_name** (String) Name of the service + +### Optional + +- **enable** (Boolean) if set to False, Basic service will be deleted to recycle bin. Otherwise destroyed immediately +- **id** (String) The ID of this resource. +- **permanently** (Boolean) if set to False, Basic service will be deleted to recycle bin. Otherwise destroyed immediately +- **restore** (Boolean) Restores BasicService instance +- **service_id** (Number) +- **snapshots** (Block List) (see [below for nested schema](#nestedblock--snapshots)) +- **ssh_key** (String) SSH key to deploy for the specified user. Same key will be deployed to all computes of the service. +- **ssh_user** (String) name of the user to deploy SSH key for. Pass empty string if no SSH key deployment is required +- **start** (Boolean) Start service. Starting a service technically means starting computes from all service groups according to group relations +- **timeouts** (Block, Optional) (see [below for nested schema](#nestedblock--timeouts)) + +### Read-Only + +- **account_id** (Number) +- **account_name** (String) +- **base_domain** (String) +- **computes** (List of Object) (see [below for nested schema](#nestedatt--computes)) +- **cpu_total** (Number) +- **created_by** (String) +- **created_time** (Number) +- **deleted_by** (String) +- **deleted_time** (Number) +- **disk_total** (String) +- **gid** (Number) +- **groups** (List of Number) +- **groups_name** (List of String) +- **guid** (Number) +- **milestones** (Number) +- **parent_srv_id** (Number) +- **parent_srv_type** (String) +- **ram_total** (Number) +- **rg_name** (String) +- **status** (String) +- **tech_status** (String) +- **updated_by** (String) +- **updated_time** (Number) +- **user_managed** (Boolean) + + +### Nested Schema for `snapshots` + +Optional: + +- **label** (String) +- **rollback** (Boolean) + +Read-Only: + +- **guid** (String) +- **timestamp** (Number) +- **valid** (Boolean) + + + +### Nested Schema for `timeouts` + +Optional: + +- **create** (String) +- **default** (String) +- **delete** (String) +- **read** (String) +- **update** (String) + + + +### Nested Schema for `computes` + +Read-Only: + +- **compgroup_id** (Number) +- **compgroup_name** (String) +- **compgroup_role** (String) +- **id** (Number) +- **name** (String) + + diff --git a/docs/resources/bservice_group.md b/docs/resources/bservice_group.md new file mode 100644 index 0000000..5ab6a26 --- /dev/null +++ b/docs/resources/bservice_group.md @@ -0,0 +1,97 @@ +--- +# generated by https://github.com/hashicorp/terraform-plugin-docs +page_title: "decort_bservice_group Resource - terraform-provider-decort" +subcategory: "" +description: |- + +--- + +# decort_bservice_group (Resource) + + + + + + +## Schema + +### Required + +- **comp_count** (Number) computes number. Defines how many computes must be there in the group +- **compgroup_name** (String) name of the Compute Group to add +- **cpu** (Number) compute CPU number. All computes in the group have the same CPU count +- **disk** (Number) compute boot disk size in GB +- **driver** (String) compute driver like a KVM_X86, KVM_PPC, etc. +- **image_id** (Number) OS image ID to create computes from +- **ram** (Number) compute RAM volume in MB. All computes in the group have the same RAM volume +- **service_id** (Number) ID of the Basic Service to add a group to + +### Optional + +- **compgroup_id** (Number) +- **extnets** (List of Number) list of external networks to connect computes to +- **force_stop** (Boolean) force stop Compute Group +- **force_update** (Boolean) force resize Compute Group +- **id** (String) The ID of this resource. +- **mode** (String) (RELATIVE;ABSOLUTE) either delta or absolute value of computes +- **parents** (List of Number) +- **remove_computes** (List of Number) +- **role** (String) group role tag. Can be empty string, does not have to be unique +- **start** (Boolean) Start the specified Compute Group within BasicService +- **timeout_start** (Number) time of Compute Group readiness +- **timeouts** (Block, Optional) (see [below for nested schema](#nestedblock--timeouts)) +- **vinses** (List of Number) list of ViNSes to connect computes to + +### Read-Only + +- **account_id** (Number) +- **account_name** (String) +- **computes** (List of Object) (see [below for nested schema](#nestedatt--computes)) +- **consistency** (Boolean) +- **created_by** (String) +- **created_time** (Number) +- **deleted_by** (String) +- **deleted_time** (Number) +- **gid** (Number) +- **guid** (Number) +- **milestones** (Number) +- **rg_id** (Number) +- **rg_name** (String) +- **sep_id** (Number) +- **seq_no** (Number) +- **status** (String) +- **tech_status** (String) +- **updated_by** (String) +- **updated_time** (Number) + + +### Nested Schema for `timeouts` + +Optional: + +- **create** (String) +- **default** (String) +- **delete** (String) +- **read** (String) +- **update** (String) + + + +### Nested Schema for `computes` + +Read-Only: + +- **id** (Number) +- **ip_addresses** (List of String) +- **name** (String) +- **os_users** (List of Object) (see [below for nested schema](#nestedobjatt--computes--os_users)) + + +### Nested Schema for `computes.os_users` + +Read-Only: + +- **login** (String) +- **password** (String) + + diff --git a/docs/resources/disk.md b/docs/resources/disk.md index 1d1a5dd..b19e57f 100644 --- a/docs/resources/disk.md +++ b/docs/resources/disk.md @@ -17,17 +17,17 @@ description: |- ### Required -- **pool** (String) Pool where this disk is located. Cannot be changed for existing disk. -- **sep_id** (Number) Storage end-point provider serving this disk. Cannot be changed for existing disk. +- **account_id** (Number) ID of the account this disk belongs to. +- **name** (String) Name of this disk. NOTE: disk names are NOT unique within an account. If disk ID is specified, disk name is ignored. - **size** (Number) Size of the disk in GB. Note, that existing disks can only be grown in size. ### Optional -- **account_id** (Number) ID of the account this disk belongs to. - **description** (String) Optional user-defined text description of this disk. - **disk_id** (Number) ID of the disk to get. If disk ID is specified, then disk name and account ID are ignored. - **id** (String) The ID of this resource. -- **name** (String) Name of this disk. NOTE: disk names are NOT unique within an account. If disk ID is specified, disk name is ignored. +- **pool** (String) Pool where this disk is located. Cannot be changed for existing disk. +- **sep_id** (Number) Storage end-point provider serving this disk. Cannot be changed for existing disk. - **timeouts** (Block, Optional) (see [below for nested schema](#nestedblock--timeouts)) ### Read-Only diff --git a/docs/resources/pcidevice.md b/docs/resources/pcidevice.md new file mode 100644 index 0000000..a4e3f86 --- /dev/null +++ b/docs/resources/pcidevice.md @@ -0,0 +1,54 @@ +--- +# generated by https://github.com/hashicorp/terraform-plugin-docs +page_title: "decort_pcidevice Resource - terraform-provider-decort" +subcategory: "" +description: |- + +--- + +# decort_pcidevice (Resource) + + + + + + +## Schema + +### Required + +- **hw_path** (String) PCI address of the device +- **name** (String) Name of Device +- **rg_id** (Number) Resource GROUP +- **stack_id** (Number) stackId + +### Optional + +- **description** (String) description, just for information +- **device_id** (Number) +- **enable** (Boolean) Enable pci device +- **force** (Boolean) Force delete +- **id** (String) The ID of this resource. +- **timeouts** (Block, Optional) (see [below for nested schema](#nestedblock--timeouts)) + +### Read-Only + +- **ckey** (String) +- **compute_id** (Number) +- **guid** (Number) +- **meta** (List of String) +- **status** (String) +- **system_name** (String) + + +### Nested Schema for `timeouts` + +Optional: + +- **create** (String) +- **default** (String) +- **delete** (String) +- **read** (String) +- **update** (String) + + diff --git a/docs/resources/sep.md b/docs/resources/sep.md new file mode 100644 index 0000000..7180b28 --- /dev/null +++ b/docs/resources/sep.md @@ -0,0 +1,69 @@ +--- +# generated by https://github.com/hashicorp/terraform-plugin-docs +page_title: "decort_sep Resource - terraform-provider-decort" +subcategory: "" +description: |- + +--- + +# decort_sep (Resource) + + + + + + +## Schema + +### Required + +- **gid** (Number) grid (platform) ID +- **name** (String) SEP name +- **type** (String) type of storage + +### Optional + +- **clear_physically** (Boolean) clear disks and images physically +- **config** (String) sep config string +- **consumed_by** (List of Number) list of consumer nodes IDs +- **decommission** (Boolean) unlink everything that exists from SEP +- **desc** (String) sep description +- **enable** (Boolean) enable SEP after creation +- **field_edit** (Block List, Max: 1) (see [below for nested schema](#nestedblock--field_edit)) +- **id** (String) The ID of this resource. +- **provided_by** (List of Number) list of provider nodes IDs +- **sep_id** (Number) sep type des id +- **timeouts** (Block, Optional) (see [below for nested schema](#nestedblock--timeouts)) +- **upd_capacity_limit** (Boolean) Update SEP capacity limit + +### Read-Only + +- **ckey** (String) +- **guid** (Number) +- **meta** (List of String) +- **milestones** (Number) +- **obj_status** (String) +- **tech_status** (String) + + +### Nested Schema for `field_edit` + +Required: + +- **field_name** (String) +- **field_type** (String) +- **field_value** (String) + + + +### Nested Schema for `timeouts` + +Optional: + +- **create** (String) +- **default** (String) +- **delete** (String) +- **read** (String) +- **update** (String) + + diff --git a/docs/resources/sep_config.md b/docs/resources/sep_config.md new file mode 100644 index 0000000..32ec3ca --- /dev/null +++ b/docs/resources/sep_config.md @@ -0,0 +1,50 @@ +--- +# generated by https://github.com/hashicorp/terraform-plugin-docs +page_title: "decort_sep_config Resource - terraform-provider-decort" +subcategory: "" +description: |- + +--- + +# decort_sep_config (Resource) + + + + + + +## Schema + +### Required + +- **sep_id** (Number) + +### Optional + +- **config** (String) +- **field_edit** (Block List, Max: 1) (see [below for nested schema](#nestedblock--field_edit)) +- **id** (String) The ID of this resource. +- **timeouts** (Block, Optional) (see [below for nested schema](#nestedblock--timeouts)) + + +### Nested Schema for `field_edit` + +Required: + +- **field_name** (String) +- **field_type** (String) +- **field_value** (String) + + + +### Nested Schema for `timeouts` + +Optional: + +- **create** (String) +- **default** (String) +- **delete** (String) +- **read** (String) +- **update** (String) + + From 945e6e08b0248f677bd9ae7f555b8bf87b771570 Mon Sep 17 00:00:00 2001 From: stSolo Date: Thu, 9 Jun 2022 17:47:25 +0300 Subject: [PATCH 31/51] Update list of contents --- samples/README.md | 2 ++ 1 file changed, 2 insertions(+) diff --git a/samples/README.md b/samples/README.md index 1e8d2a4..1797fa0 100644 --- a/samples/README.md +++ b/samples/README.md @@ -33,6 +33,8 @@ - account_templates_list - account_deleted_list - bservice_list + - bservice_snapshot_list + - bservice_deleted_list - bservice - bservice_group - extnet_default From 4b4efec196ba2f1bab2e466d5a64dc49a9a7f219 Mon Sep 17 00:00:00 2001 From: kjubybot Date: Fri, 10 Jun 2022 11:53:28 +0300 Subject: [PATCH 32/51] updated changelog; release ready --- .github/workflows/release.yml | 2 +- CHANGELOG.md | 43 ++++++++++++++++++++++++----------- 2 files changed, 31 insertions(+), 14 deletions(-) diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml index 2a8f3ea..2acce9e 100644 --- a/.github/workflows/release.yml +++ b/.github/workflows/release.yml @@ -1,4 +1,4 @@ -name: Release to registry +name: Release on: push: tags: diff --git a/CHANGELOG.md b/CHANGELOG.md index faf455d..06aeaff 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,18 +1,35 @@ ### Bug fixes -- resgroup recreation if quotas unspecified +- changing boot\_disk\_size in kvmvm +- downsizing CPU and RAM in kvmvm +- pfw recreation if public\_port\_end unspecified ### New datasources -- vgpu -- pcidevice\_list -- pcidevice -- sep -- sep\_list -- sep\_disk\_list -- sep\_config -- sep\_pool -- sep\_consumption +- disk\_list +- rg\_list +- account\_list +- account\_computes\_list +- account\_disks\_list +- account\_vins\_list +- account\_audits\_list +- account +- account\_rg\_list +- account\_counsumed\_units +- account\_counsumed\_units\_by\_type +- account\_reserved\_units +- account\_templates\_list +- account\_deleted\_list +- bservice\_list +- bservice\_snapshot\_list +- bservice\_deleted\_list +- bservice +- bservice\_group +- extnet\_default +- extnet\_list +- extnet +- extnet\_computes\_list +- vins\_list ### New resources -- pcidevice -- sep -- sep\_config +- account +- bservice +- bservice\_group From 42c4f2e505bbc964a3e6c58af8c9b749917f4d7c Mon Sep 17 00:00:00 2001 From: Pyotr Krutov Date: Sun, 26 Jun 2022 13:28:11 +0300 Subject: [PATCH 33/51] disabled controller client timeout --- decort/controller.go | 5 +---- 1 file changed, 1 insertion(+), 4 deletions(-) diff --git a/decort/controller.go b/decort/controller.go index 25e27ea..e24220b 100644 --- a/decort/controller.go +++ b/decort/controller.go @@ -140,12 +140,9 @@ func ControllerConfigure(d *schema.ResourceData) (*ControllerCfg, error) { transCfg := &http.Transport{TLSClientConfig: &tls.Config{InsecureSkipVerify: true}} //nolint:gosec ret_config.cc_client = &http.Client{ Transport: transCfg, - Timeout: Timeout180s, } } else { - ret_config.cc_client = &http.Client{ - Timeout: Timeout180s, // time.Second * 30, - } + ret_config.cc_client = &http.Client{} } switch ret_config.auth_mode_code { From b599e244e84b835355a4732815efb691a32fa58b Mon Sep 17 00:00:00 2001 From: Pyotr Krutov Date: Mon, 27 Jun 2022 10:23:01 +0300 Subject: [PATCH 34/51] made error message after HTTP 500 retry more informative --- decort/controller.go | 10 ++++++---- 1 file changed, 6 insertions(+), 4 deletions(-) diff --git a/decort/controller.go b/decort/controller.go index 25e27ea..27bd20f 100644 --- a/decort/controller.go +++ b/decort/controller.go @@ -27,7 +27,6 @@ package decort import ( "bytes" "crypto/tls" - "errors" "fmt" "io/ioutil" "net/http" @@ -379,13 +378,15 @@ func (config *ControllerCfg) decortAPICall(method string, api_name string, url_v req.Header.Set("Authorization", fmt.Sprintf("bearer %s", config.jwt)) } + var resp *http.Response + var body []byte for i := 0; i < 5; i++ { - resp, err := config.cc_client.Do(req) + resp, err = config.cc_client.Do(req) if err != nil { return "", err } - body, err := ioutil.ReadAll(resp.Body) + body, err = ioutil.ReadAll(resp.Body) if err != nil { return "", err } @@ -405,5 +406,6 @@ func (config *ControllerCfg) decortAPICall(method string, api_name string, url_v } } - return "", errors.New("number of retries exceeded") + return "", fmt.Errorf("decortAPICall: unexpected status code %d when calling API %q with request Body %q. Respone:\n%s", + resp.StatusCode, req.URL, params_str, body) } From 71aff5fa32b1f83abdb7d50fd1ce54586e011cf7 Mon Sep 17 00:00:00 2001 From: Pyotr Krutov Date: Mon, 27 Jun 2022 11:06:03 +0300 Subject: [PATCH 35/51] updated changelog --- CHANGELOG.md | 2 ++ 1 file changed, 2 insertions(+) diff --git a/CHANGELOG.md b/CHANGELOG.md index 06aeaff..88fa8aa 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,6 +2,8 @@ - changing boot\_disk\_size in kvmvm - downsizing CPU and RAM in kvmvm - pfw recreation if public\_port\_end unspecified +- uninformative error message when retrying on 500 +- hardcoded 3 minute timeout ### New datasources - disk\_list From 3613bbea28c9739ec5cdbeb1a4ddeb0678e12823 Mon Sep 17 00:00:00 2001 From: stSolo Date: Wed, 29 Jun 2022 11:34:14 +0300 Subject: [PATCH 36/51] Migrate to sdkv2 and project structure refactoring --- .gitignore | 1 + Makefile | 4 +- main.go => cmd/decort/main.go | 16 +- decort/data_source_account_deleted_list.go | 58 - decort/data_source_bservice_deleted_list.go | 58 - decort/models_api.go | 1486 ----------------- decort/provider.go | 196 --- go.mod | 2 +- go.sum | 87 + internal/constants/api.go | 26 + {decort => internal/constants}/constants.go | 27 +- internal/constants/timeouts.go | 28 + {decort => internal/controller}/controller.go | 22 +- internal/flattens/meta.go | 41 + internal/location/api.go | 22 + .../location/location.go | 124 +- internal/location/models.go | 30 + internal/provider/data_sources_map.go | 87 + internal/provider/provider.go | 134 ++ internal/provider/resource_map.go | 58 + internal/service/cloudapi/account/api.go | 55 + .../cloudapi/account}/data_source_account.go | 54 +- .../data_source_account_audits_list.go | 35 +- .../data_source_account_computes_list.go | 35 +- .../data_source_account_consumed_units.go | 35 +- ...a_source_account_consumed_units_by_type.go | 35 +- .../data_source_account_deleted_list.go | 69 + .../data_source_account_disks_list.go | 36 +- .../data_source_account_flipgroups_list.go | 35 +- .../account}/data_source_account_list.go | 51 +- .../data_source_account_reserved_units.go | 35 +- .../account}/data_source_account_rg_list.go | 35 +- .../data_source_account_templates_list.go | 35 +- .../account}/data_source_account_vins_list.go | 35 +- internal/service/cloudapi/account/models.go | 260 +++ .../cloudapi/account}/resource_account.go | 123 +- .../cloudapi/account}/utility_account.go | 24 +- .../account}/utility_account_audits_list.go | 24 +- .../account}/utility_account_computes_list.go | 24 +- .../utility_account_consumed_units.go | 24 +- .../utility_account_consumed_units_by_type.go | 24 +- .../account}/utility_account_deleted_list.go | 24 +- .../account}/utility_account_disks_list.go | 24 +- .../account}/utility_account_flip_groups.go | 24 +- .../cloudapi/account}/utility_account_list.go | 24 +- .../utility_account_reserved_units.go | 24 +- .../account}/utility_account_rg_list.go | 24 +- .../utility_account_templates_list.go | 24 +- .../account}/utility_account_vins_list.go | 24 +- internal/service/cloudapi/bservice/api.go | 59 + .../bservice}/data_source_bservice.go | 35 +- .../data_source_bservice_deleted_list.go | 69 + .../bservice}/data_source_bservice_group.go | 35 +- .../bservice}/data_source_bservice_list.go | 35 +- .../data_source_bservice_snapshot_list.go | 35 +- internal/service/cloudapi/bservice/models.go | 144 ++ .../cloudapi/bservice}/resource_bservice.go | 112 +- .../bservice}/resource_bservice_group.go | 122 +- .../utility_bservicce_deleted_list.go | 24 +- .../cloudapi/bservice}/utility_bservice.go | 24 +- .../bservice}/utility_bservice_group.go | 24 +- .../bservice}/utility_bservice_list.go | 24 +- .../utility_bservice_snapshot_list.go | 24 +- internal/service/cloudapi/disks/api.go | 39 + .../cloudapi/disks}/data_source_disk.go | 88 +- .../cloudapi/disks}/data_source_disk_list.go | 36 +- internal/service/cloudapi/disks/models.go | 95 ++ .../service/cloudapi/disks}/resource_disk.go | 101 +- .../service/cloudapi/disks}/utility_disk.go | 28 +- .../cloudapi/disks}/utility_disk_list.go | 24 +- internal/service/cloudapi/extnet/api.go | 37 + .../cloudapi/extnet}/data_source_extnet.go | 38 +- .../data_source_extnet_computes_list.go | 35 +- .../extnet}/data_source_extnet_default.go | 36 +- .../extnet}/data_source_extnet_list.go | 35 +- internal/service/cloudapi/extnet/models.go | 111 ++ .../cloudapi/extnet}/utility_extnet.go | 24 +- .../extnet}/utility_extnet_computes_list.go | 24 +- .../extnet}/utility_extnet_default.go | 24 +- .../cloudapi/extnet}/utility_extnet_list.go | 24 +- internal/service/cloudapi/k8s/api.go | 49 + internal/service/cloudapi/k8s/models.go | 131 ++ .../service/cloudapi/k8s}/node_subresource.go | 19 +- .../service/cloudapi/k8s}/resource_k8s.go | 113 +- .../service/cloudapi/k8s}/resource_k8s_wg.go | 81 +- .../service/cloudapi/k8s}/utility_k8s.go | 24 +- .../service/cloudapi/k8s}/utility_k8s_wg.go | 24 +- internal/service/cloudapi/kvmvm/api.go | 46 + .../cloudapi/kvmvm}/data_source_compute.go | 41 +- internal/service/cloudapi/kvmvm/models.go | 190 +++ .../cloudapi/kvmvm}/network_subresource.go | 32 +- .../cloudapi/kvmvm}/osusers_subresource.go | 23 +- .../cloudapi/kvmvm}/resource_compute.go | 147 +- .../cloudapi/kvmvm}/utility_compute.go | 51 +- internal/service/cloudapi/pfw/api.go | 36 + internal/service/cloudapi/pfw/models.go | 45 + .../service/cloudapi/pfw}/resource_pfw.go | 71 +- .../service/cloudapi/pfw}/utility_pfw.go | 24 +- internal/service/cloudapi/rg/api.go | 39 + .../service/cloudapi/rg}/data_source_rg.go | 83 +- .../cloudapi/rg}/data_source_rg_list.go | 35 +- internal/service/cloudapi/rg/models.go | 149 ++ .../service/cloudapi/rg}/quota_subresource.go | 27 +- .../service/cloudapi/rg}/resource_rg.go | 103 +- .../service/cloudapi/rg}/utility_rg.go | 31 +- .../service/cloudapi/rg}/utility_rg_list.go | 24 +- internal/service/cloudapi/snapshot/api.go | 37 + .../snapshot}/data_source_snapshot_list.go | 35 +- internal/service/cloudapi/snapshot/models.go | 41 + .../cloudapi/snapshot}/resource_snapshot.go | 100 +- .../cloudapi/snapshot}/utility_snapshot.go | 19 +- .../snapshot}/utility_snapshot_list.go | 26 +- internal/service/cloudapi/vgpu/api.go | 34 + .../cloudapi/vgpu}/data_source_vgpu.go | 29 +- internal/service/cloudapi/vgpu/models.go | 44 + .../service/cloudapi/vgpu}/utility_vgpu.go | 24 +- internal/service/cloudapi/vins/api.go | 44 + .../cloudapi/vins}/data_source_vins.go | 42 +- .../cloudapi/vins}/data_source_vins_list.go | 35 +- internal/service/cloudapi/vins/models.go | 94 ++ .../service/cloudapi/vins}/resource_vins.go | 97 +- .../service/cloudapi/vins}/utility_vins.go | 30 +- .../cloudapi/vins}/utility_vins_list.go | 24 +- internal/service/cloudbroker/grid/api.go | 35 + .../cloudbroker/grid}/data_source_grid.go | 34 +- .../grid}/data_source_grid_list.go | 35 +- internal/service/cloudbroker/grid/models.go | 43 + .../service/cloudbroker/grid}/utility_grid.go | 24 +- .../cloudbroker/grid}/utility_grid_list.go | 24 +- internal/service/cloudbroker/image/api.go | 52 + .../cloudbroker/image}/data_source_image.go | 37 +- .../image}/data_source_image_list.go | 35 +- .../image}/data_source_image_list_stacks.go | 35 +- internal/service/cloudbroker/image/models.go | 101 ++ .../image}/resource_cdrom_image.go | 120 +- .../image}/resource_delete_images.go | 53 +- .../cloudbroker/image}/resource_image.go | 241 +-- .../image}/resource_virtual_image.go | 111 +- .../cloudbroker/image}/utility_image.go | 24 +- .../cloudbroker/image}/utility_image_list.go | 24 +- .../image}/utility_image_list_stacks.go | 24 +- internal/service/cloudbroker/pcidevice/api.go | 38 + .../pcidevice}/data_source_pcidevice.go | 37 +- .../pcidevice}/data_source_pcidevice_list.go | 38 +- .../service/cloudbroker/pcidevice/models.go | 49 + .../pcidevice}/resource_pcidevice.go | 99 +- .../pcidevice}/utility_pcidevice.go | 19 +- .../pcidevice}/utility_pcidevice_list.go | 24 +- internal/service/cloudbroker/sep/api.go | 59 + .../cloudbroker/sep}/data_source_sep.go | 37 +- .../sep}/data_source_sep_config.go | 34 +- .../sep}/data_source_sep_consumption.go | 35 +- .../sep}/data_source_sep_disk_list.go | 35 +- .../cloudbroker/sep}/data_source_sep_list.go | 37 +- .../cloudbroker/sep}/data_source_sep_pool.go | 34 +- internal/service/cloudbroker/sep/models.go | 77 + .../service/cloudbroker/sep}/resource_sep.go | 197 ++- .../cloudbroker/sep}/resource_sep_config.go | 88 +- .../service/cloudbroker/sep}/utility_sep.go | 24 +- .../cloudbroker/sep}/utility_sep_config.go | 24 +- .../sep}/utility_sep_consumption.go | 24 +- .../cloudbroker/sep}/utility_sep_disk_list.go | 24 +- .../cloudbroker/sep}/utility_sep_list.go | 24 +- .../cloudbroker/sep}/utility_sep_pool.go | 24 +- 164 files changed, 5946 insertions(+), 3927 deletions(-) rename main.go => cmd/decort/main.go (73%) delete mode 100644 decort/data_source_account_deleted_list.go delete mode 100644 decort/data_source_bservice_deleted_list.go delete mode 100644 decort/models_api.go delete mode 100644 decort/provider.go create mode 100644 internal/constants/api.go rename {decort => internal/constants}/constants.go (65%) create mode 100644 internal/constants/timeouts.go rename {decort => internal/controller}/controller.go (95%) create mode 100644 internal/flattens/meta.go create mode 100644 internal/location/api.go rename decort/utility_location.go => internal/location/location.go (64%) create mode 100644 internal/location/models.go create mode 100644 internal/provider/data_sources_map.go create mode 100644 internal/provider/provider.go create mode 100644 internal/provider/resource_map.go create mode 100644 internal/service/cloudapi/account/api.go rename {decort => internal/service/cloudapi/account}/data_source_account.go (86%) rename {decort => internal/service/cloudapi/account}/data_source_account_audits_list.go (66%) rename {decort => internal/service/cloudapi/account}/data_source_account_computes_list.go (77%) rename {decort => internal/service/cloudapi/account}/data_source_account_consumed_units.go (62%) rename {decort => internal/service/cloudapi/account}/data_source_account_consumed_units_by_type.go (56%) create mode 100644 internal/service/cloudapi/account/data_source_account_deleted_list.go rename {decort => internal/service/cloudapi/account}/data_source_account_disks_list.go (67%) rename {decort => internal/service/cloudapi/account}/data_source_account_flipgroups_list.go (77%) rename {decort => internal/service/cloudapi/account}/data_source_account_list.go (79%) rename {decort => internal/service/cloudapi/account}/data_source_account_reserved_units.go (62%) rename {decort => internal/service/cloudapi/account}/data_source_account_rg_list.go (83%) rename {decort => internal/service/cloudapi/account}/data_source_account_templates_list.go (70%) rename {decort => internal/service/cloudapi/account}/data_source_account_vins_list.go (75%) create mode 100644 internal/service/cloudapi/account/models.go rename {decort => internal/service/cloudapi/account}/resource_account.go (81%) rename {decort => internal/service/cloudapi/account}/utility_account.go (63%) rename {decort => internal/service/cloudapi/account}/utility_account_audits_list.go (60%) rename {decort => internal/service/cloudapi/account}/utility_account_computes_list.go (60%) rename {decort => internal/service/cloudapi/account}/utility_account_consumed_units.go (60%) rename {decort => internal/service/cloudapi/account}/utility_account_consumed_units_by_type.go (59%) rename {decort => internal/service/cloudapi/account}/utility_account_deleted_list.go (61%) rename {decort => internal/service/cloudapi/account}/utility_account_disks_list.go (59%) rename {decort => internal/service/cloudapi/account}/utility_account_flip_groups.go (60%) rename {decort => internal/service/cloudapi/account}/utility_account_list.go (70%) rename {decort => internal/service/cloudapi/account}/utility_account_reserved_units.go (59%) rename {decort => internal/service/cloudapi/account}/utility_account_rg_list.go (59%) rename {decort => internal/service/cloudapi/account}/utility_account_templates_list.go (60%) rename {decort => internal/service/cloudapi/account}/utility_account_vins_list.go (59%) create mode 100644 internal/service/cloudapi/bservice/api.go rename {decort => internal/service/cloudapi/bservice}/data_source_bservice.go (82%) create mode 100644 internal/service/cloudapi/bservice/data_source_bservice_deleted_list.go rename {decort => internal/service/cloudapi/bservice}/data_source_bservice_group.go (81%) rename {decort => internal/service/cloudapi/bservice}/data_source_bservice_list.go (79%) rename {decort => internal/service/cloudapi/bservice}/data_source_bservice_snapshot_list.go (61%) create mode 100644 internal/service/cloudapi/bservice/models.go rename {decort => internal/service/cloudapi/bservice}/resource_bservice.go (77%) rename {decort => internal/service/cloudapi/bservice}/resource_bservice_group.go (78%) rename {decort => internal/service/cloudapi/bservice}/utility_bservicce_deleted_list.go (65%) rename {decort => internal/service/cloudapi/bservice}/utility_bservice.go (61%) rename {decort => internal/service/cloudapi/bservice}/utility_bservice_group.go (62%) rename {decort => internal/service/cloudapi/bservice}/utility_bservice_list.go (64%) rename {decort => internal/service/cloudapi/bservice}/utility_bservice_snapshot_list.go (61%) create mode 100644 internal/service/cloudapi/disks/api.go rename {decort => internal/service/cloudapi/disks}/data_source_disk.go (69%) rename {decort => internal/service/cloudapi/disks}/data_source_disk_list.go (86%) create mode 100644 internal/service/cloudapi/disks/models.go rename {decort => internal/service/cloudapi/disks}/resource_disk.go (76%) rename {decort => internal/service/cloudapi/disks}/utility_disk.go (82%) rename {decort => internal/service/cloudapi/disks}/utility_disk_list.go (65%) create mode 100644 internal/service/cloudapi/extnet/api.go rename {decort => internal/service/cloudapi/extnet}/data_source_extnet.go (81%) rename {decort => internal/service/cloudapi/extnet}/data_source_extnet_computes_list.go (73%) rename {decort => internal/service/cloudapi/extnet}/data_source_extnet_default.go (53%) rename {decort => internal/service/cloudapi/extnet}/data_source_extnet_list.go (65%) create mode 100644 internal/service/cloudapi/extnet/models.go rename {decort => internal/service/cloudapi/extnet}/utility_extnet.go (58%) rename {decort => internal/service/cloudapi/extnet}/utility_extnet_computes_list.go (59%) rename {decort => internal/service/cloudapi/extnet}/utility_extnet_default.go (53%) rename {decort => internal/service/cloudapi/extnet}/utility_extnet_list.go (63%) create mode 100644 internal/service/cloudapi/k8s/api.go create mode 100644 internal/service/cloudapi/k8s/models.go rename {decort => internal/service/cloudapi/k8s}/node_subresource.go (77%) rename {decort => internal/service/cloudapi/k8s}/resource_k8s.go (73%) rename {decort => internal/service/cloudapi/k8s}/resource_k8s_wg.go (68%) rename {decort => internal/service/cloudapi/k8s}/utility_k8s.go (58%) rename {decort => internal/service/cloudapi/k8s}/utility_k8s_wg.go (63%) create mode 100644 internal/service/cloudapi/kvmvm/api.go rename {decort => internal/service/cloudapi/kvmvm}/data_source_compute.go (89%) create mode 100644 internal/service/cloudapi/kvmvm/models.go rename {decort => internal/service/cloudapi/kvmvm}/network_subresource.go (83%) rename {decort => internal/service/cloudapi/kvmvm}/osusers_subresource.go (73%) rename {decort => internal/service/cloudapi/kvmvm}/resource_compute.go (80%) rename {decort => internal/service/cloudapi/kvmvm}/utility_compute.go (86%) create mode 100644 internal/service/cloudapi/pfw/api.go create mode 100644 internal/service/cloudapi/pfw/models.go rename {decort => internal/service/cloudapi/pfw}/resource_pfw.go (68%) rename {decort => internal/service/cloudapi/pfw}/utility_pfw.go (63%) create mode 100644 internal/service/cloudapi/rg/api.go rename {decort => internal/service/cloudapi/rg}/data_source_rg.go (68%) rename {decort => internal/service/cloudapi/rg}/data_source_rg_list.go (84%) create mode 100644 internal/service/cloudapi/rg/models.go rename {decort => internal/service/cloudapi/rg}/quota_subresource.go (84%) rename {decort => internal/service/cloudapi/rg}/resource_rg.go (79%) rename {decort => internal/service/cloudapi/rg}/utility_rg.go (80%) rename {decort => internal/service/cloudapi/rg}/utility_rg_list.go (63%) create mode 100644 internal/service/cloudapi/snapshot/api.go rename {decort => internal/service/cloudapi/snapshot}/data_source_snapshot_list.go (68%) create mode 100644 internal/service/cloudapi/snapshot/models.go rename {decort => internal/service/cloudapi/snapshot}/resource_snapshot.go (56%) rename {decort => internal/service/cloudapi/snapshot}/utility_snapshot.go (63%) rename {decort => internal/service/cloudapi/snapshot}/utility_snapshot_list.go (58%) create mode 100644 internal/service/cloudapi/vgpu/api.go rename {decort => internal/service/cloudapi/vgpu}/data_source_vgpu.go (69%) create mode 100644 internal/service/cloudapi/vgpu/models.go rename {decort => internal/service/cloudapi/vgpu}/utility_vgpu.go (65%) create mode 100644 internal/service/cloudapi/vins/api.go rename {decort => internal/service/cloudapi/vins}/data_source_vins.go (78%) rename {decort => internal/service/cloudapi/vins}/data_source_vins_list.go (75%) create mode 100644 internal/service/cloudapi/vins/models.go rename {decort => internal/service/cloudapi/vins}/resource_vins.go (78%) rename {decort => internal/service/cloudapi/vins}/utility_vins.go (82%) rename {decort => internal/service/cloudapi/vins}/utility_vins_list.go (63%) create mode 100644 internal/service/cloudbroker/grid/api.go rename {decort => internal/service/cloudbroker/grid}/data_source_grid.go (61%) rename {decort => internal/service/cloudbroker/grid}/data_source_grid_list.go (68%) create mode 100644 internal/service/cloudbroker/grid/models.go rename {decort => internal/service/cloudbroker/grid}/utility_grid.go (60%) rename {decort => internal/service/cloudbroker/grid}/utility_grid_list.go (61%) create mode 100644 internal/service/cloudbroker/image/api.go rename {decort => internal/service/cloudbroker/image}/data_source_image.go (86%) rename {decort => internal/service/cloudbroker/image}/data_source_image_list.go (74%) rename {decort => internal/service/cloudbroker/image}/data_source_image_list_stacks.go (75%) create mode 100644 internal/service/cloudbroker/image/models.go rename {decort => internal/service/cloudbroker/image}/resource_cdrom_image.go (73%) rename {decort => internal/service/cloudbroker/image}/resource_delete_images.go (56%) rename {decort => internal/service/cloudbroker/image}/resource_image.go (72%) rename {decort => internal/service/cloudbroker/image}/resource_virtual_image.go (70%) rename {decort => internal/service/cloudbroker/image}/utility_image.go (61%) rename {decort => internal/service/cloudbroker/image}/utility_image_list.go (64%) rename {decort => internal/service/cloudbroker/image}/utility_image_list_stacks.go (59%) create mode 100644 internal/service/cloudbroker/pcidevice/api.go rename {decort => internal/service/cloudbroker/pcidevice}/data_source_pcidevice.go (65%) rename {decort => internal/service/cloudbroker/pcidevice}/data_source_pcidevice_list.go (69%) create mode 100644 internal/service/cloudbroker/pcidevice/models.go rename {decort => internal/service/cloudbroker/pcidevice}/resource_pcidevice.go (61%) rename {decort => internal/service/cloudbroker/pcidevice}/utility_pcidevice.go (64%) rename {decort => internal/service/cloudbroker/pcidevice}/utility_pcidevice_list.go (55%) create mode 100644 internal/service/cloudbroker/sep/api.go rename {decort => internal/service/cloudbroker/sep}/data_source_sep.go (68%) rename {decort => internal/service/cloudbroker/sep}/data_source_sep_config.go (56%) rename {decort => internal/service/cloudbroker/sep}/data_source_sep_consumption.go (78%) rename {decort => internal/service/cloudbroker/sep}/data_source_sep_disk_list.go (58%) rename {decort => internal/service/cloudbroker/sep}/data_source_sep_list.go (72%) rename {decort => internal/service/cloudbroker/sep}/data_source_sep_pool.go (57%) create mode 100644 internal/service/cloudbroker/sep/models.go rename {decort => internal/service/cloudbroker/sep}/resource_sep.go (69%) rename {decort => internal/service/cloudbroker/sep}/resource_sep_config.go (57%) rename {decort => internal/service/cloudbroker/sep}/utility_sep.go (59%) rename {decort => internal/service/cloudbroker/sep}/utility_sep_config.go (59%) rename {decort => internal/service/cloudbroker/sep}/utility_sep_consumption.go (57%) rename {decort => internal/service/cloudbroker/sep}/utility_sep_disk_list.go (60%) rename {decort => internal/service/cloudbroker/sep}/utility_sep_list.go (61%) rename {decort => internal/service/cloudbroker/sep}/utility_sep_pool.go (59%) diff --git a/.gitignore b/.gitignore index 66a0b7a..6e92c2a 100644 --- a/.gitignore +++ b/.gitignore @@ -2,3 +2,4 @@ decort/vendor/ examples/ url_scrapping/ terraform-provider-decort* +.vscode/ \ No newline at end of file diff --git a/Makefile b/Makefile index 7dfe1d4..abc8d7e 100644 --- a/Makefile +++ b/Makefile @@ -4,6 +4,7 @@ NAMESPACE=decort NAME=terraform-provider-decort #BINARY=terraform-provider-${NAME} BINARY=${NAME}.exe +MAINPATH = ./cmd/decort/ VERSION=0.2 #OS_ARCH=darwin_amd64 OS_ARCH=windows_amd64 @@ -11,8 +12,7 @@ OS_ARCH=windows_amd64 default: install build: - go build -o ${BINARY} - + go build -o ${BINARY} ${MAINPATH} release: GOOS=darwin GOARCH=amd64 go build -o ./bin/${BINARY}_${VERSION}_darwin_amd64 GOOS=freebsd GOARCH=386 go build -o ./bin/${BINARY}_${VERSION}_freebsd_386 diff --git a/main.go b/cmd/decort/main.go similarity index 73% rename from main.go rename to cmd/decort/main.go index f5106cc..aeb5fa4 100644 --- a/main.go +++ b/cmd/decort/main.go @@ -1,6 +1,8 @@ /* -Copyright (c) 2019-2021 Digital Energy Cloud Solutions LLC. All Rights Reserved. -Author: Sergey Shubin, , +Copyright (c) 2019-2022 Digital Energy Cloud Solutions LLC. All Rights Reserved. +Authors: +Petr Krutov, +Stanislav Solovev, Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. @@ -32,10 +34,10 @@ package main import ( log "github.com/sirupsen/logrus" - "github.com/hashicorp/terraform-plugin-sdk/plugin" - "github.com/hashicorp/terraform-plugin-sdk/terraform" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" + "github.com/hashicorp/terraform-plugin-sdk/v2/plugin" - "github.com/rudecs/terraform-provider-decort/decort" + "github.com/rudecs/terraform-provider-decort/internal/provider" ) //go:generate go run github.com/hashicorp/terraform-plugin-docs/cmd/tfplugindocs @@ -45,8 +47,8 @@ func main() { log.Debug("Debug logging enabled") plugin.Serve(&plugin.ServeOpts{ - ProviderFunc: func() terraform.ResourceProvider { - return decort.Provider() + ProviderFunc: func() *schema.Provider { + return provider.Provider() }, }) } diff --git a/decort/data_source_account_deleted_list.go b/decort/data_source_account_deleted_list.go deleted file mode 100644 index d2a57c5..0000000 --- a/decort/data_source_account_deleted_list.go +++ /dev/null @@ -1,58 +0,0 @@ -/* -Copyright (c) 2019-2022 Digital Energy Cloud Solutions LLC. All Rights Reserved. -Author: Stanislav Solovev, - -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. -*/ - -/* -This file is part of Terraform (by Hashicorp) provider for Digital Energy Cloud Orchestration -Technology platfom. - -Visit https://github.com/rudecs/terraform-provider-decort for full source code package and updates. -*/ - -package decort - -import ( - "github.com/google/uuid" - "github.com/hashicorp/terraform-plugin-sdk/helper/schema" -) - -func dataSourceAccountDeletedListRead(d *schema.ResourceData, m interface{}) error { - accountDeletedList, err := utilityAccountDeletedListCheckPresence(d, m) - if err != nil { - return err - } - - id := uuid.New() - d.SetId(id.String()) - d.Set("items", flattenAccountList(accountDeletedList)) - - return nil -} - -func dataSourceAccountDeletedList() *schema.Resource { - return &schema.Resource{ - SchemaVersion: 1, - - Read: dataSourceAccountDeletedListRead, - - Timeouts: &schema.ResourceTimeout{ - Read: &Timeout30s, - Default: &Timeout60s, - }, - - Schema: dataSourceAccountListSchemaMake(), - } -} diff --git a/decort/data_source_bservice_deleted_list.go b/decort/data_source_bservice_deleted_list.go deleted file mode 100644 index 3f4dce8..0000000 --- a/decort/data_source_bservice_deleted_list.go +++ /dev/null @@ -1,58 +0,0 @@ -/* -Copyright (c) 2019-2022 Digital Energy Cloud Solutions LLC. All Rights Reserved. -Author: Stanislav Solovev, - -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. -*/ - -/* -This file is part of Terraform (by Hashicorp) provider for Digital Energy Cloud Orchestration -Technology platfom. - -Visit https://github.com/rudecs/terraform-provider-decort for full source code package and updates. -*/ - -package decort - -import ( - "github.com/google/uuid" - "github.com/hashicorp/terraform-plugin-sdk/helper/schema" -) - -func dataSourceBasicServiceDeletedListRead(d *schema.ResourceData, m interface{}) error { - basicServiceDeletedList, err := utilityBasicServiceDeletedListCheckPresence(d, m) - if err != nil { - return err - } - - id := uuid.New() - d.SetId(id.String()) - d.Set("items", flattenBasicServiceList(basicServiceDeletedList)) - - return nil -} - -func dataSourceBasicServiceDeletedList() *schema.Resource { - return &schema.Resource{ - SchemaVersion: 1, - - Read: dataSourceBasicServiceDeletedListRead, - - Timeouts: &schema.ResourceTimeout{ - Read: &Timeout30s, - Default: &Timeout60s, - }, - - Schema: dataSourceBasicServiceListSchemaMake(), - } -} diff --git a/decort/models_api.go b/decort/models_api.go deleted file mode 100644 index 89e8676..0000000 --- a/decort/models_api.go +++ /dev/null @@ -1,1486 +0,0 @@ -/* -Copyright (c) 2019-2021 Digital Energy Cloud Solutions LLC. All Rights Reserved. -Author: Sergey Shubin, , - -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. -*/ - -/* -This file is part of Terraform (by Hashicorp) provider for Digital Energy Cloud Orchestration -Technology platfom. - -Visit https://github.com/rudecs/terraform-provider-decort for full source code package and updates. -*/ - -package decort - -import ( - "encoding/json" - "fmt" - "strconv" - "time" -) - -// -// timeouts for API calls from CRUD functions of Terraform plugin -var Timeout30s = time.Second * 30 -var Timeout60s = time.Second * 60 -var Timeout180s = time.Second * 180 -var Timeout20m = time.Minute * 20 - -// -// structures related to /cloudapi/rg/list API -// -type UserAclRecord struct { - IsExplicit bool `json:"explicit"` - Rights string `json:"right"` - Status string `json:"status"` - Type string `json:"type"` - UgroupID string `json:"userGroupId"` - // CanBeDeleted bool `json:"canBeDeleted"` -} - -type AccountAclRecord struct { - IsExplicit bool `json:"explicit"` - Guid string `json:"guid"` - Rights string `json:"right"` - Status string `json:"status"` - Type string `json:"type"` - UgroupID string `json:"userGroupId"` - CanBeDeleted bool `json:"canBeDeleted"` -} - -type ResourceLimits struct { - CUC float64 `json:"CU_C"` - CUD float64 `json:"CU_D"` - CUI float64 `json:"CU_I"` - CUM float64 `json:"CU_M"` - CUNP float64 `json:"CU_NP"` - GpuUnits float64 `json:"gpu_units"` -} - -type ResgroupRecord struct { - ACLs []AccountAclRecord `json:"acl"` - AccountID int `json:"accountId"` - AccountName string `json:"accountName"` - CreatedBy string `json:"createdBy"` - CreatedTime uint64 `json:"createdTime"` - DefaultNetID int `json:"def_net_id"` - DefaultNetType string `json:"def_net_type"` - DeletedBy string `json:"deletedBy"` - DeletedTime int `json:"deletedTime"` - Decsription string `json:"desc"` - GridID int `json:"gid"` - GUID int `json:"guid"` - ID uint `json:"id"` - LockStatus string `json:"lockStatus"` - Milestones int `json:"milestones"` - Name string `json:"name"` - RegisterComputes bool `json:"registerComputes"` - ResourceLimits ResourceLimits `json:"resourceLimits"` - Secret string `json:"secret"` - Status string `json:"status"` - UpdatedBy string `json:"updatedBy"` - UpdatedTime uint64 `json:"updatedTime"` - Vins []int `json:"vins"` - Computes []int `json:"vms"` -} - -const ResgroupListAPI = "/restmachine/cloudapi/rg/list" - -type ResgroupListResp []ResgroupRecord - -// -// structures related to /cloudapi/rg/create API call -// -const ResgroupCreateAPI = "/restmachine/cloudapi/rg/create" - -// -// structures related to /cloudapi/rg/update API call -// -const ResgroupUpdateAPI = "/restmachine/cloudapi/rg/update" - -type ResgroupUpdateParam struct { - RgId int `json:"rgId"` - Name string `json:"name"` - Desc string `json:"decs"` - Ram int `json:"maxMemoryCapacity"` - Disk int `json:"maxVDiskCapacity"` - Cpu int `json:"maxCPUCapacity"` - NetTraffic int `json:"maxNetworkPeerTransfer"` - Reason string `json:"reason"` -} - -// -// structures related to /cloudapi/rg/get API call -// -type QuotaRecord struct { // this is how quota is reported by /api/.../rg/get - Cpu int `json:"CU_C"` // CPU count in pcs - Ram float64 `json:"CU_M"` // RAM volume in MB, it is STILL reported as FLOAT - Disk int `json:"CU_D"` // Disk capacity in GB - ExtIPs int `json:"CU_I"` // Ext IPs count - ExtTraffic int `json:"CU_NP"` // Ext network traffic - GpuUnits int `json:"gpu_units"` // GPU count -} - -type ResourceRecord struct { // this is how actual usage is reported by /api/.../rg/get - Cpu int `json:"cpu"` - Disk int `json:"disksize"` - ExtIPs int `json:"extips"` - ExtTraffic int `json:"exttraffic"` - Gpu int `json:"gpu"` - Ram int `json:"ram"` -} - -type UsageRecord struct { - Current ResourceRecord `json:"Current"` - Reserved ResourceRecord `json:"Reserved"` -} - -const ResgroupGetAPI = "/restmachine/cloudapi/rg/get" - -type ResgroupGetResp struct { - ACLs []UserAclRecord `json:"ACLs"` - Usage UsageRecord `json:"Resources"` - AccountID int `json:"accountId"` - AccountName string `json:"accountName"` - GridID int `json:"gid"` - CreatedBy string `json:"createdBy"` - CreatedTime uint64 `json:"createdTime"` - DefaultNetID int `json:"def_net_id"` - DefaultNetType string `json:"def_net_type"` - DeletedBy string `json:"deletedBy"` - DeletedTime uint64 `json:"deletedTime"` - Desc string `json:"desc"` - ID uint `json:"id"` - LockStatus string `json:"lockStatus"` - Name string `json:"name"` - Quota QuotaRecord `json:"resourceLimits"` - Status string `json:"status"` - UpdatedBy string `json:"updatedBy"` - UpdatedTime uint64 `json:"updatedTime"` - Vins []int `json:"vins"` - Computes []int `json:"vms"` - - Ignored map[string]interface{} `json:"-"` -} - -// -// structures related to /cloudapi/rg/delete API -// -const ResgroupDeleteAPI = "/restmachine/cloudapi/rg/delete" - -// -// structures related to /cloudapi/rg/listComputes API -// -type ComputeBriefRecord struct { // this is a brief compute specifiaction as returned by API rg/listComputes - // we do not even include here all fields as returned by this API, but only the most important that - // are really necessary to identify and distinguish computes - AccountID int `json:"accountId"` - AccountName string `json:"accountName"` - Name string `json:"name"` - ID uint `json:"id"` - RgID int `json:"rgId"` - RgName string `json:"rgName"` - Status string `json:"status"` - TechStatus string `json:"techStatus"` -} - -const RgListComputesAPI = "/restmachine/cloudapi/rg/listComputes" - -type RgListComputesResp []ComputeBriefRecord - -// -// structures related to /cloudapi/kvmXXX/create APIs -// -const KvmX86CreateAPI = "/restmachine/cloudapi/kvmx86/create" -const KvmPPCCreateAPI = "/restmachine/cloudapi/kvmppc/create" - -type KvmVmCreateParam struct { // this is unified structure for both x86 and PPC based KVM VMs creation - RgID uint `json:"rgId"` - Name string `json:"name"` - Cpu int `json:"cpu"` - Ram int `json:"ram"` - ImageID int `json:"imageId"` - BootDisk int `json:"bootDisk"` - NetType string `json:"netType"` - NetId int `json:"netId"` - IPAddr string `json:"ipAddr"` - UserData string `json:"userdata"` - Desc string `json:"desc"` - Start bool `json:"start"` -} - -// structures related to cloudapi/compute/start API -const ComputeStartAPI = "/restmachine/cloudapi/compute/start" -const ComputeStopAPI = "/restmachine/cloudapi/compute/stop" - -// structures related to cloudapi/compute/delete API -const ComputeDeleteAPI = "/restmachine/cloudapi/compute/delete" - -// -// structures related to /cloudapi/compute/list API -// - -type InterfaceQosRecord struct { - ERate int `json:"eRate"` - Guid string `json:"guid"` - InBurst int `json:"inBurst"` - InRate int `json:"inRate"` -} - -type InterfaceRecord struct { - ConnID int `json:"connId"` // This is VLAN ID or VxLAN ID, depending on ConnType - ConnType string `json:"connType"` // Either "VLAN" or "VXLAN" tag - DefaultGW string `json:"defGw"` - Guid string `json:"guid"` - IPAddress string `json:"ipAddress"` // without trailing network mask, i.e. "192.168.1.3" - MAC string `json:"mac"` - Name string `json:"name"` - NetID int `json:"netId"` // This is either ExtNet ID or ViNS ID, depending on NetType - NetMask int `json:"netMask"` - NetType string `json:"netType"` // Either "EXTNET" or "VINS" tag - PciSlot int `json:"pciSlot"` - Target string `json:"target"` - Type string `json:"type"` - VNFs []int `json:"vnfs"` - QOS InterfaceQosRecord `json:"qos"` -} - -type SnapSetRecord struct { - Disks []int `json:"disks"` - Guid string `json:"guid"` - Label string `json:"label"` - TimeStamp uint64 `json:"timestamp"` -} - -type ComputeRecord struct { - AccountID int `json:"accountId"` - AccountName string `json:"accountName"` - ACLs []UserAclRecord `json:"acl"` - Arch string `json:"arch"` - BootDiskSize int `json:"bootdiskSize"` - CloneReference int `json:"cloneReference"` - Clones []int `json:"clones"` - Cpus int `json:"cpus"` - CreatedBy string `json:"createdBy"` - CreatedTime uint64 `json:"createdTime"` - DeletedBy string `json:"deletedBy"` - DeletedTime uint64 `json:"deletedTime"` - Desc string `json:"desc"` - Disks []int `json:"disks"` - GridID int `json:"gid"` - ID uint `json:"id"` - ImageID int `json:"imageId"` - Interfaces []InterfaceRecord `json:"interfaces"` - LockStatus string `json:"lockStatus"` - ManagerID int `json:"managerId"` - Name string `json:"name"` - Ram int `json:"ram"` - RgID int `json:"rgId"` - RgName string `json:"rgName"` - SnapSets []SnapSetRecord `json:"snapSets"` - Status string `json:"status"` - // Tags []string `json:"tags"` // Tags were reworked since DECORT 3.7.1 - TechStatus string `json:"techStatus"` - TotalDiskSize int `json:"totalDiskSize"` - UpdatedBy string `json:"updatedBy"` - UpdateTime uint64 `json:"updateTime"` - UserManaged bool `json:"userManaged"` - Vgpus []int `json:"vgpus"` - VinsConnected int `json:"vinsConnected"` - VirtualImageID int `json:"virtualImageId"` -} - -const ComputeListAPI = "/restmachine/cloudapi/compute/list" - -type ComputeListResp []ComputeRecord - -const ComputeResizeAPI = "/restmachine/cloudapi/compute/resize" - -// -// structures related to /cloudapi/compute/get -// -type SnapshotRecord struct { - Guid string `json:"guid"` - Label string `json:"label"` - ResId string `json:"resId"` - SnapSetGuid string `json:"snapSetGuid"` - SnapSetTime uint64 `json:"snapSetTime"` - TimeStamp uint64 `json:"timestamp"` -} - -type SnapshotRecordList []SnapshotRecord - -type DiskRecord struct { - Acl map[string]interface{} `json:"acl"` - AccountID int `json:"accountId"` - AccountName string `json:"accountName"` - BootPartition int `json:"bootPartition"` - CreatedTime uint64 `json:"creationTime"` - ComputeID int `json:"computeId"` - ComputeName string `json:"computeName"` - DeletedTime uint64 `json:"deletionTime"` - DeviceName string `json:"devicename"` - Desc string `json:"desc"` - DestructionTime uint64 `json:"destructionTime"` - DiskPath string `json:"diskPath"` - GridID int `json:"gid"` - GUID int `json:"guid"` - ID uint `json:"id"` - ImageID int `json:"imageId"` - Images []int `json:"images"` - IOTune map[string]interface{} `json:"iotune"` - IQN string `json:"iqn"` - Login string `json:"login"` - Name string `json:"name"` - MachineId int `json:"machineId"` - MachineName string `json:"machineName"` - Milestones uint64 `json:"milestones"` - Order int `json:"order"` - Params string `json:"params"` - Passwd string `json:"passwd"` - ParentId int `json:"parentId"` - PciSlot int `json:"pciSlot"` - Pool string `json:"pool"` - PurgeTime uint64 `json:"purgeTime"` - PurgeAttempts uint64 `json:"purgeAttempts"` - RealityDeviceNumber int `json:"realityDeviceNumber"` - ReferenceId string `json:"referenceId"` - ResID string `json:"resId"` - ResName string `json:"resName"` - Role string `json:"role"` - SepType string `json:"sepType"` - SepID int `json:"sepId"` // NOTE: absent from compute/get output - SizeMax int `json:"sizeMax"` - SizeUsed int `json:"sizeUsed"` // sum over all snapshots of this disk to report total consumed space - Snapshots []SnapshotRecord `json:"snapshots"` - Status string `json:"status"` - TechStatus string `json:"techStatus"` - Type string `json:"type"` - UpdateBy uint64 `json:"updateBy"` - VMID int `json:"vmid"` -} - -type OsUserRecord struct { - Guid string `json:"guid"` - Login string `json:"login"` - Password string `json:"password"` - PubKey string `json:"pubkey"` -} - -const ComputeGetAPI = "/restmachine/cloudapi/compute/get" - -type ComputeGetResp struct { - // ACLs `json:"ACL"` - it is a dictionary, special parsing required - AccountID int `json:"accountId"` - AccountName string `json:"accountName"` - Arch string `json:"arch"` - BootDiskSize int `json:"bootdiskSize"` - CloneReference int `json:"cloneReference"` - Clones []int `json:"clones"` - Cpu int `json:"cpus"` - Desc string `json:"desc"` - Disks []DiskRecord `json:"disks"` - Driver string `json:"driver"` - GridID int `json:"gid"` - ID uint `json:"id"` - ImageID int `json:"imageId"` - ImageName string `json:"imageName"` - Interfaces []InterfaceRecord `json:"interfaces"` - LockStatus string `json:"lockStatus"` - ManagerID int `json:"managerId"` - ManagerType string `json:"manageType"` - Name string `json:"name"` - NatableVinsID int `json:"natableVinsId"` - NatableVinsIP string `json:"natableVinsIp"` - NatableVinsName string `json:"natableVinsName"` - NatableVinsNet string `json:"natableVinsNetwork"` - NatableVinsNetName string `json:"natableVinsNetworkName"` - OsUsers []OsUserRecord `json:"osUsers"` - Ram int `json:"ram"` - RgID int `json:"rgId"` - RgName string `json:"rgName"` - SnapSets []SnapSetRecord `json:"snapSets"` - Status string `json:"status"` - // Tags []string `json:"tags"` // Tags were reworked since DECORT 3.7.1 - TechStatus string `json:"techStatus"` - TotalDiskSize int `json:"totalDiskSize"` - UpdatedBy string `json:"updatedBy"` - UpdateTime uint64 `json:"updateTime"` - UserManaged bool `json:"userManaged"` - Vgpus []int `json:"vgpus"` - VinsConnected int `json:"vinsConnected"` - VirtualImageID int `json:"virtualImageId"` -} - -// -// structures related to /restmachine/cloudapi/image/list API -// -type ImageRecord struct { - AccountID uint `json:"accountId"` - Arch string `json:"architecture"` - BootType string `json:"bootType"` - IsBootable bool `json:"bootable"` - IsCdrom bool `json:"cdrom"` - Desc string `json:"desc"` - IsHotResize bool `json:"hotResize"` - ID uint `json:"id"` - Name string `json:"name"` - Pool string `json:"pool"` - SepID int `json:"sepId"` - Size int `json:"size"` - Status string `json:"status"` - Type string `json:"type"` - Username string `json:"username"` - IsVirtual bool `json:"virtual"` -} - -const ImagesListAPI = "/restmachine/cloudapi/image/list" - -type ImagesListResp []ImageRecord - -// -// structures related to /cloudapi/extnet/list API -// -type ExtNetRecord struct { - Name string `json:"name"` - ID uint `json:"id"` - IPCIDR string `json:"ipcidr"` -} - -const ExtNetListAPI = "/restmachine/cloudapi/extnet/list" - -type ExtNetListResp []ExtNetRecord - -// -// structures related to /cloudapi/account/list API -// -type AccountRecord struct { - // ACLs []UserAclRecord `json:"acl"` - // CreatedTime uint64 `json:"creationTime"` - // DeletedTime uint64 `json:"deletionTime"` - ID int `json:"id"` - Name string `json:"name"` - Status string `json:"status"` - // UpdatedTime uint64 `json:"updateTime"` -} - -const AccountsGetAPI = "/restmachine/cloudapi/account/get" // returns AccountRecord superset - -const AccountsListAPI = "/restmachine/cloudapi/account/list" // returns list of abdridged info about accounts -type AccountsListResp []AccountRecord - -// -// structures related to /cloudapi/portforwarding/list API -// -type PfwRecord struct { - ID int `json:"id"` - LocalIP string `json:"localIp"` - LocalPort int `json:"localPort"` - Protocol string `json:"protocol"` - PublicPortEnd int `json:"publicPortEnd"` - PublicPortStart int `json:"publicPortStart"` - ComputeID int `json:"vmId"` -} - -const ComputePfwListAPI = "/restmachine/cloudapi/compute/pfwList" - -type ComputePfwListResp []PfwRecord - -const ComputePfwAddAPI = "/restmachine/cloudapi/compute/pfwAdd" - -const ComputePfwDelAPI = "/restmachine/cloudapi/compute/pfwDel" - -// -// structures related to /cloudapi/compute/net Attach/Detach API -// -type ComputeNetMgmtRecord struct { // used to "cache" network specs when preparing to manage compute networks - ID int - Type string - IPAddress string - MAC string -} - -const ComputeNetAttachAPI = "/restmachine/cloudapi/compute/netAttach" - -const ComputeNetDetachAPI = "/restmachine/cloudapi/compute/netDetach" - -// -// structures related to /cloudapi/compute/disk Attach/Detach API -// -const ComputeDiskAttachAPI = "/restmachine/cloudapi/compute/diskAttach" - -const ComputeDiskDetachAPI = "/restmachine/cloudapi/compute/diskDetach" - -// -// structures related to /cloudapi/disks/create -// -const DisksCreateAPI = "/restmachine/cloudapi/disks/create" - -// -// structures related to /cloudapi/disks/get -// -const DisksGetAPI = "/restmachine/cloudapi/disks/get" // Returns single DiskRecord on success - -const DisksListAPI = "/restmachine/cloudapi/disks/list" // Returns list of DiskRecord on success - -type DisksListResp []DiskRecord - -// -// structures related to /cloudapi/disks/resize -// -const DisksResizeAPI = "/restmachine/cloudapi/disks/resize2" - -// -// structures related to /cloudapi/disks/resize -// -const DisksRenameAPI = "/restmachine/cloudapi/disks/rename" - -// -// structures related to /cloudapi/disks/delete -// -const DisksDeleteAPI = "/restmachine/cloudapi/disks/delete" - -// -// ViNS structures -// - -// this is the structure of the element in the list returned by vins/search API -type VinsSearchRecord struct { - ID int `json:"id"` - Name string `json:"name"` - IPCidr string `json:"network"` - VxLanID int `json:"vxlanId"` - ExternalIP string `json:"externalIP"` - AccountID int `json:"accountId"` - AccountName string `json:"accountName"` - RgID int `json:"rgId"` - RgName string `json:"rgName"` -} - -const VinsSearchAPI = "/restmachine/cloudapi/vins/search" - -type VinsSearchResp []VinsSearchRecord - -type VnfRecord struct { - ID int `json:"id"` - AccountID int `json:"accountId"` - Type string `json:"type"` // "DHCP", "NAT", "GW" etc - Config map[string]interface{} `json:"config"` // NOTE: VNF specs vary by VNF type -} - -type VnfGwConfigRecord struct { // describes GW VNF config structure inside ViNS, as returned by API vins/get - ExtNetID int `json:"ext_net_id"` - ExtNetIP string `json:"ext_net_ip"` - ExtNetMask int `json:"ext_net_mask"` - DefaultGW string `json:"default_gw"` -} -type VinsRecord struct { // represents part of the response from API vins/get - ID int `json:"id"` - Name string `json:"name"` - IPCidr string `json:"network"` - VxLanID int `json:"vxlanId"` - ExternalIP string `json:"externalIP"` - AccountID int `json:"accountId"` - AccountName string `json:"accountName"` - RgID int `json:"rgid"` - RgName string `json:"rgName"` - VNFs map[string]VnfRecord `json:"vnfs"` - Desc string `json:"desc"` -} - -const VinsGetAPI = "/restmachine/cloudapi/vins/get" - -const VinsCreateInAccountAPI = "/restmachine/cloudapi/vins/createInAccount" -const VinsCreateInRgAPI = "/restmachine/cloudapi/vins/createInRG" - -const VinsExtNetConnectAPI = "/restmachine/cloudapi/vins/extNetConnect" -const VinsExtNetDisconnectAPI = "/restmachine/cloudapi/vins/extNetDisconnect" - -const VinsDeleteAPI = "/restmachine/cloudapi/vins/delete" - -// -// K8s structures -// - -//K8sNodeRecord represents a worker/master group -type K8sNodeRecord struct { - ID int `json:"id"` - Name string `json:"name"` - Disk int `json:"disk"` - Cpu int `json:"cpu"` - Num int `json:"num"` - Ram int `json:"ram"` - DetailedInfo []struct { - ID int `json:"id"` - Name string `json:"name"` - } `json:"detailedInfo"` -} - -//K8sRecord represents k8s instance -type K8sRecord struct { - AccountID int `json:"accountId"` - AccountName string `json:"accountName"` - CI int `json:"ciId"` - ID int `json:"id"` - Groups struct { - Masters K8sNodeRecord `json:"masters"` - Workers []K8sNodeRecord `json:"workers"` - } `json:"k8sGroups"` - LbID int `json:"lbId"` - Name string `json:"name"` - RgID int `json:"rgId"` - RgName string `json:"rgName"` -} - -//LbRecord represents load balancer instance -type LbRecord struct { - ID int `json:"id"` - Name string `json:"name"` - RgID int `json:"rgId"` - VinsID int `json:"vinsId"` - ExtNetID int `json:"extnetId"` - PrimaryNode struct { - BackendIP string `json:"backendIp"` - ComputeID int `json:"computeId"` - FrontendIP string `json:"frontendIp"` - NetworkID int `json:"networkId"` - } `json:"primaryNode"` -} - -const K8sCreateAPI = "/restmachine/cloudapi/k8s/create" -const K8sGetAPI = "/restmachine/cloudapi/k8s/get" -const K8sUpdateAPI = "/restmachine/cloudapi/k8s/update" -const K8sDeleteAPI = "/restmachine/cloudapi/k8s/delete" - -const K8sWgCreateAPI = "/restmachine/cloudapi/k8s/workersGroupAdd" -const K8sWgDeleteAPI = "/restmachine/cloudapi/k8s/workersGroupDelete" - -const K8sWorkerAddAPI = "/restmachine/cloudapi/k8s/workerAdd" -const K8sWorkerDeleteAPI = "/restmachine/cloudapi/k8s/deleteWorkerFromGroup" - -const K8sGetConfigAPI = "/restmachine/cloudapi/k8s/getConfig" - -const LbGetAPI = "/restmachine/cloudapi/lb/get" - -//Blasphemous workaround for parsing Result value -type TaskResult int - -func (r *TaskResult) UnmarshalJSON(b []byte) error { - if b[0] == '"' { - b := b[1 : len(b)-1] - if len(b) == 0 { - *r = 0 - return nil - } - n, err := strconv.Atoi(string(b)) - if err != nil { - return err - } - *r = TaskResult(n) - } else if b[0] == '[' { - res := []interface{}{} - if err := json.Unmarshal(b, &res); err != nil { - return err - } - if n, ok := res[0].(float64); ok { - *r = TaskResult(n) - } else { - return fmt.Errorf("could not unmarshal %v into int", res[0]) - } - } - - return nil -} - -//AsyncTask represents a long task completion status -type AsyncTask struct { - AuditID string `json:"auditId"` - Completed bool `json:"completed"` - Error string `json:"error"` - Log []string `json:"log"` - Result TaskResult `json:"result"` - Stage string `json:"stage"` - Status string `json:"status"` - UpdateTime uint64 `json:"updateTime"` - UpdatedTime uint64 `json:"updatedTime"` -} - -const AsyncTaskGetAPI = "/restmachine/cloudapi/tasks/get" - -// -// Grid ID structures -// -type LocationRecord struct { - GridID int `json:"gid"` - Id int `json:"id"` - LocationCode string `json:"locationCode"` - Name string `json:"name"` - Flag string `json:"flag"` -} - -const LocationsListAPI = "/restmachine/cloudapi/locations/list" // Returns list of GridRecord on success -type LocationsListResp []LocationRecord - -// -// Auxiliary structures -// -type SshKeyConfig struct { - User string - SshKey string - UserShell string -} - -//////////////////// -// IMAGE API // -//////////////////// -const imageCreateAPI = "/restmachine/cloudbroker/image/createImage" -const imageSyncCreateAPI = "/restmachine/cloudbroker/image/syncCreateImage" -const imageCreateVirtualAPI = "/restmachine/cloudbroker/image/createVirtual" -const imageCreateCDROMAPI = "/restmachine/cloudbroker/image/createCDROMImage" -const imageListStacksApi = "/restmachine/cloudbroker/image/listStacks" -const imageGetAPI = "/restmachine/cloudbroker/image/get" -const imageListGetAPI = "/restmachine/cloudbroker/image/list" -const imageEditAPI = "/restmachine/cloudbroker/image/edit" -const imageDeleteAPI = "/restmachine/cloudbroker/image/delete" -const imageDeleteCDROMAPI = "/restmachine/cloudbroker/image/deleteCDROMImage" -const imageEnableAPI = "/restmachine/cloudbroker/image/enable" -const imageDisableAPI = "/restmachine/cloudbroker/image/disable" -const imageEditNameAPI = "/restmachine/cloudbroker/image/rename" -const imageLinkAPI = "/restmachine/cloudbroker/image/link" -const imageShareAPI = "/restmachine/cloudbroker/image/share" -const imageComputeciSetAPI = "/restmachine/cloudbroker/image/computeciSet" -const imageComputeciUnsetAPI = "/restmachine/cloudbroker/image/computeciUnset" -const imageUpdateNodesAPI = "/restmachine/cloudbroker/image/updateNodes" -const imageDeleteImagesAPI = "/restmachine/cloudbroker/image/deleteImages" - -type History struct { - Guid string `json:"guid"` - Id int `json:"id"` - Timestamp int64 `json:"timestamp"` -} - -type Image struct { - ImageId int `json:"id"` - Name string `json:"name"` - Url string `json:"url"` - Gid int `json:"gid"` - Guid int `json:"guid"` - Boottype string `json:"bootType"` - Imagetype string `json:"type"` - Drivers []string `json:"drivers"` - Hotresize bool `json:"hotResize"` - Bootable bool `json:"bootable"` - Username string `json:"username"` - Password string `json:"password"` - AccountId int `json:"accountId"` - UsernameDL string `json:"usernameDL"` - PasswordDL string `json:"passwordDL"` - SepId int `json:"sepId"` - PoolName string `json:"pool"` - Architecture string `json:"architecture"` - UNCPath string `json:"UNCPath"` - LinkTo int `json:"linkTo"` - Status string `json:"status"` - TechStatus string `json:"techStatus"` - Size int `json:"size"` - Version string `json:"version"` - Enabled bool `json:"enabled"` - ComputeciId int `json:"computeciId"` - Milestones int `json:"milestones"` - ProviderName string `json:"provider_name"` - PurgeAttempts int `json:"purgeAttempts"` - ReferenceId string `json:"referenceId"` - ResId string `json:"resId"` - ResName string `json:"resName"` - Rescuecd bool `json:"rescuecd"` - Meta []interface{} `json:"_meta"` - History []History `json:"history"` - LastModified int64 `json:"lastModified"` - Desc string `json:"desc"` - SharedWith []int `json:"sharedWith"` -} - -type ImageList []Image - -type ImageStack struct { - ApiURL string `json:"apiUrl"` - ApiKey string `json:"apikey"` - AppId string `json:"appId"` - Desc string `json:"desc"` - Drivers []string `json:"drivers"` - Error int `json:"error"` - Guid int `json:"guid"` - Id int `json:"id"` - Images []int `json:"images"` - Login string `json:"login"` - Name string `json:"name"` - Passwd string `json:"passwd"` - ReferenceId string `json:"referenceId"` - Status string `json:"status"` - Type string `json:"type"` -} - -type ImageListStacks []ImageStack - -///////////////// -// GRID API // -///////////////// -const GridListGetAPI = "/restmachine/cloudbroker/grid/list" -const GridGetAPI = "/restmachine/cloudbroker/grid/get" - -type Grid struct { - Flag string `json:"flag"` - Gid int `json:"gid"` - Guid int `json:"guid"` - Id int `json:"id"` - LocationCode string `json:"locationCode"` - Name string `json:"name"` -} - -type GridList []Grid - -///////////////////// -/// SNAPSHOT API /// -///////////////////// - -const snapshotCreateAPI = "/restmachine/cloudapi/compute/snapshotCreate" -const snapshotDeleteAPI = "/restmachine/cloudapi/compute/snapshotDelete" -const snapshotRollbackAPI = "/restmachine/cloudapi/compute/snapshotRollback" -const snapshotListAPI = "/restmachine/cloudapi/compute/snapshotList" - -type Snapshot struct { - Disks []int `json:"disks"` - Guid string `json:"guid"` - Label string `json:"label"` - Timestamp uint64 `json:"timestamp"` -} - -type SnapshotList []Snapshot - -//////////////// -/// VGPU API /// -//////////////// - -const vgpuListAPI = "/restmachine/cloudbroker/vgpu/list" - -type VGPU struct { - AccountID int `json:"accountId"` - ID int `json:"id"` - Mode string `json:"mode"` - PgpuID int `json:"pgpuid"` - ProfileID int `json:"profileId"` - RAM int `json:"ram"` - Status string `json:"status"` - Type string `json:"type"` - VmID int `json:"vmid"` -} - -///////////////////////////// -// PCIDEVICE // -///////////////////////////// - -const pcideviceListAPI = "/restmachine/cloudbroker/pcidevice/list" -const pcideviceDisableAPI = "/restmachine/cloudbroker/pcidevice/disable" -const pcideviceEnableAPI = "/restmachine/cloudbroker/pcidevice/enable" -const pcideviceCreateAPI = "/restmachine/cloudbroker/pcidevice/create" -const pcideviceDeleteAPI = "/restmachine/cloudbroker/pcidevice/delete" - -type Pcidevice struct { - CKey string `json:"_ckey"` - Meta []interface{} `json:"_meta"` - Computeid int `json:"computeId"` - Description string `json:"description"` - Guid int `json:"guid"` - HwPath string `json:"hwPath"` - ID int `json:"id"` - Name string `json:"name"` - RgID int `json:"rgId"` - StackID int `json:"stackId"` - Status string `json:"status"` - SystemName string `json:"systemName"` -} - -type PcideviceList []Pcidevice - -/////////////////// -///// SEP API ///// -/////////////////// -const sepAddConsumerNodesAPI = "/restmachine/cloudbroker/sep/addConsumerNodes" -const sepDelConsumerNodesAPI = "/restmachine/cloudbroker/sep/delConsumerNodes" -const sepAddProviderNodesAPI = "/restmachine/cloudbroker/sep/addProviderNodes" - -const sepConfigFieldEditAPI = "/restmachine/cloudbroker/sep/configFieldEdit" -const sepConfigInsertAPI = "/restmachine/cloudbroker/sep/configInsert" -const sepConfigValidateAPI = "/restmachine/cloudbroker/sep/configValidate" - -const sepConsumptionAPI = "/restmachine/cloudbroker/sep/consumption" - -const sepDecommissionAPI = "/restmachine/cloudbroker/sep/decommission" - -const sepEnableAPI = "/restmachine/cloudbroker/sep/enable" -const sepDisableAPI = "/restmachine/cloudbroker/sep/disable" - -const sepDiskListAPI = "/restmachine/cloudbroker/sep/diskList" - -const sepGetAPI = "/restmachine/cloudbroker/sep/get" -const sepGetConfigAPI = "/restmachine/cloudbroker/sep/getConfig" -const sepGetPoolAPI = "/restmachine/cloudbroker/sep/getPool" - -const sepCreateAPI = "/restmachine/cloudbroker/sep/create" -const sepDeleteAPI = "/restmachine/cloudbroker/sep/delete" -const sepListAPI = "/restmachine/cloudbroker/sep/list" - -const sepUpdateCapacityLimitAPI = "/restmachine/cloudbroker/sep/updateCapacityLimit" - -///Sep Models -type SepConsumptionInd struct { - DiskCount int `json:"disk_count"` - DiskUsage int `json:"disk_usage"` - SnapshotCount int `json:"snapshot_count"` - SnapshotUsage int `json:"snapshot_usage"` - Usage int `json:"usage"` - UsageLimit int `json:"usage_limit"` -} - -type SepConsumptionTotal struct { - CapacityLimit int `json:"capacity_limit"` - SepConsumptionInd -} - -type SepConsumption struct { - Total SepConsumptionTotal `json:"total"` - Type string `json:"type"` - ByPool map[string]SepConsumptionInd `json:"byPool"` -} - -type SepDiskList []int - -type Sep struct { - Ckey string `json:"_ckey"` - Meta []interface{} `json:"_meta"` - ConsumedBy []int `json:"consumedBy"` - Desc string `json:"desc"` - Gid int `json:"gid"` - Guid int `json:"guid"` - Id int `json:"id"` - Milestones int `json:"milestones"` - Name string `json:"name"` - ObjStatus string `json:"objStatus"` - ProvidedBy []int `json:"providedBy"` - TechStatus string `json:"techStatus"` - Type string `json:"type"` - Config SepConfig `json:"config"` -} - -type SepConfig map[string]interface{} - -type SepList []Sep -type SepPool map[string]interface{} - -/////////////////////// -///// ACCOUNTS //// -/////////////////////// - -const accountAddUserAPI = "/restmachine/cloudapi/account/addUser" -const accountAuditsAPI = "/restmachine/cloudapi/account/audits" -const accountCreateAPI = "/restmachine/cloudapi/account/create" -const accountDeleteAPI = "/restmachine/cloudapi/account/delete" -const accountDeleteUserAPI = "/restmachine/cloudapi/account/deleteUser" -const accountDisableAPI = "/restmachine/cloudapi/account/disable" -const accountEnableAPI = "/restmachine/cloudapi/account/enable" -const accountGetAPI = "/restmachine/cloudapi/account/get" -const accountGetConsumedUnitsAPI = "/restmachine/cloudapi/account/getConsumedAccountUnits" -const accountGetConsumedUnitsByTypeAPI = "/restmachine/cloudapi/account/getConsumedCloudUnitsByType" -const accountGetReservedUnitsAPI = "/restmachine/cloudapi/account/getReservedAccountUnits" -const accountListAPI = "/restmachine/cloudapi/account/list" -const accountListComputesAPI = "/restmachine/cloudapi/account/listComputes" -const accountListDeletedAPI = "/restmachine/cloudapi/account/listDeleted" -const accountListDisksAPI = "/restmachine/cloudapi/account/listDisks" -const accountListFlipGroupsAPI = "/restmachine/cloudapi/account/listFlipGroups" -const accountListRGAPI = "/restmachine/cloudapi/account/listRG" -const accountListTemplatesAPI = "/restmachine/cloudapi/account/listTemplates" -const accountListVinsAPI = "/restmachine/cloudapi/account/listVins" -const accountRestoreAPI = "/restmachine/cloudapi/account/restore" -const accountUpdateAPI = "/restmachine/cloudapi/account/update" -const accountUpdateUserAPI = "/restmachine/cloudapi/account/updateUser" - -////Structs - -type Account struct { - DCLocation string `json:"DCLocation"` - CKey string `jspn:"_ckey"` - Meta []interface{} `json:"_meta"` - Acl []AccountAclRecord `json:"acl"` - Company string `json:"company"` - CompanyUrl string `json:"companyurl"` - CreatedBy string `jspn:"createdBy"` - CreatedTime int `json:"createdTime"` - DeactiovationTime float64 `json:"deactivationTime"` - DeletedBy string `json:"deletedBy"` - DeletedTime int `json:"deletedTime"` - DisplayName string `json:"displayname"` - GUID int `json:"guid"` - ID int `json:"id"` - Name string `json:"name"` - ResourceLimits ResourceLimits `json:"resourceLimits"` - SendAccessEmails bool `json:"sendAccessEmails"` - ServiceAccount bool `json:"serviceAccount"` - Status string `json:"status"` - UpdatedTime int `json:"updatedTime"` - Version int `json:"version"` - Vins []int `json:"vins"` -} - -type AccountList []Account - -type AccountCloudApi struct { - Acl []AccountAclRecord `json:"acl"` - CreatedTime int `json:"createdTime"` - DeletedTime int `json:"deletedTime"` - ID int `json:"id"` - Name string `json:"name"` - Status string `json:"status"` - UpdatedTime int `json:"updatedTime"` -} - -type AccountCloudApiList []AccountCloudApi - -type Resource struct { - CPU int `json:"cpu"` - Disksize int `json:"disksize"` - Extips int `json:"extips"` - Exttraffic int `json:"exttraffic"` - GPU int `json:"gpu"` - RAM int `json:"ram"` -} - -type Resources struct { - Current Resource `json:"Current"` - Reserved Resource `json:"Reserved"` -} - -type Computes struct { - Started int `json:"started"` - Stopped int `json:"stopped"` -} - -type Machines struct { - Running int `json:"running"` - Halted int `json:"halted"` -} - -type AccountWithResources struct { - Account - Resources Resources `json:"Resources"` - Computes Computes `json:"computes"` - Machines Machines `json:"machines"` - Vinses int `json:"vinses"` -} - -type AccountCompute struct { - AccountId int `json:"accountId"` - AccountName string `json:"accountName"` - CPUs int `json:"cpus"` - CreatedBy string `json:"createdBy"` - CreatedTime int `json:"createdTime"` - DeletedBy string `json:"deletedBy"` - DeletedTime int `json:"deletedTime"` - ComputeId int `json:"id"` - ComputeName string `json:"name"` - RAM int `json:"ram"` - Registered bool `json:"registered"` - RgId int `json:"rgId"` - RgName string `json:"rgName"` - Status string `json:"status"` - TechStatus string `json:"techStatus"` - TotalDisksSize int `json:"totalDisksSize"` - UpdatedBy string `json:"updatedBy"` - UpdatedTime int `json:"updatedTime"` - UserManaged bool `json:"userManaged"` - VinsConnected int `json:"vinsConnected"` -} - -type AccountComputesList []AccountCompute - -type AccountDisk struct { - ID int `json:"id"` - Name string `json:"name"` - Pool string `json:"pool"` - SepId int `json:"sepId"` - SizeMax int `json:"sizeMax"` - Type string `json:"type"` -} - -type AccountDisksList []AccountDisk - -type AccountVin struct { - AccountId int `json:"accountId"` - AccountName string `json:"accountName"` - Computes int `json:"computes"` - CreatedBy string `json:"createdBy"` - CreatedTime int `json:"createdTime"` - DeletedBy string `json:"deletedBy"` - DeletedTime int `json:"deletedTime"` - ExternalIP string `json:"externalIP"` - ID int `json:"id"` - Name string `json:"name"` - Network string `json:"network"` - PriVnfDevId int `json:"priVnfDevId"` - RgId int `json:"rgId"` - RgName string `json:"rgName"` - Status string `json:"status"` - UpdatedBy string `json:"updatedBy"` - UpdatedTime int `json:"updatedTime"` -} - -type AccountVinsList []AccountVin - -type AccountAudit struct { - Call string `json:"call"` - ResponseTime float64 `json:"responsetime"` - StatusCode int `json:"statuscode"` - Timestamp float64 `json:"timestamp"` - User string `json:"user"` -} - -type AccountAuditsList []AccountAudit - -type AccountRGComputes struct { - Started int `json:"Started"` - Stopped int `json:"Stopped"` -} - -type AccountRGResources struct { - Consumed Resource `json:"Consumed"` - Limits Resource `json:"Limits"` - Reserved Resource `json:"Reserved"` -} - -type AccountRG struct { - Computes AccountRGComputes `json:"Computes"` - Resources AccountRGResources `json:"Resources"` - CreatedBy string `json:"createdBy"` - CreatedTime int `json:"createdTime"` - DeletedBy string `json:"deletedBy"` - DeletedTime int `json:"deletedTime"` - RGID int `json:"id"` - Milestones int `json:"milestones"` - RGName string `json:"name"` - Status string `json:"status"` - UpdatedBy string `json:"updatedBy"` - UpdatedTime int `json:"updatedTime"` - Vinses int `json:"vinses"` -} - -type AccountRGList []AccountRG - -type AccountTemplate struct { - UNCPath string `json:"UNCPath"` - AccountId int `json:"accountId"` - Desc string `json:"desc"` - ID int `json:"id"` - Name string `json:"name"` - Public bool `json:"public"` - Size int `json:"size"` - Status string `json:"status"` - Type string `json:"type"` - Username string `json:"username"` -} - -type AccountTemplatesList []AccountTemplate - -type AccountFlipGroup struct { - AccountId int `json:"accountId"` - ClientType string `json:"clientType"` - ConnType string `json:"connType"` - CreatedBy string `json:"createdBy"` - CreatedTime int `json:"createdTime"` - DefaultGW string `json:"defaultGW"` - DeletedBy string `json:"deletedBy"` - DeletedTime int `json:"deletedTime"` - Desc string `json:"desc"` - GID int `json:"gid"` - GUID int `json:"guid"` - ID int `json:"id"` - IP string `json:"ip"` - Milestones int `json:"milestones"` - Name string `json:"name"` - NetID int `json:"netId"` - NetType string `json:"netType"` - NetMask int `json:"netmask"` - Status string `json:"status"` - UpdatedBy string `json:"updatedBy"` - UpdatedTime int `json:"updatedTime"` -} - -type AccountFlipGroupsList []AccountFlipGroup - -//////////////////// -//// BSERVICE //// -//////////////////// - -const bserviceCreateAPI = "/restmachine/cloudapi/bservice/create" -const bserviceDeleteAPI = "/restmachine/cloudapi/bservice/delete" -const bserviceDisableAPI = "/restmachine/cloudapi/bservice/disable" -const bserviceEnableAPI = "/restmachine/cloudapi/bservice/enable" -const bserviceGetAPI = "/restmachine/cloudapi/bservice/get" -const bserviceGroupAddAPI = "/restmachine/cloudapi/bservice/groupAdd" -const bserviceGroupComputeRemoveAPI = "/restmachine/cloudapi/bservice/groupComputeRemove" -const bserviceGroupGetAPI = "/restmachine/cloudapi/bservice/groupGet" -const bserviceGroupParentAddAPI = "/restmachine/cloudapi/bservice/groupParentAdd" -const bserviceGroupParentRemoveAPI = "/restmachine/cloudapi/bservice/groupParentRemove" -const bserviceGroupRemoveAPI = "/restmachine/cloudapi/bservice/groupRemove" -const bserviceGroupResizeAPI = "/restmachine/cloudapi/bservice/groupResize" -const bserviceGroupStartAPI = "/restmachine/cloudapi/bservice/groupStart" -const bserviceGroupStopAPI = "/restmachine/cloudapi/bservice/groupStop" -const bserviceGroupUpdateAPI = "/restmachine/cloudapi/bservice/groupUpdate" -const bserviceGroupUpdateExtnetAPI = "/restmachine/cloudapi/bservice/groupUpdateExtnet" -const bserviceGroupUpdateVinsAPI = "/restmachine/cloudapi/bservice/groupUpdateVins" -const bserviceListAPI = "/restmachine/cloudapi/bservice/list" -const bserviceListDeletedAPI = "/restmachine/cloudapi/bservice/listDeleted" -const bserviceRestoreAPI = "/restmachine/cloudapi/bservice/restore" -const bserviceSnapshotCreateAPI = "/restmachine/cloudapi/bservice/snapshotCreate" -const bserviceSnapshotDeleteAPI = "/restmachine/cloudapi/bservice/snapshotDelete" -const bserviceSnapshotListAPI = "/restmachine/cloudapi/bservice/snapshotList" -const bserviceSnapshotRollbackAPI = "/restmachine/cloudapi/bservice/snapshotRollback" -const bserviceStartAPI = "/restmachine/cloudapi/bservice/start" -const bserviceStopAPI = "/restmachine/cloudapi/bservice/stop" - -///Structs - -type BasicServiceCompute struct { - CompGroupId int `json:"compgroupId"` - CompGroupName string `json:"compgroupName"` - CompGroupRole string `json:"compgroupRole"` - ID int `json:"id"` - Name string `json:"name"` -} - -type BasicServiceComputes []BasicServiceCompute - -type BasicServiceSnapshot struct { - GUID string `json:"guid"` - Label string `json:"label"` - Timestamp int `json:"timestamp"` - Valid bool `json:"valid"` -} - -type BasicServiceSnapshots []BasicServiceSnapshot - -type BasicService struct { - AccountId int `json:"accountId"` - AccountName string `json:"accountName"` - BaseDomain string `json:"baseDomain"` - - CreatedBy string `json:"createdBy"` - CreatedTime int `json:"createdTime"` - DeletedBy string `json:"deletedBy"` - DeletedTime int `json:"deletedTime"` - GID int `json:"gid"` - Groups []int `json:"groups"` - GUID int `json:"guid"` - ID int `json:"id"` - Name string `json:"name"` - ParentSrvId int `json:"parentSrvId"` - ParentSrvType string `json:"parentSrvType"` - RGID int `json:"rgId"` - RGName string `json:"rgName"` - SSHUser string `json:"sshUser"` - Status string `json:"status"` - TechStatus string `json:"techStatus"` - UpdatedBy string `json:"updatedBy"` - UpdatedTime int `json:"updatedTime"` - UserManaged bool `json:"userManaged"` -} - -type BasicServiceList []BasicService - -type BasicServiceExtend struct { - BasicService - Computes BasicServiceComputes `json:"computes"` - CPUTotal int `json:"cpuTotal"` - DiskTotal int `json:"diskTotal"` - GroupsName []string `json:"groupsName"` - Milestones int `json:"milestones"` - RamTotal int `json:"ramTotal"` - Snapshots BasicServiceSnapshots `json:"snapshots"` - SSHKey string `json:"sshKey"` -} - -type BasicServiceGroupOSUser struct { - Login string `json:"login"` - Password string `json:"password"` -} - -type BasicServiceGroupOSUsers []BasicServiceGroupOSUser - -type BasicServicceGroupCompute struct { - ID int `json:"id"` - IPAdresses []string `json:"ipAddresses"` - Name string `json:"name"` - OSUsers BasicServiceGroupOSUsers `json:"osUsers"` -} - -type BasicServiceGroupComputes []BasicServicceGroupCompute - -type BasicServiceGroup struct { - AccountId int `json:"accountId"` - AccountName string `json:"accountName"` - Computes BasicServiceGroupComputes `json:"computes"` - Consistency bool `json:"consistency"` - CPU int `json:"cpu"` - CreatedBy string `json:"createdBy"` - CreatedTime int `json:"createdTime"` - DeletedBy string `json:"deletedBy"` - DeletedTime int `json:"deletedTime"` - Disk int `json:"disk"` - Driver string `json:"driver"` - Extnets []int `json:"extnets"` - GID int `json:"gid"` - GUID int `json:"guid"` - ID int `json:"id"` - ImageId int `json:"imageId"` - Milestones int `json:"milestones"` - Name string `json:"name"` - Parents []int `json:"parents"` - RAM int `json:"ram"` - RGID int `json:"rgId"` - RGName string `json:"rgName"` - Role string `json:"role"` - SepId int `json:"sepId"` - SeqNo int `json:"seqNo"` - ServiceId int `json:"serviceId"` - Status string `json:"status"` - TechStatus string `json:"techStatus"` - TimeoutStart int `json:"timeoutStart"` - UpdatedBy string `json:"updatedBy"` - UpdatedTime int `json:"updatedTime"` - Vinses []int `json:"vinses"` -} - -/////////////////// -///// EXTNET ///// -/////////////////// - -const extnetListAPI = "/restmachine/cloudapi/extnet/list" -const extnetListComputesAPI = "/restmachine/cloudapi/extnet/listComputes" -const extnetGetDefaultAPI = "/restmachine/cloudapi/extnet/getDefault" -const extnetGetAPI = "/restmachine/cloudapi/extnet/get" - -type Extnet struct { - ID int `json:"id"` - IPCidr string `json:"ipcidr"` - Name string `json:"name"` -} -type ExtnetExtend struct { - Extnet - IPAddr string `json:"ipaddr"` -} - -type ExtnetList []Extnet -type ExtnetExtendList []ExtnetExtend - -type ExtnetComputes struct { - AccountId int `json:"accountId"` - AccountName string `json:"accountName"` - Extnets ExtnetExtendList `json:"extnets"` - ID int `json:"id"` - Name string `json:"name"` - RGID int `json:"rgId"` - RGName string `json:"rgName"` -} - -type ExtnetComputesList []ExtnetComputes - -type ExtnetQos struct { - ERate int `json:"eRate"` - GUID string `json:"guid"` - InBurst int `json:"inBurst"` - InRate int `json:"inRate"` -} - -type ExtnetReservation struct { - ClientType string `json:"clientType"` - Desc string `json:"desc"` - DomainName string `json:"domainname"` - HostName string `json:"hostname"` - IP string `json:"ip"` - MAC string `json:"mac"` - Type string `json:"type"` - VMID int `json:"vmId"` -} - -type ExtnetReservations []ExtnetReservation - -type ExtnetVNFS struct { - DHCP int `json:"dhcp"` -} - -type ExtnetDetailed struct { - CKey string `json:"_ckey"` - Meta []interface{} `json:"_meta"` - CheckIPs []string `json:"checkIPs"` - CheckIps []string `json:"checkIps"` - Default bool `json:"default"` - DefaultQos ExtnetQos `json:"defaultQos"` - Desc string `json:"desc"` - Dns []string `json:"dns"` - Excluded []string `json:"excluded"` - FreeIps int `json:"free_ips"` - Gateway string `json:"gateway"` - GID int `json:"gid"` - GUID int `json:"guid"` - ID int `json:"id"` - IPCidr string `json:"ipcidr"` - Milestones int `json:"milestones"` - Name string `json:"name"` - Network string `json:"network"` - NetworkId int `json:"networkId"` - PreReservationsNum int `json:"preReservationsNum"` - Prefix int `json:"prefix"` - PriVnfDevId int `json:"priVnfDevId"` - Reservations ExtnetReservations `json:"reservations"` - SharedWith []int `json:"sharedWith"` - Status string `json:"status"` - VlanID int `json:"vlanId"` - VNFS ExtnetVNFS `json:"vnfs"` -} - -////////////// -//// VINS //// -////////////// - -const vinsListAPI = "/restmachine/cloudapi/vins/list" - -type Vins struct { - AccountId int `json:"accountId"` - AccountName string `json:"accountName"` - CreatedBy string `json:"createdBy"` - CreatedTime int `json:"createdTime"` - DeletedBy string `json:"deletedBy"` - DeletedTime int `json:"deletedTime"` - ExternalIP string `json:"externalIP"` - ID int `json:"id"` - Name string `json:"name"` - Network string `json:"network"` - RGID int `json:"rgId"` - RGName string `json:"rgName"` - Status string `json:"status"` - UpdatedBy string `json:"updatedBy"` - UpdatedTime int `json:"updatedTime"` - VXLanID int `json:"vxlanId"` -} - -type VinsList []Vins diff --git a/decort/provider.go b/decort/provider.go deleted file mode 100644 index 1f47cbc..0000000 --- a/decort/provider.go +++ /dev/null @@ -1,196 +0,0 @@ -/* -Copyright (c) 2019-2021 Digital Energy Cloud Solutions LLC. All Rights Reserved. -Author: Sergey Shubin, , - -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. -*/ - -package decort - -import ( - "fmt" - "strings" - - "github.com/hashicorp/terraform-plugin-sdk/helper/schema" - "github.com/hashicorp/terraform-plugin-sdk/helper/validation" - // "github.com/hashicorp/terraform-plugin-sdk/terraform" -) - -func Provider() *schema.Provider { - return &schema.Provider{ - Schema: map[string]*schema.Schema{ - "authenticator": { - Type: schema.TypeString, - Required: true, - StateFunc: stateFuncToLower, - ValidateFunc: validation.StringInSlice([]string{"oauth2", "legacy", "jwt"}, true), // ignore case while validating - Description: "Authentication mode to use when connecting to DECORT cloud API. Should be one of 'oauth2', 'legacy' or 'jwt'.", - }, - - "oauth2_url": { - Type: schema.TypeString, - Optional: true, - StateFunc: stateFuncToLower, - DefaultFunc: schema.EnvDefaultFunc("DECORT_OAUTH2_URL", nil), - Description: "OAuth2 application URL in 'oauth2' authentication mode.", - }, - - "controller_url": { - Type: schema.TypeString, - Required: true, - ForceNew: true, - StateFunc: stateFuncToLower, - Description: "URL of DECORT Cloud controller to use. API calls will be directed to this URL.", - }, - - "user": { - Type: schema.TypeString, - Optional: true, - DefaultFunc: schema.EnvDefaultFunc("DECORT_USER", nil), - Description: "User name for DECORT cloud API operations in 'legacy' authentication mode.", - }, - - "password": { - Type: schema.TypeString, - Optional: true, - DefaultFunc: schema.EnvDefaultFunc("DECORT_PASSWORD", nil), - Description: "User password for DECORT cloud API operations in 'legacy' authentication mode.", - }, - - "app_id": { - Type: schema.TypeString, - Optional: true, - DefaultFunc: schema.EnvDefaultFunc("DECORT_APP_ID", nil), - Description: "Application ID to access DECORT cloud API in 'oauth2' authentication mode.", - }, - - "app_secret": { - Type: schema.TypeString, - Optional: true, - DefaultFunc: schema.EnvDefaultFunc("DECORT_APP_SECRET", nil), - Description: "Application secret to access DECORT cloud API in 'oauth2' authentication mode.", - }, - - "jwt": { - Type: schema.TypeString, - Optional: true, - DefaultFunc: schema.EnvDefaultFunc("DECORT_JWT", nil), - Description: "JWT to access DECORT cloud API in 'jwt' authentication mode.", - }, - - "allow_unverified_ssl": { - Type: schema.TypeBool, - Optional: true, - Default: false, - Description: "If true, DECORT API will not verify SSL certificates. Use this with caution and in trusted environments only!", - }, - }, - - ResourcesMap: map[string]*schema.Resource{ - "decort_resgroup": resourceResgroup(), - "decort_kvmvm": resourceCompute(), - "decort_disk": resourceDisk(), - "decort_vins": resourceVins(), - "decort_pfw": resourcePfw(), - "decort_k8s": resourceK8s(), - "decort_k8s_wg": resourceK8sWg(), - "decort_image": resourceImage(), - "decort_virtual_image": resourceVirtualImage(), - "decort_cdrom_image": resourceCDROMImage(), - "decort_delete_images": resourceDeleteImages(), - "decort_snapshot": resourceSnapshot(), - "decort_pcidevice": resourcePcidevice(), - "decort_sep": resourceSep(), - "decort_sep_config": resourceSepConfig(), - "decort_account": resourceAccount(), - "decort_bservice": resourceBasicService(), - "decort_bservice_group": resourceBasicServiceGroup(), - }, - - DataSourcesMap: map[string]*schema.Resource{ - "decort_account": dataSourceAccount(), - "decort_resgroup": dataSourceResgroup(), - "decort_kvmvm": dataSourceCompute(), - "decort_image": dataSourceImage(), - "decort_disk": dataSourceDisk(), - "decort_vins": dataSourceVins(), - "decort_grid": dataSourceGrid(), - "decort_grid_list": dataSourceGridList(), - "decort_image_list": dataSourceImageList(), - "decort_image_list_stacks": dataSourceImageListStacks(), - "decort_snapshot_list": dataSourceSnapshotList(), - "decort_vgpu": dataSourceVGPU(), - "decort_pcidevice": dataSourcePcidevice(), - "decort_pcidevice_list": dataSourcePcideviceList(), - "decort_sep_list": dataSourceSepList(), - "decort_sep": dataSourceSep(), - "decort_sep_consumption": dataSourceSepConsumption(), - "decort_sep_disk_list": dataSourceSepDiskList(), - "decort_sep_config": dataSourceSepConfig(), - "decort_sep_pool": dataSourceSepPool(), - "decort_disk_list": dataSourceDiskList(), - "decort_rg_list": dataSourceRgList(), - "decort_account_list": dataSourceAccountList(), - "decort_account_computes_list": dataSourceAccountComputesList(), - "decort_account_disks_list": dataSourceAccountDisksList(), - "decort_account_vins_list": dataSourceAccountVinsList(), - "decort_account_audits_list": dataSourceAccountAuditsList(), - "decort_account_rg_list": dataSourceAccountRGList(), - "decort_account_consumed_units": dataSourceAccountConsumedUnits(), - "decort_account_consumed_units_by_type": dataSourceAccountConsumedUnitsByType(), - "decort_account_reserved_units": dataSourceAccountReservedUnits(), - "decort_account_templates_list": dataSourceAccountTemplatessList(), - "decort_account_deleted_list": dataSourceAccountDeletedList(), - "decort_account_flipgroups_list": dataSourceAccountFlipGroupsList(), - "decort_bservice_list": dataSourceBasicServiceList(), - "decort_bservice": dataSourceBasicService(), - "decort_bservice_snapshot_list": dataSourceBasicServiceSnapshotList(), - "decort_bservice_group": dataSourceBasicServiceGroup(), - "decort_bservice_deleted_list": dataSourceBasicServiceDeletedList(), - "decort_extnet_list": dataSourceExtnetList(), - "decort_extnet_computes_list": dataSourceExtnetComputesList(), - "decort_extnet": dataSourceExtnet(), - "decort_extnet_default": dataSourceExtnetDefault(), - "decort_vins_list": dataSourceVinsList(), - // "decort_pfw": dataSourcePfw(), - }, - - ConfigureFunc: providerConfigure, - } -} - -func stateFuncToLower(argval interface{}) string { - return strings.ToLower(argval.(string)) -} - -func stateFuncToUpper(argval interface{}) string { - return strings.ToUpper(argval.(string)) -} - -func providerConfigure(d *schema.ResourceData) (interface{}, error) { - decsController, err := ControllerConfigure(d) - if err != nil { - return nil, err - } - - // initialize global default Grid ID - it will be needed to create some resource types, e.g. disks - gridId, err := decsController.utilityLocationGetDefaultGridID() - if err != nil { - return nil, err - } - if gridId == 0 { - return nil, fmt.Errorf("providerConfigure: invalid default Grid ID = 0") - } - - return decsController, nil -} diff --git a/go.mod b/go.mod index 6221e3f..8663324 100644 --- a/go.mod +++ b/go.mod @@ -6,6 +6,6 @@ require ( github.com/dgrijalva/jwt-go v3.2.0+incompatible github.com/google/uuid v1.3.0 github.com/hashicorp/terraform-plugin-docs v0.5.1 - github.com/hashicorp/terraform-plugin-sdk v1.16.0 + github.com/hashicorp/terraform-plugin-sdk/v2 v2.17.0 // indirect github.com/sirupsen/logrus v1.7.0 ) diff --git a/go.sum b/go.sum index b3d57c6..66dcc19 100644 --- a/go.sum +++ b/go.sum @@ -55,13 +55,17 @@ github.com/alcortesm/tgz v0.0.0-20161220082320-9c5fe88206d7/go.mod h1:6zEj6s6u/g github.com/andybalholm/crlf v0.0.0-20171020200849-670099aa064f/go.mod h1:k8feO4+kXDxro6ErPXBRTJ/ro2mf0SsFG8s7doP9kJE= github.com/anmitsu/go-shlex v0.0.0-20161002113705-648efa622239 h1:kFOfPq6dUM1hTo4JG6LR5AXSUEsOjtdm0kw0FtQtMJA= github.com/anmitsu/go-shlex v0.0.0-20161002113705-648efa622239/go.mod h1:2FmKhYUyUczH0OGQWaF5ceTx0UBShxjsH6f8oGKYe2c= +github.com/antihax/optional v1.0.0/go.mod h1:uupD/76wgC+ih3iEmQUL+0Ugr19nfwCT1kdvxnR2qWY= github.com/apparentlymart/go-cidr v1.0.1 h1:NmIwLZ/KdsjIUlhf+/Np40atNXm/+lZ5txfTJ/SpF+U= github.com/apparentlymart/go-cidr v1.0.1/go.mod h1:EBcsNrHc3zQeuaeCeCtQruQm+n9/YjEn/vI25Lg7Gwc= +github.com/apparentlymart/go-cidr v1.1.0 h1:2mAhrMoF+nhXqxTzSZMUzDHkLjmIHC+Zzn4tdgBZjnU= +github.com/apparentlymart/go-cidr v1.1.0/go.mod h1:EBcsNrHc3zQeuaeCeCtQruQm+n9/YjEn/vI25Lg7Gwc= github.com/apparentlymart/go-dump v0.0.0-20180507223929-23540a00eaa3/go.mod h1:oL81AME2rN47vu18xqj1S1jPIPuN7afo62yKTNn3XMM= github.com/apparentlymart/go-dump v0.0.0-20190214190832-042adf3cf4a0 h1:MzVXffFUye+ZcSR6opIgz9Co7WcDx6ZcY+RjfFHoA0I= github.com/apparentlymart/go-dump v0.0.0-20190214190832-042adf3cf4a0/go.mod h1:oL81AME2rN47vu18xqj1S1jPIPuN7afo62yKTNn3XMM= github.com/apparentlymart/go-textseg v1.0.0 h1:rRmlIsPEEhUTIKQb7T++Nz/A5Q6C9IuX2wFoYVvnCs0= github.com/apparentlymart/go-textseg v1.0.0/go.mod h1:z96Txxhf3xSFMPmb5X/1W05FF/Nj9VFpLOpjS5yuumk= +github.com/apparentlymart/go-textseg/v12 v12.0.0/go.mod h1:S/4uRK2UtaQttw1GenVJEynmyUenKwP++x/+DdGV/Ec= github.com/apparentlymart/go-textseg/v13 v13.0.0 h1:Y+KvPE1NYz0xl601PVImeQfFyEy6iT90AvPUL1NNfNw= github.com/apparentlymart/go-textseg/v13 v13.0.0/go.mod h1:ZK2fH7c4NqDTLtiYLvIkEghdlcqw7yxLeM89kiTRPUo= github.com/armon/go-radix v0.0.0-20180808171621-7fddfc383310/go.mod h1:ufUuZ+zHj4x4TnLV4JWEpy2hxWSpsRywHrMgIH9cCH8= @@ -77,12 +81,18 @@ github.com/bgentry/go-netrc v0.0.0-20140422174119-9fd32a8b3d3d/go.mod h1:6QX/PXZ github.com/bgentry/speakeasy v0.1.0 h1:ByYyxL9InA1OWqxJqqp2A5pYHUrCiAL6K3J+LKSsQkY= github.com/bgentry/speakeasy v0.1.0/go.mod h1:+zsyZBPWlz7T6j88CTgSN5bM796AkVf0kBD4zp0CCIs= github.com/census-instrumentation/opencensus-proto v0.2.1/go.mod h1:f6KPmirojxKA12rnyqOA5BBL4O983OfeGPqjHWSTneU= +github.com/cespare/xxhash/v2 v2.1.1/go.mod h1:VGX0DQ3Q6kWi7AoAeZDth3/j3BFtOZR5XLFGgcrjCOs= github.com/cheggaaa/pb v1.0.27/go.mod h1:pQciLPpbU0oxA0h+VJYYLxO+XeDQb5pZijXscXHm81s= github.com/chzyer/logex v1.1.10/go.mod h1:+Ywpsq7O8HXn0nuIou7OrIPyXbp3wmkHB+jjWRnGsAI= github.com/chzyer/readline v0.0.0-20180603132655-2972be24d48e/go.mod h1:nSuG5e5PlCu98SY8svDHJxuZscDgtXS6KTTbou5AhLI= github.com/chzyer/test v0.0.0-20180213035817-a1ea475d72b1/go.mod h1:Q3SI9o4m/ZMnBNeIyt5eFwwo7qiLfzFZmjNmxjkiQlU= github.com/client9/misspell v0.3.4/go.mod h1:qj6jICC3Q7zFZvVWo7KLAzC3yx5G7kyvSDkc90ppPyw= github.com/cncf/udpa/go v0.0.0-20191209042840-269d4d468f6f/go.mod h1:M8M6+tZqaGXZJjfX53e64911xZQV5JYwmTeXPW+k8Sc= +github.com/cncf/udpa/go v0.0.0-20201120205902-5459f2c99403/go.mod h1:WmhPx2Nbnhtbo57+VJT5O0JRkEi1Wbu0z5j0R8u5Hbk= +github.com/cncf/udpa/go v0.0.0-20210930031921-04548b0d99d4/go.mod h1:6pvJx4me5XPnfI9Z40ddWsdw2W/uZgQLFXToKeRcDiI= +github.com/cncf/xds/go v0.0.0-20210922020428-25de7278fc84/go.mod h1:eXthEFrGJvWHgFFCl3hGmgk+/aYT6PnTQLykKQRLhEs= +github.com/cncf/xds/go v0.0.0-20211001041855-01bcc9b48dfe/go.mod h1:eXthEFrGJvWHgFFCl3hGmgk+/aYT6PnTQLykKQRLhEs= +github.com/cncf/xds/go v0.0.0-20211011173535-cb28da3451f1/go.mod h1:eXthEFrGJvWHgFFCl3hGmgk+/aYT6PnTQLykKQRLhEs= github.com/creack/pty v1.1.9/go.mod h1:oKZEueFk5CKHvIhNR5MUki03XCEU+Q6VDXinZuGJ33E= github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c= @@ -94,11 +104,14 @@ github.com/emirpasic/gods v1.12.0/go.mod h1:YfzfFFoVP/catgzJb4IKIqXjX78Ha8FMSDh3 github.com/envoyproxy/go-control-plane v0.9.0/go.mod h1:YTl/9mNaCwkRvm6d1a2C3ymFceY/DCBVvsKhRF0iEA4= github.com/envoyproxy/go-control-plane v0.9.1-0.20191026205805-5f8ba28d4473/go.mod h1:YTl/9mNaCwkRvm6d1a2C3ymFceY/DCBVvsKhRF0iEA4= github.com/envoyproxy/go-control-plane v0.9.4/go.mod h1:6rpuAdCZL397s3pYoYcLgu1mIlRU8Am5FuJP05cCM98= +github.com/envoyproxy/go-control-plane v0.9.9-0.20201210154907-fd9021fe5dad/go.mod h1:cXg6YxExXjJnVBQHBLXeUAgxn2UodCpnH306RInaBQk= +github.com/envoyproxy/go-control-plane v0.10.2-0.20220325020618-49ff273808a1/go.mod h1:KJwIaB5Mv44NWtYuAOFCVOjcI94vtpEz2JU/D2v6IjE= github.com/envoyproxy/protoc-gen-validate v0.1.0/go.mod h1:iSmxcyjqTsJpI2R4NaDN7+kN2VEUnK/pcBlmesArF7c= github.com/fatih/color v1.7.0 h1:DkWD4oS2D8LGGgTQ6IvwJJXSL5Vp2ffcQg58nFV38Ys= github.com/fatih/color v1.7.0/go.mod h1:Zm6kSWBoL9eyXnKyktHP6abPY2pDugNf5KwzbycvMj4= github.com/flynn/go-shlex v0.0.0-20150515145356-3f9db97f8568 h1:BHsljHzVlRcyQhjrss6TZTdY2VfCqZPbv5k3iBFa2ZQ= github.com/flynn/go-shlex v0.0.0-20150515145356-3f9db97f8568/go.mod h1:xEzjJPgXI435gkrCt3MPfRiAkVrwSbHsst4LCFVfpJc= +github.com/ghodss/yaml v1.0.0/go.mod h1:4dBDuWmgqj2HViK6kFavaiC9ZROes6MMH2rRYeMEF04= github.com/gliderlabs/ssh v0.2.2 h1:6zsha5zo/TWhRhwqCD3+EarCAgZ2yN28ipRnGPnwkI0= github.com/gliderlabs/ssh v0.2.2/go.mod h1:U7qILu1NlMHj9FlMhZLlkCdDnU1DBEAqr0aevW3Awn0= github.com/go-git/gcfg v1.5.0 h1:Q5ViNfGF8zFgyJWPqYwA7qGFoMTEiBmdlkcfRmpIMa4= @@ -145,6 +158,10 @@ github.com/golang/protobuf v1.4.0/go.mod h1:jodUvKwWbYaEsadDk5Fwe5c77LiNKVO9IDvq github.com/golang/protobuf v1.4.1/go.mod h1:U8fpvMrcmy5pZrNK1lt4xCsGvpyWQ/VVv6QDs8UjoX8= github.com/golang/protobuf v1.4.2 h1:+Z5KGCizgyZCbGh1KZqA0fcLLkwbsjIzS4aV2v7wJX0= github.com/golang/protobuf v1.4.2/go.mod h1:oDoupMAO8OvCJWAcko0GGGIgR6R6ocIYbsSw735rRwI= +github.com/golang/protobuf v1.4.3/go.mod h1:oDoupMAO8OvCJWAcko0GGGIgR6R6ocIYbsSw735rRwI= +github.com/golang/protobuf v1.5.0/go.mod h1:FsONVRAS9T7sI+LIUmWTfcYkHO4aIWwzhcaSAoJOfIk= +github.com/golang/protobuf v1.5.2 h1:ROPKBNFfQgOUMifHyP+KYbvpjbdoFNs+aK7DXlji0Tw= +github.com/golang/protobuf v1.5.2/go.mod h1:XVQd3VNwM+JqD3oG2Ue2ip4fOMUkwXdXDdiuN0vRsmY= github.com/golang/snappy v0.0.1/go.mod h1:/XxbfmMg8lxefKM7IXC3fBNl/7bRcc72aCRzEWrmP2Q= github.com/google/btree v0.0.0-20180813153112-4030bb1f1f0c/go.mod h1:lNA+9X1NB3Zf8V7Ke586lFgjr2dZNuvo3lPJSGZ5JPQ= github.com/google/btree v1.0.0/go.mod h1:lNA+9X1NB3Zf8V7Ke586lFgjr2dZNuvo3lPJSGZ5JPQ= @@ -154,8 +171,12 @@ github.com/google/go-cmp v0.3.1/go.mod h1:8QqcDgzrUqlUb/G2PQTWiueGozuR1884gddMyw github.com/google/go-cmp v0.4.0/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/gNBxE= github.com/google/go-cmp v0.4.1/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/gNBxE= github.com/google/go-cmp v0.5.0/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/gNBxE= +github.com/google/go-cmp v0.5.5/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/gNBxE= github.com/google/go-cmp v0.5.6 h1:BKbKCqvP6I+rmFHt06ZmyQtvB8xAkWdhFyr0ZUNZcxQ= github.com/google/go-cmp v0.5.6/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/gNBxE= +github.com/google/go-cmp v0.5.7/go.mod h1:n+brtR0CgQNWTVd5ZUFpTBC8YFBDLK/h/bpaJ8/DtOE= +github.com/google/go-cmp v0.5.8 h1:e6P7q2lk1O+qJJb4BtCQXlK8vWEO8V1ZeuEdJNOqZyg= +github.com/google/go-cmp v0.5.8/go.mod h1:17dUlkBOakJ0+DkrSSNjCkIjxS6bF9zb3elmeNGIjoY= github.com/google/martian v2.1.0+incompatible h1:/CP5g8u/VJHijgedC/Legn3BAbAaWPgecwXBIDzw5no= github.com/google/martian v2.1.0+incompatible/go.mod h1:9I4somxYTbIHy5NJKHRl3wXiIaQGbYVAs8BPL6v8lEs= github.com/google/martian/v3 v3.0.0 h1:pMen7vLs8nvgEYhywH3KDWJIJTeEr2ULsVWHWYHQyBs= @@ -175,6 +196,7 @@ github.com/google/uuid v1.3.0/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+ github.com/googleapis/gax-go/v2 v2.0.4/go.mod h1:0Wqv26UfaUD9n4G6kQubkQ+KchISgw+vpHVxEJEs9eg= github.com/googleapis/gax-go/v2 v2.0.5 h1:sjZBwGj9Jlw33ImPtvFviGYvseOtDM7hkSKB7+Tv3SM= github.com/googleapis/gax-go/v2 v2.0.5/go.mod h1:DWXyrwAJ9X0FpwwEdw+IPEYBICEFu5mhpdKc/us6bOk= +github.com/grpc-ecosystem/grpc-gateway v1.16.0/go.mod h1:BDjrQk3hbvj6Nolgz8mAMFbcEtjT1g+wF4CSlocrBnw= github.com/hashicorp/errwrap v1.0.0 h1:hLrqtEDnRye3+sgx6z4qVLNuviH3MR5aQ0ykNJa/UYA= github.com/hashicorp/errwrap v1.0.0/go.mod h1:YH+1FKiLXxHSkmPseP+kNlulaMuP3n2brvKWEqk/Jc4= github.com/hashicorp/go-checkpoint v0.5.0 h1:MFYpPZCnQqQTE18jFwSII6eUQrD/oxMFp3mlgcqk5mU= @@ -183,6 +205,8 @@ github.com/hashicorp/go-cleanhttp v0.5.0/go.mod h1:JpRdi6/HCYpAwUzNwuwqhbovhLtng github.com/hashicorp/go-cleanhttp v0.5.1/go.mod h1:JpRdi6/HCYpAwUzNwuwqhbovhLtngrth3wmdIIUrZ80= github.com/hashicorp/go-cleanhttp v0.5.2 h1:035FKYIWjmULyFRBKPs8TBQoi0x6d9G4xc9neXJWAZQ= github.com/hashicorp/go-cleanhttp v0.5.2/go.mod h1:kO/YDlP8L1346E6Sodw+PrpBSV4/SoxCXGY6BqNFT48= +github.com/hashicorp/go-cty v1.4.1-0.20200414143053-d3edf31b6320 h1:1/D3zfFHttUKaCaGKZ/dR2roBXv0vKbSCnssIldfQdI= +github.com/hashicorp/go-cty v1.4.1-0.20200414143053-d3edf31b6320/go.mod h1:EiZBMaudVLy8fmjf9Npq1dq9RalhveqZG5w/yz3mHWs= github.com/hashicorp/go-getter v1.4.0/go.mod h1:7qxyCd8rBfcShwsvxgIguu4KbS3l8bUCwg2Umn7RjeY= github.com/hashicorp/go-getter v1.4.2-0.20200106182914-9813cbd4eb02/go.mod h1:7qxyCd8rBfcShwsvxgIguu4KbS3l8bUCwg2Umn7RjeY= github.com/hashicorp/go-getter v1.5.3 h1:NF5+zOlQegim+w/EUhSLh6QhXHmZMEeHLQzllkQ3ROU= @@ -190,27 +214,43 @@ github.com/hashicorp/go-getter v1.5.3/go.mod h1:BrrV/1clo8cCYu6mxvboYg+KutTiFnXj github.com/hashicorp/go-hclog v0.0.0-20180709165350-ff2cf002a8dd/go.mod h1:9bjs9uLqI8l75knNv3lV1kA55veR+WUPSiKIWcQHudI= github.com/hashicorp/go-hclog v0.9.2 h1:CG6TE5H9/JXsFWJCfoIVpKFIkFe6ysEuHirp4DxCsHI= github.com/hashicorp/go-hclog v0.9.2/go.mod h1:5CU+agLiy3J7N7QjHK5d05KxGsuXiQLrjA0H7acj2lQ= +github.com/hashicorp/go-hclog v0.14.1/go.mod h1:whpDNt7SSdeAju8AWKIWsul05p54N/39EeqMAyrmvFQ= +github.com/hashicorp/go-hclog v1.2.0 h1:La19f8d7WIlm4ogzNHB0JGqs5AUDAZ2UfCY4sJXcJdM= +github.com/hashicorp/go-hclog v1.2.0/go.mod h1:whpDNt7SSdeAju8AWKIWsul05p54N/39EeqMAyrmvFQ= github.com/hashicorp/go-multierror v1.0.0 h1:iVjPR7a6H0tWELX5NxNe7bYopibicUzc7uPribsnS6o= github.com/hashicorp/go-multierror v1.0.0/go.mod h1:dHtQlpGsu+cZNNAkkCN/P3hoUDHhCYQXV3UM06sGGrk= +github.com/hashicorp/go-multierror v1.1.1 h1:H5DkEtf6CXdFp0N0Em5UCwQpXMWke8IA0+lD48awMYo= +github.com/hashicorp/go-multierror v1.1.1/go.mod h1:iw975J/qwKPdAO1clOe2L8331t/9/fmwbPZ6JB6eMoM= github.com/hashicorp/go-plugin v1.3.0 h1:4d/wJojzvHV1I4i/rrjVaeuyxWrLzDE1mDCyDy8fXS8= github.com/hashicorp/go-plugin v1.3.0/go.mod h1:F9eH4LrE/ZsRdbwhfjs9k9HoDUwAHnYtXdgmf1AVNs0= +github.com/hashicorp/go-plugin v1.4.4 h1:NVdrSdFRt3SkZtNckJ6tog7gbpRrcbOjQi/rgF7JYWQ= +github.com/hashicorp/go-plugin v1.4.4/go.mod h1:viDMjcLJuDui6pXb8U4HVfb8AamCWhHGUjr2IrTF67s= github.com/hashicorp/go-safetemp v1.0.0 h1:2HR189eFNrjHQyENnQMMpCiBAsRxzbTMIgBhEyExpmo= github.com/hashicorp/go-safetemp v1.0.0/go.mod h1:oaerMy3BhqiTbVye6QuFhFtIceqFoDHxNAB65b+Rj1I= github.com/hashicorp/go-uuid v1.0.0/go.mod h1:6SBZvOh/SIDV7/2o3Jml5SYk/TvGqwFJ/bN7x4byOro= github.com/hashicorp/go-uuid v1.0.1 h1:fv1ep09latC32wFoVwnqcnKJGnMSdBanPczbHAYm1BE= github.com/hashicorp/go-uuid v1.0.1/go.mod h1:6SBZvOh/SIDV7/2o3Jml5SYk/TvGqwFJ/bN7x4byOro= +github.com/hashicorp/go-uuid v1.0.3 h1:2gKiV6YVmrJ1i2CKKa9obLvRieoRGviZFL26PcT/Co8= +github.com/hashicorp/go-uuid v1.0.3/go.mod h1:6SBZvOh/SIDV7/2o3Jml5SYk/TvGqwFJ/bN7x4byOro= github.com/hashicorp/go-version v1.1.0/go.mod h1:fltr4n8CU8Ke44wwGCBoEymUuxUHl09ZGVZPK5anwXA= github.com/hashicorp/go-version v1.2.0/go.mod h1:fltr4n8CU8Ke44wwGCBoEymUuxUHl09ZGVZPK5anwXA= github.com/hashicorp/go-version v1.2.1/go.mod h1:fltr4n8CU8Ke44wwGCBoEymUuxUHl09ZGVZPK5anwXA= github.com/hashicorp/go-version v1.3.0 h1:McDWVJIU/y+u1BRV06dPaLfLCaT7fUTJLp5r04x7iNw= github.com/hashicorp/go-version v1.3.0/go.mod h1:fltr4n8CU8Ke44wwGCBoEymUuxUHl09ZGVZPK5anwXA= +github.com/hashicorp/go-version v1.4.0/go.mod h1:fltr4n8CU8Ke44wwGCBoEymUuxUHl09ZGVZPK5anwXA= +github.com/hashicorp/go-version v1.5.0 h1:O293SZ2Eg+AAYijkVK3jR786Am1bhDEh2GHT0tIVE5E= +github.com/hashicorp/go-version v1.5.0/go.mod h1:fltr4n8CU8Ke44wwGCBoEymUuxUHl09ZGVZPK5anwXA= github.com/hashicorp/golang-lru v0.5.0/go.mod h1:/m3WP610KZHVQ1SGc6re/UDhFvYD7pJ4Ao+sR/qLZy8= github.com/hashicorp/golang-lru v0.5.1/go.mod h1:/m3WP610KZHVQ1SGc6re/UDhFvYD7pJ4Ao+sR/qLZy8= +github.com/hashicorp/hc-install v0.3.1/go.mod h1:3LCdWcCDS1gaHC9mhHCGbkYfoY6vdsKohGjugbZdZak= +github.com/hashicorp/hc-install v0.3.2/go.mod h1:xMG6Tr8Fw1WFjlxH0A9v61cW15pFwgEGqEz0V4jisHs= github.com/hashicorp/hcl v0.0.0-20170504190234-a4b07c25de5f h1:UdxlrJz4JOnY8W+DbLISwf2B8WXEolNRA8BGCwI9jws= github.com/hashicorp/hcl v0.0.0-20170504190234-a4b07c25de5f/go.mod h1:oZtUIOe8dh44I2q6ScRibXws4Ajl+d+nod3AaR9vL5w= github.com/hashicorp/hcl/v2 v2.0.0/go.mod h1:oVVDG71tEinNGYCxinCYadcmKU9bglqW9pV3txagJ90= github.com/hashicorp/hcl/v2 v2.3.0 h1:iRly8YaMwTBAKhn1Ybk7VSdzbnopghktCD031P8ggUE= github.com/hashicorp/hcl/v2 v2.3.0/go.mod h1:d+FwDBbOLvpAM3Z6J7gPj/VoAGkNe/gm352ZhjJ/Zv8= +github.com/hashicorp/hcl/v2 v2.12.0 h1:PsYxySWpMD4KPaoJLnsHwtK5Qptvj/4Q6s0t4sUxZf4= +github.com/hashicorp/hcl/v2 v2.12.0/go.mod h1:FwWsfWEjyV/CMj8s/gqAuiviY72rJ1/oayI9WftqcKg= github.com/hashicorp/logutils v1.0.0 h1:dLEQVugN8vlakKOUE3ihGLTZJRB4j+M2cdTm/ORI65Y= github.com/hashicorp/logutils v1.0.0/go.mod h1:QIAnNjmIWmVIIkWDTG1z5v++HQmx9WQRO+LraFDTW64= github.com/hashicorp/terraform-config-inspect v0.0.0-20191115094559-17f92b0546e8 h1:+RyjwU+Gnd/aTJBPZVDNm903eXVjjqhbaR4Ypx3xYyY= @@ -218,16 +258,28 @@ github.com/hashicorp/terraform-config-inspect v0.0.0-20191115094559-17f92b0546e8 github.com/hashicorp/terraform-exec v0.10.0/go.mod h1:tOT8j1J8rP05bZBGWXfMyU3HkLi1LWyqL3Bzsc3CJjo= github.com/hashicorp/terraform-exec v0.15.0 h1:cqjh4d8HYNQrDoEmlSGelHmg2DYDh5yayckvJ5bV18E= github.com/hashicorp/terraform-exec v0.15.0/go.mod h1:H4IG8ZxanU+NW0ZpDRNsvh9f0ul7C0nHP+rUR/CHs7I= +github.com/hashicorp/terraform-exec v0.16.1/go.mod h1:aj0lVshy8l+MHhFNoijNHtqTJQI3Xlowv5EOsEaGO7M= github.com/hashicorp/terraform-json v0.5.0/go.mod h1:eAbqb4w0pSlRmdvl8fOyHAi/+8jnkVYN28gJkSJrLhU= github.com/hashicorp/terraform-json v0.13.0 h1:Li9L+lKD1FO5RVFRM1mMMIBDoUHslOniyEi5CM+FWGY= github.com/hashicorp/terraform-json v0.13.0/go.mod h1:y5OdLBCT+rxbwnpxZs9kGL7R9ExU76+cpdY8zHwoazk= +github.com/hashicorp/terraform-json v0.14.0/go.mod h1:5A9HIWPkk4e5aeeXIBbkcOvaZbIYnAIkEyqP2pNSckM= github.com/hashicorp/terraform-plugin-docs v0.5.1 h1:WwrUcamix9x0TqfTw/WGHMRqoTe1QPZKaeWJPuFb4lQ= github.com/hashicorp/terraform-plugin-docs v0.5.1/go.mod h1:SQwEgy0/B0UPQ07rNEG1Wpt6E3jvRcCwkVHPNybGgc0= +github.com/hashicorp/terraform-plugin-go v0.9.1 h1:vXdHaQ6aqL+OF076nMSBV+JKPdmXlzG5mzVDD04WyPs= +github.com/hashicorp/terraform-plugin-go v0.9.1/go.mod h1:ItjVSlQs70otlzcCwlPcU8FRXLdO973oYFRZwAOxy8M= +github.com/hashicorp/terraform-plugin-log v0.4.0 h1:F3eVnm8r2EfQCe2k9blPIiF/r2TT01SHijXnS7bujvc= +github.com/hashicorp/terraform-plugin-log v0.4.0/go.mod h1:9KclxdunFownr4pIm1jdmwKRmE4d6HVG2c9XDq47rpg= github.com/hashicorp/terraform-plugin-sdk v1.16.0 h1:NrkXMRjHErUPPTHQkZ6JIn6bByiJzGnlJzH1rVdNEuE= github.com/hashicorp/terraform-plugin-sdk v1.16.0/go.mod h1:5sVxrwW6/xzFhZyql+Q9zXCUEJaGWcBIxBbZFLpVXOI= +github.com/hashicorp/terraform-plugin-sdk/v2 v2.17.0 h1:Qr5fWNg1SPSfCRMtou67Y6Kcy9UnMYRNlIJTKRuUvXU= +github.com/hashicorp/terraform-plugin-sdk/v2 v2.17.0/go.mod h1:b+LFg8WpYgFgvEBP/6Htk5H9/pJp1V1E8NJAekfH2Ws= github.com/hashicorp/terraform-plugin-test/v2 v2.1.2/go.mod h1:jerO5mrd+jVNALy8aiq+VZOg/CR8T2T1QR3jd6JKGOI= +github.com/hashicorp/terraform-registry-address v0.0.0-20210412075316-9b2996cce896 h1:1FGtlkJw87UsTMg5s8jrekrHmUPUJaMcu6ELiVhQrNw= +github.com/hashicorp/terraform-registry-address v0.0.0-20210412075316-9b2996cce896/go.mod h1:bzBPnUIkI0RxauU8Dqo+2KrZZ28Cf48s8V6IHt3p4co= github.com/hashicorp/terraform-svchost v0.0.0-20191011084731-65d371908596 h1:hjyO2JsNZUKT1ym+FAdlBEkGPevazYsmVgIMw7dVELg= github.com/hashicorp/terraform-svchost v0.0.0-20191011084731-65d371908596/go.mod h1:kNDNcF7sN4DocDLBkQYz73HGKwN1ANB1blq4lIYLYvg= +github.com/hashicorp/terraform-svchost v0.0.0-20200729002733-f050f53b9734 h1:HKLsbzeOsfXmKNpr3GiT18XAblV0BjCbzL8KQAMZGa0= +github.com/hashicorp/terraform-svchost v0.0.0-20200729002733-f050f53b9734/go.mod h1:kNDNcF7sN4DocDLBkQYz73HGKwN1ANB1blq4lIYLYvg= github.com/hashicorp/yamux v0.0.0-20180604194846-3520598351bb/go.mod h1:+NfK9FKeTrX5uv1uIXGdwYDTeHna2qgaIlx54MXqjAM= github.com/hashicorp/yamux v0.0.0-20181012175058-2f1d1f20f75d h1:kJCB4vdITiW1eC1vq2e6IsrXKrZit1bv/TDYFGMp4BQ= github.com/hashicorp/yamux v0.0.0-20181012175058-2f1d1f20f75d/go.mod h1:+NfK9FKeTrX5uv1uIXGdwYDTeHna2qgaIlx54MXqjAM= @@ -272,11 +324,14 @@ github.com/matryer/is v1.2.0 h1:92UTHpy8CDwaJ08GqLDzhhuixiBUUD1p3AU6PHddz4A= github.com/matryer/is v1.2.0/go.mod h1:2fLPjFQM9rhQ15aVEtbuwhJinnOqrmgXPNdZsdwlWXA= github.com/mattn/go-colorable v0.0.9/go.mod h1:9vuHe8Xs5qXnSaW/c/ABM9alt+Vo+STaOChaDxuIBZU= github.com/mattn/go-colorable v0.1.1/go.mod h1:FuOcm+DKB9mbwrcAfNl7/TZVBZ6rcnceauSikq3lYCQ= +github.com/mattn/go-colorable v0.1.4/go.mod h1:U0ppj6V5qS13XJ6of8GYAs25YV2eR4EVcfRqFIhoBtE= github.com/mattn/go-colorable v0.1.11 h1:nQ+aFkoE2TMGc0b68U2OKSexC+eq46+XwZzWXHRmPYs= github.com/mattn/go-colorable v0.1.11/go.mod h1:u5H1YNBxpqRaxsYJYSkiCWKzEfiAb1Gb520KVy5xxl4= github.com/mattn/go-isatty v0.0.3/go.mod h1:M+lRXTBqGeGNdLjl/ufCoiOlB5xdOkqRJdNxMWT7Zi4= github.com/mattn/go-isatty v0.0.4/go.mod h1:M+lRXTBqGeGNdLjl/ufCoiOlB5xdOkqRJdNxMWT7Zi4= github.com/mattn/go-isatty v0.0.5/go.mod h1:Iq45c/XA43vh69/j3iqttzPXn0bhXyGjM0Hdxcsrc5s= +github.com/mattn/go-isatty v0.0.8/go.mod h1:Iq45c/XA43vh69/j3iqttzPXn0bhXyGjM0Hdxcsrc5s= +github.com/mattn/go-isatty v0.0.10/go.mod h1:qgIWMr58cqv1PHHyhnkY9lrL7etaEgOFcMEpPG5Rm84= github.com/mattn/go-isatty v0.0.14 h1:yVuAays6BHfxijgZPzw+3Zlu5yQgKGP2/hcQbHb7S9Y= github.com/mattn/go-isatty v0.0.14/go.mod h1:7GGIvUiUoEMVVmxf/4nioHXj79iQHKdU27kJ6hsGG94= github.com/mattn/go-runewidth v0.0.4/go.mod h1:LwmH8dsx7+W8Uxz3IHJYH5QSwggIsqBzpuz5H//U1FU= @@ -294,16 +349,21 @@ github.com/mitchellh/go-testing-interface v0.0.0-20171004221916-a61a99592b77/go. github.com/mitchellh/go-testing-interface v1.0.0/go.mod h1:kRemZodwjscx+RGhAo8eIhFbs2+BFgRtFPeD/KE+zxI= github.com/mitchellh/go-testing-interface v1.0.4 h1:ZU1VNC02qyufSZsjjs7+khruk2fKvbQ3TwRV/IBCeFA= github.com/mitchellh/go-testing-interface v1.0.4/go.mod h1:kRemZodwjscx+RGhAo8eIhFbs2+BFgRtFPeD/KE+zxI= +github.com/mitchellh/go-testing-interface v1.14.1 h1:jrgshOhYAUVNMAJiKbEu7EqAwgJJ2JqpQmpLJOu07cU= +github.com/mitchellh/go-testing-interface v1.14.1/go.mod h1:gfgS7OtZj6MA4U1UrDRp04twqAjfvlZyCfX3sDjEym8= github.com/mitchellh/go-wordwrap v0.0.0-20150314170334-ad45545899c7/go.mod h1:ZXFpozHsX6DPmq2I0TCekCxypsnAUbP2oI0UX1GXzOo= github.com/mitchellh/go-wordwrap v1.0.0 h1:6GlHJ/LTGMrIJbwgdqdl2eEH8o+Exx/0m8ir9Gns0u4= github.com/mitchellh/go-wordwrap v1.0.0/go.mod h1:ZXFpozHsX6DPmq2I0TCekCxypsnAUbP2oI0UX1GXzOo= github.com/mitchellh/mapstructure v1.1.2 h1:fmNYVwqnSfB9mZU6OS2O6GsXM+wcskZDuKQzvN1EDeE= github.com/mitchellh/mapstructure v1.1.2/go.mod h1:FVVH3fgwuzCH5S8UJGiWEs2h04kUh9fWfEaFds41c1Y= +github.com/mitchellh/mapstructure v1.5.0 h1:jeMsZIYE/09sWLaz43PL7Gy6RuMjD2eJVyuac5Z2hdY= +github.com/mitchellh/mapstructure v1.5.0/go.mod h1:bFUtVrKA4DC2yAKiSyO/QUcy7e+RRV2QTWOzhPopBRo= github.com/mitchellh/reflectwalk v1.0.0/go.mod h1:mSTlrgnPZtwu0c4WaC2kGObEpuNDbx0jmZXqmk4esnw= github.com/mitchellh/reflectwalk v1.0.1/go.mod h1:mSTlrgnPZtwu0c4WaC2kGObEpuNDbx0jmZXqmk4esnw= github.com/mitchellh/reflectwalk v1.0.2 h1:G2LzWKi524PWgd3mLHV8Y5k7s6XUvT0Gef6zxSIeXaQ= github.com/mitchellh/reflectwalk v1.0.2/go.mod h1:mSTlrgnPZtwu0c4WaC2kGObEpuNDbx0jmZXqmk4esnw= github.com/niemeyer/pretty v0.0.0-20200227124842-a10e7caefd8e/go.mod h1:zD1mROLANZcx1PVRCS0qkT7pwLkGfwJo4zjcN/Tysno= +github.com/nsf/jsondiff v0.0.0-20200515183724-f29ed568f4ce/go.mod h1:uFMI8w+ref4v2r9jz+c9i1IfIttS/OkmLfrk1jne5hs= github.com/oklog/run v1.0.0 h1:Ru7dDtJNOyC66gQ5dQmaCa0qIsAUFY3sFpK1Xk8igrw= github.com/oklog/run v1.0.0/go.mod h1:dlhp/R75TPv97u0XWUtDeV/lRKWPKSdTuV0TZvrmrQA= github.com/pierrec/lz4 v2.0.5+incompatible/go.mod h1:pdkljMzZIN41W+lC3N2tnIh5sFi+IEE17M5jbnwPHcY= @@ -316,6 +376,7 @@ github.com/posener/complete v1.1.1/go.mod h1:em0nMJCgc9GFtwrmVmEMR/ZL6WyhyjMBndr github.com/posener/complete v1.2.1 h1:LrvDIY//XNo65Lq84G/akBuMGlawHvGBABv8f/ZN6DI= github.com/posener/complete v1.2.1/go.mod h1:6gapUrK/U1TAN7ciCoNRIdVC5sbdBTUh1DKN0g6uH7E= github.com/prometheus/client_model v0.0.0-20190812154241-14fe0d1b01d4/go.mod h1:xMI15A0UPsDsEKsMN9yxemIoYk6Tm2C1GtYGdfGttqA= +github.com/rogpeppe/fastuuid v1.2.0/go.mod h1:jVj6XXZzXRy/MSR5jhDC/2q6DgLz+nrA6LYCDYWNEvQ= github.com/rogpeppe/go-internal v1.3.0/go.mod h1:M8bDsm7K2OlrFYOpmOWEs/qY81heoFRclV5y23lUDJ4= github.com/russross/blackfriday v1.6.0 h1:KqfZb0pUVN2lYqZUYRddxF4OR8ZMURnJIG5Y3VRLtww= github.com/russross/blackfriday v1.6.0/go.mod h1:ti0ldHuxg49ri4ksnFxlkCfN+hvslNlmVHqNRXXJNAY= @@ -336,6 +397,7 @@ github.com/stretchr/objx v0.1.1/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+ github.com/stretchr/testify v1.2.2/go.mod h1:a8OnRcib4nhh0OaRAV+Yts87kKdq0PP7pXfy6kDkUVs= github.com/stretchr/testify v1.3.0/go.mod h1:M5WIy9Dh21IEIfnGCwXGc5bZfKNJtfHm1UVUgZn+9EI= github.com/stretchr/testify v1.4.0/go.mod h1:j7eGeouHqKxXV5pUuKE4zz7dFj8WfuZ+81PSLYec5m4= +github.com/stretchr/testify v1.5.1/go.mod h1:5W2xD1RspED5o8YsWQXVCued0rvSQ+mT+I5cxcmMvtA= github.com/stretchr/testify v1.6.1/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg= github.com/stretchr/testify v1.7.0 h1:nwc3DEeHmmLAfoZucVR881uASk0Mfjw8xYJ99tb5CcY= github.com/stretchr/testify v1.7.0/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg= @@ -346,6 +408,8 @@ github.com/ulikunitz/xz v0.5.8/go.mod h1:nbz6k7qbPmH4IRqmfOplQw/tblSgqTqBwxkY0oW github.com/vmihailenco/msgpack v3.3.3+incompatible/go.mod h1:fy3FlTQTDXWkZ7Bh6AcGMlsjHatGryHQYUTf1ShIgkk= github.com/vmihailenco/msgpack v4.0.1+incompatible h1:RMF1enSPeKTlXrXdOcqjFUElywVZjjC6pqse21bKbEU= github.com/vmihailenco/msgpack v4.0.1+incompatible/go.mod h1:fy3FlTQTDXWkZ7Bh6AcGMlsjHatGryHQYUTf1ShIgkk= +github.com/vmihailenco/msgpack v4.0.4+incompatible h1:dSLoQfGFAo3F6OoNhwUmLwVgaUXK79GlxNBwueZn0xI= +github.com/vmihailenco/msgpack v4.0.4+incompatible/go.mod h1:fy3FlTQTDXWkZ7Bh6AcGMlsjHatGryHQYUTf1ShIgkk= github.com/vmihailenco/msgpack/v4 v4.3.12 h1:07s4sz9IReOgdikxLTKNbBdqDMLsjPKXwvCazn8G65U= github.com/vmihailenco/msgpack/v4 v4.3.12/go.mod h1:gborTTJjAo/GWTqqRjrLCn9pgNN+NXzzngzBKDPIqw4= github.com/vmihailenco/tagparser v0.1.1 h1:quXMXlA39OCbd2wAdTsGDlK9RkOk6Wuw+x37wVyIuWY= @@ -360,6 +424,7 @@ github.com/zclconf/go-cty v1.0.0/go.mod h1:xnAOWiHeOqg2nWS62VtQ7pbOu17FtxJNW8RLE github.com/zclconf/go-cty v1.1.0/go.mod h1:xnAOWiHeOqg2nWS62VtQ7pbOu17FtxJNW8RLEih+O3s= github.com/zclconf/go-cty v1.2.0/go.mod h1:hOPWgoHbaTUnI5k4D2ld+GRpFJSCe6bCM7m1q/N4PQ8= github.com/zclconf/go-cty v1.2.1/go.mod h1:hOPWgoHbaTUnI5k4D2ld+GRpFJSCe6bCM7m1q/N4PQ8= +github.com/zclconf/go-cty v1.8.0/go.mod h1:vVKLxnk3puL4qRAv72AO+W99LUD4da90g3uUAzyuvAk= github.com/zclconf/go-cty v1.9.1/go.mod h1:vVKLxnk3puL4qRAv72AO+W99LUD4da90g3uUAzyuvAk= github.com/zclconf/go-cty v1.10.0 h1:mp9ZXQeIcN8kAwuqorjH+Q+njbJKjLrvB2yIh4q7U+0= github.com/zclconf/go-cty v1.10.0/go.mod h1:vVKLxnk3puL4qRAv72AO+W99LUD4da90g3uUAzyuvAk= @@ -372,6 +437,7 @@ go.opencensus.io v0.22.2/go.mod h1:yxeiOL68Rb0Xd1ddK5vPZ/oVn4vY4Ynel7k9FzqtOIw= go.opencensus.io v0.22.3/go.mod h1:yxeiOL68Rb0Xd1ddK5vPZ/oVn4vY4Ynel7k9FzqtOIw= go.opencensus.io v0.22.4 h1:LYy1Hy3MJdrCdMwwzxA/dRok4ejH+RwNGbuoD9fCjto= go.opencensus.io v0.22.4/go.mod h1:yxeiOL68Rb0Xd1ddK5vPZ/oVn4vY4Ynel7k9FzqtOIw= +go.opentelemetry.io/proto/otlp v0.7.0/go.mod h1:PqfVotwruBrMGOCsRd/89rSnXhoiJIqeYNgFYFoEGnI= golang.org/x/crypto v0.0.0-20190219172222-a4c6cb3142f2/go.mod h1:6SG95UA2DQfeDnfUPMdvaQW0Q7yPrPDi9nlGo2tz2b4= golang.org/x/crypto v0.0.0-20190308221718-c2843e01d9a2/go.mod h1:djNgcEr1/C05ACkg1iLfiJU5Ep61QUkGW8qpdssI0+w= golang.org/x/crypto v0.0.0-20190426145343-a29dc8fdc734/go.mod h1:yigFU9vqHzYiE8UmvKecakEJjdnWj3jj499lnFckfCI= @@ -384,6 +450,7 @@ golang.org/x/crypto v0.0.0-20200820211705-5c72a883971a/go.mod h1:LzIPMQfyMNhhGPh golang.org/x/crypto v0.0.0-20210322153248-0c34fe9e7dc2/go.mod h1:T9bdIzuCu7OtxOm1hfPfRQxPLYneinmdGuTeoZ9dtd4= golang.org/x/crypto v0.0.0-20210421170649-83a5a9bb288b h1:7mWr3k41Qtv8XlltBkDkl8LoP3mpSgBW8BUoxtEdbXg= golang.org/x/crypto v0.0.0-20210421170649-83a5a9bb288b/go.mod h1:T9bdIzuCu7OtxOm1hfPfRQxPLYneinmdGuTeoZ9dtd4= +golang.org/x/crypto v0.0.0-20210616213533-5ff15b29337e/go.mod h1:GvvjBRRGRdwPK5ydBHafDWAxML/pGHZbMvKqRZ5+Abc= golang.org/x/exp v0.0.0-20190121172915-509febef88a4/go.mod h1:CJ0aWSM057203Lf6IL+f9T1iT9GByDxfZKAQTCR3kQA= golang.org/x/exp v0.0.0-20190306152737-a1d7652674e8/go.mod h1:CJ0aWSM057203Lf6IL+f9T1iT9GByDxfZKAQTCR3kQA= golang.org/x/exp v0.0.0-20190510132918-efd6b22b2522/go.mod h1:ZjyILWgesfNpC6sMxTJOJm9Kp84zZh5NQWvqDGG3Qr8= @@ -444,6 +511,9 @@ golang.org/x/net v0.0.0-20200513185701-a91f0712d120/go.mod h1:qpuaurCH72eLCgpAm/ golang.org/x/net v0.0.0-20200520182314-0ba52f642ac2/go.mod h1:qpuaurCH72eLCgpAm/N6yyVIVM9cpaDIP3A8BGJEC5A= golang.org/x/net v0.0.0-20200625001655-4c5254603344/go.mod h1:/O7V0waA8r7cgGh81Ro3o1hOxt32SMVPicZroKQ2sZA= golang.org/x/net v0.0.0-20200707034311-ab3426394381/go.mod h1:/O7V0waA8r7cgGh81Ro3o1hOxt32SMVPicZroKQ2sZA= +golang.org/x/net v0.0.0-20200822124328-c89045814202/go.mod h1:/O7V0waA8r7cgGh81Ro3o1hOxt32SMVPicZroKQ2sZA= +golang.org/x/net v0.0.0-20201021035429-f5854403a974/go.mod h1:sp8m0HH+o8qH0wwXwYZr8TS3Oi6o0r6Gce1SSxlDquU= +golang.org/x/net v0.0.0-20210119194325-5f4716e94777/go.mod h1:m0MpNAwzfU5UDzcl9v0D8zg8gWTRqZa9RBIspLL5mdg= golang.org/x/net v0.0.0-20210226172049-e18ecbb05110/go.mod h1:m0MpNAwzfU5UDzcl9v0D8zg8gWTRqZa9RBIspLL5mdg= golang.org/x/net v0.0.0-20210326060303-6b1517762897 h1:KrsHThm5nFk34YtATK1LsThyGhGbGe1olrte/HInHvs= golang.org/x/net v0.0.0-20210326060303-6b1517762897/go.mod h1:uSPa2vr4CLtc/ILN5odXGNXS6mhrKVzTaCXzk9m6W3k= @@ -477,6 +547,7 @@ golang.org/x/sys v0.0.0-20190624142023-c5567b49c5d0/go.mod h1:h1NjWce9XRLGQEsW7w golang.org/x/sys v0.0.0-20190726091711-fc99dfbffb4e/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/sys v0.0.0-20190916202348-b4ddaad3f8a3/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/sys v0.0.0-20191001151750-bb3f8db39f24/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20191008105621-543471e840be/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/sys v0.0.0-20191026070338-33540a1f6037/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/sys v0.0.0-20191204072324-ce4227a45e2e/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/sys v0.0.0-20191228213918-04cbcbbfeed8/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= @@ -492,10 +563,13 @@ golang.org/x/sys v0.0.0-20200501052902-10377860bb8e/go.mod h1:h1NjWce9XRLGQEsW7w golang.org/x/sys v0.0.0-20200511232937-7e40ca221e25/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/sys v0.0.0-20200515095857-1151b9dac4a9/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/sys v0.0.0-20200523222454-059865788121/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20200930185726-fdedc70b468f/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/sys v0.0.0-20201119102817-f84b799fce68/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20210119212857-b64e53b001e4/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/sys v0.0.0-20210320140829-1e4c9ba3b0c4/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/sys v0.0.0-20210324051608-47abb6519492/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/sys v0.0.0-20210502180810-71e4cd670f79/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20210615035016-665e8c7367d1/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.0.0-20210630005230-0f9fa26af87c/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.0.0-20210927094055-39ccf1dd6fa6 h1:foEbQz/B0Oz6YIqu/69kfXPYeFQAuuMYFkjaqXzl5Wo= golang.org/x/sys v0.0.0-20210927094055-39ccf1dd6fa6/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= @@ -554,6 +628,7 @@ golang.org/x/xerrors v0.0.0-20190717185122-a985d3407aa7/go.mod h1:I/5z698sn9Ka8T golang.org/x/xerrors v0.0.0-20191011141410-1b5146add898/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= golang.org/x/xerrors v0.0.0-20191204190536-9bdfabe68543 h1:E7g+9GITq07hpfrRu66IVDexMakfv52eLZ2CXBWiKr4= golang.org/x/xerrors v0.0.0-20191204190536-9bdfabe68543/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= +golang.org/x/xerrors v0.0.0-20200804184101-5ec99f83aff1/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= google.golang.org/api v0.4.0/go.mod h1:8k5glujaEP+g9n7WNsDg8QP6cUVNI86fCNMcbazEtwE= google.golang.org/api v0.7.0/go.mod h1:WtwebWUNSVBH/HAw79HIFXZNqEvBhG+Ra+ax0hx3E3M= google.golang.org/api v0.8.0/go.mod h1:o4eAsZoiT+ibD93RtjEohWalFOjRDx6CVaqeizhEnKg= @@ -601,6 +676,7 @@ google.golang.org/genproto v0.0.0-20200312145019-da6875a35672/go.mod h1:55QSHmfG google.golang.org/genproto v0.0.0-20200331122359-1ee6d9798940/go.mod h1:55QSHmfGQM9UVYDPBsyGGes0y52j32PQ3BqQfXhyH3c= google.golang.org/genproto v0.0.0-20200430143042-b979b6f78d84/go.mod h1:55QSHmfGQM9UVYDPBsyGGes0y52j32PQ3BqQfXhyH3c= google.golang.org/genproto v0.0.0-20200511104702-f5ebc3bea380/go.mod h1:55QSHmfGQM9UVYDPBsyGGes0y52j32PQ3BqQfXhyH3c= +google.golang.org/genproto v0.0.0-20200513103714-09dca8ec2884/go.mod h1:55QSHmfGQM9UVYDPBsyGGes0y52j32PQ3BqQfXhyH3c= google.golang.org/genproto v0.0.0-20200515170657-fc4c6c6a6587/go.mod h1:YsZOwe1myG/8QRHRsmBRE1LrgQY60beZKjly0O1fX9U= google.golang.org/genproto v0.0.0-20200526211855-cb27e3aa2013/go.mod h1:NbSheEEYHJ7i3ixzK3sjbqSGDJWnxyFXZblF3eUsNvo= google.golang.org/genproto v0.0.0-20200618031413-b414f8b61790/go.mod h1:jDfRM7FcilCzHH/e9qn6dsT145K34l5v+OpcnNgKAAA= @@ -619,6 +695,11 @@ google.golang.org/grpc v1.28.0/go.mod h1:rpkK4SK4GF4Ach/+MFLZUBavHOvF2JJB5uozKKa google.golang.org/grpc v1.29.1/go.mod h1:itym6AZVZYACWQqET3MqgPpjcuV5QH3BxFS3IjizoKk= google.golang.org/grpc v1.30.0 h1:M5a8xTlYTxwMn5ZFkwhRabsygDY5G8TYLyQDBxJNAxE= google.golang.org/grpc v1.30.0/go.mod h1:N36X2cJ7JwdamYAgDz+s+rVMFjt3numwzf/HckM8pak= +google.golang.org/grpc v1.33.1/go.mod h1:fr5YgcSWrqhRRxogOsw7RzIpsmvOZ6IcH4kBYTpR3n0= +google.golang.org/grpc v1.36.0/go.mod h1:qjiiYl8FncCW8feJPdyg3v6XW24KsRHe+dy9BAGRRjU= +google.golang.org/grpc v1.46.0 h1:oCjezcn6g6A75TGoKYBPgKmVBLexhYLM6MebdrPApP8= +google.golang.org/grpc v1.46.0/go.mod h1:vN9eftEi1UMyUsIF80+uQXhHjbXYbm0uXoFCACuMGWk= +google.golang.org/grpc/cmd/protoc-gen-go-grpc v1.2.0/go.mod h1:DNq5QpG7LJqD2AamLZ7zvKE0DEpVl2BSEVjFycAAjRY= google.golang.org/protobuf v0.0.0-20200109180630-ec00e32a8dfd/go.mod h1:DFci5gLYBciE7Vtevhsrf46CRTquxDuWsQurQQe4oz8= google.golang.org/protobuf v0.0.0-20200221191635-4d8936d0db64/go.mod h1:kwYJMbMJ01Woi6D6+Kah6886xMZcty6N08ah7+eCXa0= google.golang.org/protobuf v0.0.0-20200228230310-ab0ca4ff8a60/go.mod h1:cfTl7dwQJ+fmap5saPgwCLgHXTUD7jkjRqWcaiX5VyM= @@ -630,6 +711,11 @@ google.golang.org/protobuf v1.23.1-0.20200526195155-81db48ad09cc/go.mod h1:EGpAD google.golang.org/protobuf v1.24.0/go.mod h1:r/3tXBNzIEhYS9I1OUVjXDlt8tc493IdKGjtUeSXeh4= google.golang.org/protobuf v1.25.0 h1:Ejskq+SyPohKW+1uil0JJMtmHCgJPJ/qWTxr8qp+R4c= google.golang.org/protobuf v1.25.0/go.mod h1:9JNX74DMeImyA3h4bdi1ymwjUzf21/xIlbajtzgsN7c= +google.golang.org/protobuf v1.26.0-rc.1/go.mod h1:jlhhOSvTdKEhbULTjvd4ARK9grFBp09yW+WbY/TyQbw= +google.golang.org/protobuf v1.26.0/go.mod h1:9q0QmTI4eRPtz6boOQmLYwt+qCgq0jsYwAQnmE0givc= +google.golang.org/protobuf v1.27.1/go.mod h1:9q0QmTI4eRPtz6boOQmLYwt+qCgq0jsYwAQnmE0givc= +google.golang.org/protobuf v1.28.0 h1:w43yiav+6bVFTBQFZX0r7ipe9JQ1QsbMgHwbBziscLw= +google.golang.org/protobuf v1.28.0/go.mod h1:HV8QOd/L58Z+nl8r43ehVNZIU/HEI6OcFqwMG9pJV4I= gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= gopkg.in/check.v1 v1.0.0-20180628173108-788fd7840127/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= gopkg.in/check.v1 v1.0.0-20190902080502-41f04d3bba15/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= @@ -641,6 +727,7 @@ gopkg.in/errgo.v2 v2.1.0/go.mod h1:hNsd1EY+bozCKY1Ytp96fpM3vjJbqLJn88ws8XvfDNI= gopkg.in/warnings.v0 v0.1.2 h1:wFXVbFY8DY5/xOe1ECiWdKCzZlxgshcYVNkBHstARME= gopkg.in/warnings.v0 v0.1.2/go.mod h1:jksf8JmL6Qr/oQM2OXTHunEvvTAsrWBLb6OOjuVWRNI= gopkg.in/yaml.v2 v2.2.2/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI= +gopkg.in/yaml.v2 v2.2.3/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI= gopkg.in/yaml.v2 v2.2.4/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI= gopkg.in/yaml.v2 v2.3.0 h1:clyUAQHOM3G0M3f5vQj7LuJrETvjVot3Z5el9nffUtU= gopkg.in/yaml.v2 v2.3.0/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI= diff --git a/internal/constants/api.go b/internal/constants/api.go new file mode 100644 index 0000000..74f24e8 --- /dev/null +++ b/internal/constants/api.go @@ -0,0 +1,26 @@ +/* +Copyright (c) 2019-2022 Digital Energy Cloud Solutions LLC. All Rights Reserved. +Authors: +Petr Krutov, +Stanislav Solovev, + +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. +*/ + +package constants + +//CloudApi - a part of url for cloudapi +const CloudApi = "/restmachine/cloudapi" + +//CloudBroker - a part of url for cloudbroker +const CloudBroker = "/restmachine/cloudbroker" diff --git a/decort/constants.go b/internal/constants/constants.go similarity index 65% rename from decort/constants.go rename to internal/constants/constants.go index e4ddc67..436d647 100644 --- a/decort/constants.go +++ b/internal/constants/constants.go @@ -1,6 +1,8 @@ /* -Copyright (c) 2019-2021 Digital Energy Cloud Solutions LLC. All Rights Reserved. -Author: Sergey Shubin, , +Copyright (c) 2019-2022 Digital Energy Cloud Solutions LLC. All Rights Reserved. +Authors: +Petr Krutov, +Stanislav Solovev, Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. @@ -15,29 +17,22 @@ See the License for the specific language governing permissions and limitations under the License. */ -/* -This file is part of Terraform (by Hashicorp) provider for Digital Energy Cloud Orchestration -Technology platfom. - -Visit https://github.com/rudecs/terraform-provider-decort for full source code package and updates. -*/ - -package decort +package constants // LimitMaxVinsPerResgroup set maximum number of VINs instances per Resource Group -const LimitMaxVinsPerResgroup=4 +const LimitMaxVinsPerResgroup = 4 // MaxSshKeysPerCompute sets maximum number of user:ssh_key pairs to authorize when creating new compute -const MaxSshKeysPerCompute=12 +const MaxSshKeysPerCompute = 12 // MaxExtraDisksPerCompute sets maximum number of extra disks that can be added when creating new compute -const MaxExtraDisksPerCompute=12 +const MaxExtraDisksPerCompute = 12 // MaxNetworksPerCompute sets maximum number of vNICs per compute -const MaxNetworksPerCompute=8 +const MaxNetworksPerCompute = 8 // MaxCpusPerCompute sets maximum number of vCPUs per compute -const MaxCpusPerCompute=128 +const MaxCpusPerCompute = 128 // MinRamPerCompute sets minimum amount of RAM per compute in MB -const MinRamPerCompute=128 \ No newline at end of file +const MinRamPerCompute = 128 diff --git a/internal/constants/timeouts.go b/internal/constants/timeouts.go new file mode 100644 index 0000000..71cc7d1 --- /dev/null +++ b/internal/constants/timeouts.go @@ -0,0 +1,28 @@ +/* +Copyright (c) 2019-2022 Digital Energy Cloud Solutions LLC. All Rights Reserved. +Authors: +Petr Krutov, +Stanislav Solovev, + +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. +*/ + +package constants + +import "time" + +// timeouts for API calls from CRUD functions of Terraform plugin +var Timeout30s = time.Second * 30 +var Timeout60s = time.Second * 60 +var Timeout180s = time.Second * 180 +var Timeout20m = time.Minute * 20 diff --git a/decort/controller.go b/internal/controller/controller.go similarity index 95% rename from decort/controller.go rename to internal/controller/controller.go index 19a5ac1..d36389e 100644 --- a/decort/controller.go +++ b/internal/controller/controller.go @@ -1,6 +1,8 @@ /* -Copyright (c) 2019-2021 Digital Energy Cloud Solutions LLC. All Rights Reserved. -Author: Sergey Shubin, , +Copyright (c) 2019-2022 Digital Energy Cloud Solutions LLC. All Rights Reserved. +Authors: +Petr Krutov, +Stanislav Solovev, Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. @@ -15,14 +17,7 @@ See the License for the specific language governing permissions and limitations under the License. */ -/* -This file is part of Terraform (by Hashicorp) provider for Digital Energy Cloud Orchestration -Technology platfom. - -Visit https://github.com/rudecs/terraform-provider-decort for full source code package and updates. -*/ - -package decort +package controller import ( "bytes" @@ -41,8 +36,7 @@ import ( "github.com/dgrijalva/jwt-go" - "github.com/hashicorp/terraform-plugin-sdk/helper/schema" - // "github.com/hashicorp/terraform-plugin-sdk/terraform" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" ) // enumerated constants that define authentication modes @@ -191,7 +185,7 @@ func ControllerConfigure(d *schema.ResourceData) (*ControllerCfg, error) { return ret_config, nil } -func (config *ControllerCfg) getDecortUsername() string { +func (config *ControllerCfg) GetDecortUsername() string { return config.decort_username } @@ -331,7 +325,7 @@ func (config *ControllerCfg) validateLegacyUser() (bool, error) { return true, nil } -func (config *ControllerCfg) decortAPICall(method string, api_name string, url_values *url.Values) (json_resp string, err error) { //nolint:unparam +func (config *ControllerCfg) DecortAPICall(method string, api_name string, url_values *url.Values) (json_resp string, err error) { //nolint:unparam // This is a convenience wrapper around standard HTTP request methods that is aware of the // authorization mode for which the provider was initialized and compiles request accordingly. diff --git a/internal/flattens/meta.go b/internal/flattens/meta.go new file mode 100644 index 0000000..85c30c3 --- /dev/null +++ b/internal/flattens/meta.go @@ -0,0 +1,41 @@ +/* +Copyright (c) 2019-2022 Digital Energy Cloud Solutions LLC. All Rights Reserved. +Authors: +Petr Krutov, +Stanislav Solovev, + +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. +*/ + +package flattens + +import "strconv" + +func FlattenMeta(m []interface{}) []string { + output := []string{} + for _, item := range m { + switch d := item.(type) { + case string: + output = append(output, d) + case int: + output = append(output, strconv.Itoa(d)) + case int64: + output = append(output, strconv.FormatInt(d, 10)) + case float64: + output = append(output, strconv.FormatInt(int64(d), 10)) + default: + output = append(output, "") + } + } + return output +} diff --git a/internal/location/api.go b/internal/location/api.go new file mode 100644 index 0000000..169b89b --- /dev/null +++ b/internal/location/api.go @@ -0,0 +1,22 @@ +/* +Copyright (c) 2019-2022 Digital Energy Cloud Solutions LLC. All Rights Reserved. +Authors: +Petr Krutov, +Stanislav Solovev, + +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. +*/ + +package location + +const LocationsListAPI = "/restmachine/cloudapi/locations/list" // Returns list of GridRecord on success diff --git a/decort/utility_location.go b/internal/location/location.go similarity index 64% rename from decort/utility_location.go rename to internal/location/location.go index c1fd12f..a5333a9 100644 --- a/decort/utility_location.go +++ b/internal/location/location.go @@ -1,65 +1,59 @@ -/* -Copyright (c) 2021 Digital Energy Cloud Solutions LLC. All Rights Reserved. -Author: Sergey Shubin, , - -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. -*/ - -/* -This file is part of Terraform (by Hashicorp) provider for Digital Energy Cloud Orchestration -Technology platfom. - -Visit https://github.com/rudecs/terraform-provider-decort for full source code package and updates. -*/ - -package decort - -import ( - "encoding/json" - "fmt" - "net/url" - - log "github.com/sirupsen/logrus" - - // "github.com/hashicorp/terraform-plugin-sdk/helper/schema" - // "github.com/hashicorp/terraform-plugin-sdk/helper/validation" -) - -var DefaultGridID int - -func (controller *ControllerCfg) utilityLocationGetDefaultGridID() (int, error) { - urlValues := &url.Values{} - - log.Debug("utilityLocationGetDefaultGridID: retrieving locations list") - apiResp, err := controller.decortAPICall("POST", LocationsListAPI, urlValues) - if err != nil { - return 0, err - } - - locList := LocationsListResp{} - err = json.Unmarshal([]byte(apiResp), &locList) - if err != nil { - return 0, err - } - - if len(locList) == 0 { - DefaultGridID = 0 - return 0, fmt.Errorf("utilityLocationGetDefaultGridID: retrieved 0 length locations list") - } - - DefaultGridID = locList[0].GridID - log.Debugf("utilityLocationGetDefaultGridID: default location GridID %d, name %s", DefaultGridID, locList[0].Name) - - return DefaultGridID, nil -} - +/* +Copyright (c) 2019-2022 Digital Energy Cloud Solutions LLC. All Rights Reserved. +Authors: +Petr Krutov, +Stanislav Solovev, + +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. +*/ + +package location + +import ( + "encoding/json" + "fmt" + "net/url" + + "github.com/rudecs/terraform-provider-decort/internal/controller" + log "github.com/sirupsen/logrus" +) + +var DefaultGridID int + +func UtilityLocationGetDefaultGridID(m interface{}) (int, error) { + c := m.(*controller.ControllerCfg) + + urlValues := &url.Values{} + + log.Debug("utilityLocationGetDefaultGridID: retrieving locations list") + apiResp, err := c.DecortAPICall("POST", LocationsListAPI, urlValues) + if err != nil { + return 0, err + } + + locList := LocationsListResp{} + err = json.Unmarshal([]byte(apiResp), &locList) + if err != nil { + return 0, err + } + + if len(locList) == 0 { + DefaultGridID = 0 + return 0, fmt.Errorf("utilityLocationGetDefaultGridID: retrieved 0 length locations list") + } + + DefaultGridID = locList[0].GridID + log.Debugf("utilityLocationGetDefaultGridID: default location GridID %d, name %s", DefaultGridID, locList[0].Name) + + return DefaultGridID, nil +} diff --git a/internal/location/models.go b/internal/location/models.go new file mode 100644 index 0000000..b42c9f8 --- /dev/null +++ b/internal/location/models.go @@ -0,0 +1,30 @@ +/* +Copyright (c) 2019-2022 Digital Energy Cloud Solutions LLC. All Rights Reserved. +Authors: +Petr Krutov, +Stanislav Solovev, + +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. +*/ + +package location + +type LocationRecord struct { + GridID int `json:"gid"` + Id int `json:"id"` + LocationCode string `json:"locationCode"` + Name string `json:"name"` + Flag string `json:"flag"` +} + +type LocationsListResp []LocationRecord diff --git a/internal/provider/data_sources_map.go b/internal/provider/data_sources_map.go new file mode 100644 index 0000000..70d715a --- /dev/null +++ b/internal/provider/data_sources_map.go @@ -0,0 +1,87 @@ +/* +Copyright (c) 2019-2022 Digital Energy Cloud Solutions LLC. All Rights Reserved. +Authors: +Petr Krutov, +Stanislav Solovev, + +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. +*/ + +package provider + +import ( + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" + "github.com/rudecs/terraform-provider-decort/internal/service/cloudapi/account" + "github.com/rudecs/terraform-provider-decort/internal/service/cloudapi/bservice" + "github.com/rudecs/terraform-provider-decort/internal/service/cloudapi/disks" + "github.com/rudecs/terraform-provider-decort/internal/service/cloudapi/extnet" + "github.com/rudecs/terraform-provider-decort/internal/service/cloudapi/rg" + "github.com/rudecs/terraform-provider-decort/internal/service/cloudapi/snapshot" + "github.com/rudecs/terraform-provider-decort/internal/service/cloudapi/vgpu" + "github.com/rudecs/terraform-provider-decort/internal/service/cloudapi/vins" + "github.com/rudecs/terraform-provider-decort/internal/service/cloudbroker/grid" + "github.com/rudecs/terraform-provider-decort/internal/service/cloudbroker/image" + "github.com/rudecs/terraform-provider-decort/internal/service/cloudbroker/pcidevice" + "github.com/rudecs/terraform-provider-decort/internal/service/cloudbroker/sep" +) + +func NewDataSourcesMap() map[string]*schema.Resource { + return map[string]*schema.Resource{ + "decort_account": account.DataSourceAccount(), + "decort_resgroup": rg.DataSourceResgroup(), + // "decort_kvmvm": dataSourceCompute(), + "decort_image": image.DataSourceImage(), + "decort_disk": disks.DataSourceDisk(), + "decort_vins": vins.DataSourceVins(), + "decort_grid": grid.DataSourceGrid(), + "decort_grid_list": grid.DataSourceGridList(), + "decort_image_list": image.DataSourceImageList(), + "decort_image_list_stacks": image.DataSourceImageListStacks(), + "decort_snapshot_list": snapshot.DataSourceSnapshotList(), + "decort_vgpu": vgpu.DataSourceVGPU(), + "decort_pcidevice": pcidevice.DataSourcePcidevice(), + "decort_pcidevice_list": pcidevice.DataSourcePcideviceList(), + "decort_sep_list": sep.DataSourceSepList(), + "decort_sep": sep.DataSourceSep(), + "decort_sep_consumption": sep.DataSourceSepConsumption(), + "decort_sep_disk_list": sep.DataSourceSepDiskList(), + "decort_sep_config": sep.DataSourceSepConfig(), + "decort_sep_pool": sep.DataSourceSepPool(), + "decort_disk_list": disks.DataSourceDiskList(), + "decort_rg_list": rg.DataSourceRgList(), + "decort_account_list": account.DataSourceAccountList(), + "decort_account_computes_list": account.DataSourceAccountComputesList(), + "decort_account_disks_list": account.DataSourceAccountDisksList(), + "decort_account_vins_list": account.DataSourceAccountVinsList(), + "decort_account_audits_list": account.DataSourceAccountAuditsList(), + "decort_account_rg_list": account.DataSourceAccountRGList(), + "decort_account_consumed_units": account.DataSourceAccountConsumedUnits(), + "decort_account_consumed_units_by_type": account.DataSourceAccountConsumedUnitsByType(), + "decort_account_reserved_units": account.DataSourceAccountReservedUnits(), + "decort_account_templates_list": account.DataSourceAccountTemplatessList(), + "decort_account_deleted_list": account.DataSourceAccountDeletedList(), + "decort_account_flipgroups_list": account.DataSourceAccountFlipGroupsList(), + "decort_bservice_list": bservice.DataSourceBasicServiceList(), + "decort_bservice": bservice.DataSourceBasicService(), + "decort_bservice_snapshot_list": bservice.DataSourceBasicServiceSnapshotList(), + "decort_bservice_group": bservice.DataSourceBasicServiceGroup(), + "decort_bservice_deleted_list": bservice.DataSourceBasicServiceDeletedList(), + "decort_extnet_list": extnet.DataSourceExtnetList(), + "decort_extnet_computes_list": extnet.DataSourceExtnetComputesList(), + "decort_extnet": extnet.DataSourceExtnet(), + "decort_extnet_default": extnet.DataSourceExtnetDefault(), + "decort_vins_list": vins.DataSourceVinsList(), + // "decort_pfw": dataSourcePfw(), + } + +} diff --git a/internal/provider/provider.go b/internal/provider/provider.go new file mode 100644 index 0000000..ec3d24d --- /dev/null +++ b/internal/provider/provider.go @@ -0,0 +1,134 @@ +/* +Copyright (c) 2019-2022 Digital Energy Cloud Solutions LLC. All Rights Reserved. +Authors: +Petr Krutov, +Stanislav Solovev, + +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. +*/ + +package provider + +import ( + "fmt" + "strings" + + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/validation" + + "github.com/rudecs/terraform-provider-decort/internal/controller" + "github.com/rudecs/terraform-provider-decort/internal/location" +) + +func Provider() *schema.Provider { + return &schema.Provider{ + Schema: map[string]*schema.Schema{ + "authenticator": { + Type: schema.TypeString, + Required: true, + StateFunc: StateFuncToLower, + ValidateFunc: validation.StringInSlice([]string{"oauth2", "legacy", "jwt"}, true), // ignore case while validating + Description: "Authentication mode to use when connecting to DECORT cloud API. Should be one of 'oauth2', 'legacy' or 'jwt'.", + }, + + "oauth2_url": { + Type: schema.TypeString, + Optional: true, + StateFunc: StateFuncToLower, + DefaultFunc: schema.EnvDefaultFunc("DECORT_OAUTH2_URL", nil), + Description: "OAuth2 application URL in 'oauth2' authentication mode.", + }, + + "controller_url": { + Type: schema.TypeString, + Required: true, + ForceNew: true, + StateFunc: StateFuncToLower, + Description: "URL of DECORT Cloud controller to use. API calls will be directed to this URL.", + }, + + "user": { + Type: schema.TypeString, + Optional: true, + DefaultFunc: schema.EnvDefaultFunc("DECORT_USER", nil), + Description: "User name for DECORT cloud API operations in 'legacy' authentication mode.", + }, + + "password": { + Type: schema.TypeString, + Optional: true, + DefaultFunc: schema.EnvDefaultFunc("DECORT_PASSWORD", nil), + Description: "User password for DECORT cloud API operations in 'legacy' authentication mode.", + }, + + "app_id": { + Type: schema.TypeString, + Optional: true, + DefaultFunc: schema.EnvDefaultFunc("DECORT_APP_ID", nil), + Description: "Application ID to access DECORT cloud API in 'oauth2' authentication mode.", + }, + + "app_secret": { + Type: schema.TypeString, + Optional: true, + DefaultFunc: schema.EnvDefaultFunc("DECORT_APP_SECRET", nil), + Description: "Application secret to access DECORT cloud API in 'oauth2' authentication mode.", + }, + + "jwt": { + Type: schema.TypeString, + Optional: true, + DefaultFunc: schema.EnvDefaultFunc("DECORT_JWT", nil), + Description: "JWT to access DECORT cloud API in 'jwt' authentication mode.", + }, + + "allow_unverified_ssl": { + Type: schema.TypeBool, + Optional: true, + Default: false, + Description: "If true, DECORT API will not verify SSL certificates. Use this with caution and in trusted environments only!", + }, + }, + + ResourcesMap: NewRersourcesMap(), + + DataSourcesMap: NewDataSourcesMap(), + + ConfigureFunc: providerConfigure, + } +} + +func StateFuncToLower(argval interface{}) string { + return strings.ToLower(argval.(string)) +} + +func StateFuncToUpper(argval interface{}) string { + return strings.ToUpper(argval.(string)) +} + +func providerConfigure(d *schema.ResourceData) (interface{}, error) { + decsController, err := controller.ControllerConfigure(d) + if err != nil { + return nil, err + } + + gridId, err := location.UtilityLocationGetDefaultGridID(decsController) + if err != nil { + return nil, err + } + if gridId == 0 { + return nil, fmt.Errorf("providerConfigure: invalid default Grid ID = 0") + } + + return decsController, nil +} diff --git a/internal/provider/resource_map.go b/internal/provider/resource_map.go new file mode 100644 index 0000000..1c03347 --- /dev/null +++ b/internal/provider/resource_map.go @@ -0,0 +1,58 @@ +/* +Copyright (c) 2019-2022 Digital Energy Cloud Solutions LLC. All Rights Reserved. +Authors: +Petr Krutov, +Stanislav Solovev, + +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. +*/ + +package provider + +import ( + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" + "github.com/rudecs/terraform-provider-decort/internal/service/cloudapi/account" + "github.com/rudecs/terraform-provider-decort/internal/service/cloudapi/bservice" + "github.com/rudecs/terraform-provider-decort/internal/service/cloudapi/disks" + "github.com/rudecs/terraform-provider-decort/internal/service/cloudapi/k8s" + "github.com/rudecs/terraform-provider-decort/internal/service/cloudapi/pfw" + "github.com/rudecs/terraform-provider-decort/internal/service/cloudapi/rg" + "github.com/rudecs/terraform-provider-decort/internal/service/cloudapi/snapshot" + "github.com/rudecs/terraform-provider-decort/internal/service/cloudapi/vins" + "github.com/rudecs/terraform-provider-decort/internal/service/cloudbroker/image" + "github.com/rudecs/terraform-provider-decort/internal/service/cloudbroker/pcidevice" + "github.com/rudecs/terraform-provider-decort/internal/service/cloudbroker/sep" +) + +func NewRersourcesMap() map[string]*schema.Resource { + return map[string]*schema.Resource{ + "decort_resgroup": rg.ResourceResgroup(), + // "decort_kvmvm": resourceCompute(), + "decort_disk": disks.ResourceDisk(), + "decort_vins": vins.ResourceVins(), + "decort_pfw": pfw.ResourcePfw(), + "decort_k8s": k8s.ResourceK8s(), + "decort_k8s_wg": k8s.ResourceK8sWg(), + "decort_image": image.ResourceImage(), + "decort_virtual_image": image.ResourceVirtualImage(), + "decort_cdrom_image": image.ResourceCDROMImage(), + "decort_delete_images": image.ResourceDeleteImages(), + "decort_snapshot": snapshot.ResourceSnapshot(), + "decort_pcidevice": pcidevice.ResourcePcidevice(), + "decort_sep": sep.ResourceSep(), + "decort_sep_config": sep.ResourceSepConfig(), + "decort_account": account.ResourceAccount(), + "decort_bservice": bservice.ResourceBasicService(), + "decort_bservice_group": bservice.ResourceBasicServiceGroup(), + } +} diff --git a/internal/service/cloudapi/account/api.go b/internal/service/cloudapi/account/api.go new file mode 100644 index 0000000..b69c616 --- /dev/null +++ b/internal/service/cloudapi/account/api.go @@ -0,0 +1,55 @@ +/* +Copyright (c) 2019-2022 Digital Energy Cloud Solutions LLC. All Rights Reserved. +Authors: +Petr Krutov, +Stanislav Solovev, + +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. +*/ + +/* +Terraform DECORT provider - manage resources provided by DECORT (Digital Energy Cloud +Orchestration Technology) with Terraform by Hashicorp. + +Source code: https://github.com/rudecs/terraform-provider-decort + +Please see README.md to learn where to place source code so that it +builds seamlessly. + +Documentation: https://github.com/rudecs/terraform-provider-decort/wiki +*/ + +package account + +const accountAddUserAPI = "/restmachine/cloudapi/account/addUser" +const accountAuditsAPI = "/restmachine/cloudapi/account/audits" +const accountCreateAPI = "/restmachine/cloudapi/account/create" +const accountDeleteAPI = "/restmachine/cloudapi/account/delete" +const accountDeleteUserAPI = "/restmachine/cloudapi/account/deleteUser" +const accountDisableAPI = "/restmachine/cloudapi/account/disable" +const accountEnableAPI = "/restmachine/cloudapi/account/enable" +const accountGetAPI = "/restmachine/cloudapi/account/get" +const accountGetConsumedUnitsAPI = "/restmachine/cloudapi/account/getConsumedAccountUnits" +const accountGetConsumedUnitsByTypeAPI = "/restmachine/cloudapi/account/getConsumedCloudUnitsByType" +const accountGetReservedUnitsAPI = "/restmachine/cloudapi/account/getReservedAccountUnits" +const accountListAPI = "/restmachine/cloudapi/account/list" +const accountListComputesAPI = "/restmachine/cloudapi/account/listComputes" +const accountListDeletedAPI = "/restmachine/cloudapi/account/listDeleted" +const accountListDisksAPI = "/restmachine/cloudapi/account/listDisks" +const accountListFlipGroupsAPI = "/restmachine/cloudapi/account/listFlipGroups" +const accountListRGAPI = "/restmachine/cloudapi/account/listRG" +const accountListTemplatesAPI = "/restmachine/cloudapi/account/listTemplates" +const accountListVinsAPI = "/restmachine/cloudapi/account/listVins" +const accountRestoreAPI = "/restmachine/cloudapi/account/restore" +const accountUpdateAPI = "/restmachine/cloudapi/account/update" +const accountUpdateUserAPI = "/restmachine/cloudapi/account/updateUser" diff --git a/decort/data_source_account.go b/internal/service/cloudapi/account/data_source_account.go similarity index 86% rename from decort/data_source_account.go rename to internal/service/cloudapi/account/data_source_account.go index 39ef95c..85f4003 100644 --- a/decort/data_source_account.go +++ b/internal/service/cloudapi/account/data_source_account.go @@ -1,6 +1,8 @@ /* Copyright (c) 2019-2022 Digital Energy Cloud Solutions LLC. All Rights Reserved. -Author: Stanislav Solovev, +Authors: +Petr Krutov, +Stanislav Solovev, Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. @@ -16,23 +18,33 @@ limitations under the License. */ /* -This file is part of Terraform (by Hashicorp) provider for Digital Energy Cloud Orchestration -Technology platfom. +Terraform DECORT provider - manage resources provided by DECORT (Digital Energy Cloud +Orchestration Technology) with Terraform by Hashicorp. -Visit https://github.com/rudecs/terraform-provider-decort for full source code package and updates. +Source code: https://github.com/rudecs/terraform-provider-decort + +Please see README.md to learn where to place source code so that it +builds seamlessly. + +Documentation: https://github.com/rudecs/terraform-provider-decort/wiki */ -package decort +package account import ( + "context" + "github.com/google/uuid" - "github.com/hashicorp/terraform-plugin-sdk/helper/schema" + "github.com/hashicorp/terraform-plugin-sdk/v2/diag" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" + "github.com/rudecs/terraform-provider-decort/internal/constants" + "github.com/rudecs/terraform-provider-decort/internal/flattens" ) -func dataSourceAccountRead(d *schema.ResourceData, m interface{}) error { +func dataSourceAccountRead(ctx context.Context, d *schema.ResourceData, m interface{}) diag.Diagnostics { acc, err := utilityAccountCheckPresence(d, m) if err != nil { - return err + return diag.FromErr(err) } id := uuid.New() @@ -40,7 +52,7 @@ func dataSourceAccountRead(d *schema.ResourceData, m interface{}) error { d.Set("dc_location", acc.DCLocation) d.Set("resources", flattenAccResources(acc.Resources)) d.Set("ckey", acc.CKey) - d.Set("meta", flattenMeta(acc.Meta)) + d.Set("meta", flattens.FlattenMeta(acc.Meta)) d.Set("acl", flattenAccAcl(acc.Acl)) d.Set("company", acc.Company) d.Set("companyurl", acc.CompanyUrl) @@ -103,6 +115,22 @@ func flattenAccAcl(acls []AccountAclRecord) []map[string]interface{} { return res } +func flattenRgResourceLimits(rl ResourceLimits) []map[string]interface{} { + res := make([]map[string]interface{}, 0) + temp := map[string]interface{}{ + "cu_c": rl.CUC, + "cu_d": rl.CUD, + "cu_i": rl.CUI, + "cu_m": rl.CUM, + "cu_np": rl.CUNP, + "gpu_units": rl.GpuUnits, + } + res = append(res, temp) + + return res + +} + func flattenAccResources(r Resources) []map[string]interface{} { res := make([]map[string]interface{}, 0) temp := map[string]interface{}{ @@ -401,15 +429,15 @@ func dataSourceAccountSchemaMake() map[string]*schema.Schema { return res } -func dataSourceAccount() *schema.Resource { +func DataSourceAccount() *schema.Resource { return &schema.Resource{ SchemaVersion: 1, - Read: dataSourceAccountRead, + ReadContext: dataSourceAccountRead, Timeouts: &schema.ResourceTimeout{ - Read: &Timeout30s, - Default: &Timeout60s, + Read: &constants.Timeout30s, + Default: &constants.Timeout60s, }, Schema: dataSourceAccountSchemaMake(), diff --git a/decort/data_source_account_audits_list.go b/internal/service/cloudapi/account/data_source_account_audits_list.go similarity index 66% rename from decort/data_source_account_audits_list.go rename to internal/service/cloudapi/account/data_source_account_audits_list.go index c31e947..6351c70 100644 --- a/decort/data_source_account_audits_list.go +++ b/internal/service/cloudapi/account/data_source_account_audits_list.go @@ -1,6 +1,8 @@ /* Copyright (c) 2019-2022 Digital Energy Cloud Solutions LLC. All Rights Reserved. -Author: Stanislav Solovev, +Authors: +Petr Krutov, +Stanislav Solovev, Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. @@ -16,17 +18,26 @@ limitations under the License. */ /* -This file is part of Terraform (by Hashicorp) provider for Digital Energy Cloud Orchestration -Technology platfom. +Terraform DECORT provider - manage resources provided by DECORT (Digital Energy Cloud +Orchestration Technology) with Terraform by Hashicorp. -Visit https://github.com/rudecs/terraform-provider-decort for full source code package and updates. +Source code: https://github.com/rudecs/terraform-provider-decort + +Please see README.md to learn where to place source code so that it +builds seamlessly. + +Documentation: https://github.com/rudecs/terraform-provider-decort/wiki */ -package decort +package account import ( + "context" + "github.com/google/uuid" - "github.com/hashicorp/terraform-plugin-sdk/helper/schema" + "github.com/hashicorp/terraform-plugin-sdk/v2/diag" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" + "github.com/rudecs/terraform-provider-decort/internal/constants" ) func flattenAccountAuditsList(aal AccountAuditsList) []map[string]interface{} { @@ -45,10 +56,10 @@ func flattenAccountAuditsList(aal AccountAuditsList) []map[string]interface{} { } -func dataSourceAccountAuditsListRead(d *schema.ResourceData, m interface{}) error { +func dataSourceAccountAuditsListRead(ctx context.Context, d *schema.ResourceData, m interface{}) diag.Diagnostics { accountAuditsList, err := utilityAccountAuditsListCheckPresence(d, m) if err != nil { - return err + return diag.FromErr(err) } id := uuid.New() @@ -98,15 +109,15 @@ func dataSourceAccountAuditsListSchemaMake() map[string]*schema.Schema { return res } -func dataSourceAccountAuditsList() *schema.Resource { +func DataSourceAccountAuditsList() *schema.Resource { return &schema.Resource{ SchemaVersion: 1, - Read: dataSourceAccountAuditsListRead, + ReadContext: dataSourceAccountAuditsListRead, Timeouts: &schema.ResourceTimeout{ - Read: &Timeout30s, - Default: &Timeout60s, + Read: &constants.Timeout30s, + Default: &constants.Timeout60s, }, Schema: dataSourceAccountAuditsListSchemaMake(), diff --git a/decort/data_source_account_computes_list.go b/internal/service/cloudapi/account/data_source_account_computes_list.go similarity index 77% rename from decort/data_source_account_computes_list.go rename to internal/service/cloudapi/account/data_source_account_computes_list.go index 8a7ba77..9828c2a 100644 --- a/decort/data_source_account_computes_list.go +++ b/internal/service/cloudapi/account/data_source_account_computes_list.go @@ -1,6 +1,8 @@ /* Copyright (c) 2019-2022 Digital Energy Cloud Solutions LLC. All Rights Reserved. -Author: Stanislav Solovev, +Authors: +Petr Krutov, +Stanislav Solovev, Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. @@ -16,17 +18,26 @@ limitations under the License. */ /* -This file is part of Terraform (by Hashicorp) provider for Digital Energy Cloud Orchestration -Technology platfom. +Terraform DECORT provider - manage resources provided by DECORT (Digital Energy Cloud +Orchestration Technology) with Terraform by Hashicorp. -Visit https://github.com/rudecs/terraform-provider-decort for full source code package and updates. +Source code: https://github.com/rudecs/terraform-provider-decort + +Please see README.md to learn where to place source code so that it +builds seamlessly. + +Documentation: https://github.com/rudecs/terraform-provider-decort/wiki */ -package decort +package account import ( + "context" + "github.com/google/uuid" - "github.com/hashicorp/terraform-plugin-sdk/helper/schema" + "github.com/hashicorp/terraform-plugin-sdk/v2/diag" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" + "github.com/rudecs/terraform-provider-decort/internal/constants" ) func flattenAccountComputesList(acl AccountComputesList) []map[string]interface{} { @@ -60,10 +71,10 @@ func flattenAccountComputesList(acl AccountComputesList) []map[string]interface{ } -func dataSourceAccountComputesListRead(d *schema.ResourceData, m interface{}) error { +func dataSourceAccountComputesListRead(ctx context.Context, d *schema.ResourceData, m interface{}) diag.Diagnostics { accountComputesList, err := utilityAccountComputesListCheckPresence(d, m) if err != nil { - return err + return diag.FromErr(err) } id := uuid.New() @@ -173,15 +184,15 @@ func dataSourceAccountComputesListSchemaMake() map[string]*schema.Schema { return res } -func dataSourceAccountComputesList() *schema.Resource { +func DataSourceAccountComputesList() *schema.Resource { return &schema.Resource{ SchemaVersion: 1, - Read: dataSourceAccountComputesListRead, + ReadContext: dataSourceAccountComputesListRead, Timeouts: &schema.ResourceTimeout{ - Read: &Timeout30s, - Default: &Timeout60s, + Read: &constants.Timeout30s, + Default: &constants.Timeout60s, }, Schema: dataSourceAccountComputesListSchemaMake(), diff --git a/decort/data_source_account_consumed_units.go b/internal/service/cloudapi/account/data_source_account_consumed_units.go similarity index 62% rename from decort/data_source_account_consumed_units.go rename to internal/service/cloudapi/account/data_source_account_consumed_units.go index 6723e17..52b9f19 100644 --- a/decort/data_source_account_consumed_units.go +++ b/internal/service/cloudapi/account/data_source_account_consumed_units.go @@ -1,6 +1,8 @@ /* Copyright (c) 2019-2022 Digital Energy Cloud Solutions LLC. All Rights Reserved. -Author: Stanislav Solovev, +Authors: +Petr Krutov, +Stanislav Solovev, Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. @@ -16,23 +18,32 @@ limitations under the License. */ /* -This file is part of Terraform (by Hashicorp) provider for Digital Energy Cloud Orchestration -Technology platfom. +Terraform DECORT provider - manage resources provided by DECORT (Digital Energy Cloud +Orchestration Technology) with Terraform by Hashicorp. -Visit https://github.com/rudecs/terraform-provider-decort for full source code package and updates. +Source code: https://github.com/rudecs/terraform-provider-decort + +Please see README.md to learn where to place source code so that it +builds seamlessly. + +Documentation: https://github.com/rudecs/terraform-provider-decort/wiki */ -package decort +package account import ( + "context" + "github.com/google/uuid" - "github.com/hashicorp/terraform-plugin-sdk/helper/schema" + "github.com/hashicorp/terraform-plugin-sdk/v2/diag" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" + "github.com/rudecs/terraform-provider-decort/internal/constants" ) -func dataSourceAccountConsumedUnitsRead(d *schema.ResourceData, m interface{}) error { +func dataSourceAccountConsumedUnitsRead(ctx context.Context, d *schema.ResourceData, m interface{}) diag.Diagnostics { accountConsumedUnits, err := utilityAccountConsumedUnitsCheckPresence(d, m) if err != nil { - return err + return diag.FromErr(err) } id := uuid.New() @@ -82,15 +93,15 @@ func dataSourceAccountConsumedUnitsSchemaMake() map[string]*schema.Schema { return res } -func dataSourceAccountConsumedUnits() *schema.Resource { +func DataSourceAccountConsumedUnits() *schema.Resource { return &schema.Resource{ SchemaVersion: 1, - Read: dataSourceAccountConsumedUnitsRead, + ReadContext: dataSourceAccountConsumedUnitsRead, Timeouts: &schema.ResourceTimeout{ - Read: &Timeout30s, - Default: &Timeout60s, + Read: &constants.Timeout30s, + Default: &constants.Timeout60s, }, Schema: dataSourceAccountConsumedUnitsSchemaMake(), diff --git a/decort/data_source_account_consumed_units_by_type.go b/internal/service/cloudapi/account/data_source_account_consumed_units_by_type.go similarity index 56% rename from decort/data_source_account_consumed_units_by_type.go rename to internal/service/cloudapi/account/data_source_account_consumed_units_by_type.go index 4b9ccd6..877608e 100644 --- a/decort/data_source_account_consumed_units_by_type.go +++ b/internal/service/cloudapi/account/data_source_account_consumed_units_by_type.go @@ -1,6 +1,8 @@ /* Copyright (c) 2019-2022 Digital Energy Cloud Solutions LLC. All Rights Reserved. -Author: Stanislav Solovev, +Authors: +Petr Krutov, +Stanislav Solovev, Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. @@ -16,23 +18,32 @@ limitations under the License. */ /* -This file is part of Terraform (by Hashicorp) provider for Digital Energy Cloud Orchestration -Technology platfom. +Terraform DECORT provider - manage resources provided by DECORT (Digital Energy Cloud +Orchestration Technology) with Terraform by Hashicorp. -Visit https://github.com/rudecs/terraform-provider-decort for full source code package and updates. +Source code: https://github.com/rudecs/terraform-provider-decort + +Please see README.md to learn where to place source code so that it +builds seamlessly. + +Documentation: https://github.com/rudecs/terraform-provider-decort/wiki */ -package decort +package account import ( + "context" + "github.com/google/uuid" - "github.com/hashicorp/terraform-plugin-sdk/helper/schema" + "github.com/hashicorp/terraform-plugin-sdk/v2/diag" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" + "github.com/rudecs/terraform-provider-decort/internal/constants" ) -func dataSourceAccountConsumedUnitsByTypeRead(d *schema.ResourceData, m interface{}) error { +func dataSourceAccountConsumedUnitsByTypeRead(ctx context.Context, d *schema.ResourceData, m interface{}) diag.Diagnostics { result, err := utilityAccountConsumedUnitsByTypeCheckPresence(d, m) if err != nil { - return err + return diag.FromErr(err) } id := uuid.New() @@ -62,15 +73,15 @@ func dataSourceAccountConsumedUnitsByTypeSchemaMake() map[string]*schema.Schema return res } -func dataSourceAccountConsumedUnitsByType() *schema.Resource { +func DataSourceAccountConsumedUnitsByType() *schema.Resource { return &schema.Resource{ SchemaVersion: 1, - Read: dataSourceAccountConsumedUnitsByTypeRead, + ReadContext: dataSourceAccountConsumedUnitsByTypeRead, Timeouts: &schema.ResourceTimeout{ - Read: &Timeout30s, - Default: &Timeout60s, + Read: &constants.Timeout30s, + Default: &constants.Timeout60s, }, Schema: dataSourceAccountConsumedUnitsByTypeSchemaMake(), diff --git a/internal/service/cloudapi/account/data_source_account_deleted_list.go b/internal/service/cloudapi/account/data_source_account_deleted_list.go new file mode 100644 index 0000000..0dc1d3f --- /dev/null +++ b/internal/service/cloudapi/account/data_source_account_deleted_list.go @@ -0,0 +1,69 @@ +/* +Copyright (c) 2019-2022 Digital Energy Cloud Solutions LLC. All Rights Reserved. +Authors: +Petr Krutov, +Stanislav Solovev, + +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. +*/ + +/* +Terraform DECORT provider - manage resources provided by DECORT (Digital Energy Cloud +Orchestration Technology) with Terraform by Hashicorp. + +Source code: https://github.com/rudecs/terraform-provider-decort + +Please see README.md to learn where to place source code so that it +builds seamlessly. + +Documentation: https://github.com/rudecs/terraform-provider-decort/wiki +*/ + +package account + +import ( + "context" + + "github.com/google/uuid" + "github.com/hashicorp/terraform-plugin-sdk/v2/diag" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" + "github.com/rudecs/terraform-provider-decort/internal/constants" +) + +func dataSourceAccountDeletedListRead(ctx context.Context, d *schema.ResourceData, m interface{}) diag.Diagnostics { + accountDeletedList, err := utilityAccountDeletedListCheckPresence(d, m) + if err != nil { + return diag.FromErr(err) + } + + id := uuid.New() + d.SetId(id.String()) + d.Set("items", flattenAccountList(accountDeletedList)) + + return nil +} + +func DataSourceAccountDeletedList() *schema.Resource { + return &schema.Resource{ + SchemaVersion: 1, + + ReadContext: dataSourceAccountDeletedListRead, + + Timeouts: &schema.ResourceTimeout{ + Read: &constants.Timeout30s, + Default: &constants.Timeout60s, + }, + + Schema: dataSourceAccountListSchemaMake(), + } +} diff --git a/decort/data_source_account_disks_list.go b/internal/service/cloudapi/account/data_source_account_disks_list.go similarity index 67% rename from decort/data_source_account_disks_list.go rename to internal/service/cloudapi/account/data_source_account_disks_list.go index def9676..9871eed 100644 --- a/decort/data_source_account_disks_list.go +++ b/internal/service/cloudapi/account/data_source_account_disks_list.go @@ -1,6 +1,8 @@ /* Copyright (c) 2019-2022 Digital Energy Cloud Solutions LLC. All Rights Reserved. -Author: Stanislav Solovev, +Authors: +Petr Krutov, +Stanislav Solovev, Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. @@ -16,17 +18,25 @@ limitations under the License. */ /* -This file is part of Terraform (by Hashicorp) provider for Digital Energy Cloud Orchestration -Technology platfom. +Terraform DECORT provider - manage resources provided by DECORT (Digital Energy Cloud +Orchestration Technology) with Terraform by Hashicorp. -Visit https://github.com/rudecs/terraform-provider-decort for full source code package and updates. -*/ +Source code: https://github.com/rudecs/terraform-provider-decort + +Please see README.md to learn where to place source code so that it +builds seamlessly. -package decort +Documentation: https://github.com/rudecs/terraform-provider-decort/wiki +*/ +package account import ( + "context" + "github.com/google/uuid" - "github.com/hashicorp/terraform-plugin-sdk/helper/schema" + "github.com/hashicorp/terraform-plugin-sdk/v2/diag" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" + "github.com/rudecs/terraform-provider-decort/internal/constants" ) func flattenAccountDisksList(adl AccountDisksList) []map[string]interface{} { @@ -46,10 +56,10 @@ func flattenAccountDisksList(adl AccountDisksList) []map[string]interface{} { } -func dataSourceAccountDisksListRead(d *schema.ResourceData, m interface{}) error { +func dataSourceAccountDisksListRead(ctx context.Context, d *schema.ResourceData, m interface{}) diag.Diagnostics { accountDisksList, err := utilityAccountDisksListCheckPresence(d, m) if err != nil { - return err + return diag.FromErr(err) } id := uuid.New() @@ -103,15 +113,15 @@ func dataSourceAccountDisksListSchemaMake() map[string]*schema.Schema { return res } -func dataSourceAccountDisksList() *schema.Resource { +func DataSourceAccountDisksList() *schema.Resource { return &schema.Resource{ SchemaVersion: 1, - Read: dataSourceAccountDisksListRead, + ReadContext: dataSourceAccountDisksListRead, Timeouts: &schema.ResourceTimeout{ - Read: &Timeout30s, - Default: &Timeout60s, + Read: &constants.Timeout30s, + Default: &constants.Timeout60s, }, Schema: dataSourceAccountDisksListSchemaMake(), diff --git a/decort/data_source_account_flipgroups_list.go b/internal/service/cloudapi/account/data_source_account_flipgroups_list.go similarity index 77% rename from decort/data_source_account_flipgroups_list.go rename to internal/service/cloudapi/account/data_source_account_flipgroups_list.go index dd83716..09bc65b 100644 --- a/decort/data_source_account_flipgroups_list.go +++ b/internal/service/cloudapi/account/data_source_account_flipgroups_list.go @@ -1,6 +1,8 @@ /* Copyright (c) 2019-2022 Digital Energy Cloud Solutions LLC. All Rights Reserved. -Author: Stanislav Solovev, +Authors: +Petr Krutov, +Stanislav Solovev, Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. @@ -16,17 +18,26 @@ limitations under the License. */ /* -This file is part of Terraform (by Hashicorp) provider for Digital Energy Cloud Orchestration -Technology platfom. +Terraform DECORT provider - manage resources provided by DECORT (Digital Energy Cloud +Orchestration Technology) with Terraform by Hashicorp. -Visit https://github.com/rudecs/terraform-provider-decort for full source code package and updates. +Source code: https://github.com/rudecs/terraform-provider-decort + +Please see README.md to learn where to place source code so that it +builds seamlessly. + +Documentation: https://github.com/rudecs/terraform-provider-decort/wiki */ -package decort +package account import ( + "context" + "github.com/google/uuid" - "github.com/hashicorp/terraform-plugin-sdk/helper/schema" + "github.com/hashicorp/terraform-plugin-sdk/v2/diag" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" + "github.com/rudecs/terraform-provider-decort/internal/constants" ) func flattenAccountFlipGroupsList(afgl AccountFlipGroupsList) []map[string]interface{} { @@ -61,10 +72,10 @@ func flattenAccountFlipGroupsList(afgl AccountFlipGroupsList) []map[string]inter } -func dataSourceAccountFlipGroupsListRead(d *schema.ResourceData, m interface{}) error { +func dataSourceAccountFlipGroupsListRead(ctx context.Context, d *schema.ResourceData, m interface{}) diag.Diagnostics { accountFlipGroupsList, err := utilityAccountFlipGroupsListCheckPresence(d, m) if err != nil { - return err + return diag.FromErr(err) } id := uuid.New() @@ -178,15 +189,15 @@ func dataSourceAccountFlipGroupsListSchemaMake() map[string]*schema.Schema { return res } -func dataSourceAccountFlipGroupsList() *schema.Resource { +func DataSourceAccountFlipGroupsList() *schema.Resource { return &schema.Resource{ SchemaVersion: 1, - Read: dataSourceAccountFlipGroupsListRead, + ReadContext: dataSourceAccountFlipGroupsListRead, Timeouts: &schema.ResourceTimeout{ - Read: &Timeout30s, - Default: &Timeout60s, + Read: &constants.Timeout30s, + Default: &constants.Timeout60s, }, Schema: dataSourceAccountFlipGroupsListSchemaMake(), diff --git a/decort/data_source_account_list.go b/internal/service/cloudapi/account/data_source_account_list.go similarity index 79% rename from decort/data_source_account_list.go rename to internal/service/cloudapi/account/data_source_account_list.go index b587bda..df625d0 100644 --- a/decort/data_source_account_list.go +++ b/internal/service/cloudapi/account/data_source_account_list.go @@ -1,6 +1,8 @@ /* Copyright (c) 2019-2022 Digital Energy Cloud Solutions LLC. All Rights Reserved. -Author: Stanislav Solovev, +Authors: +Petr Krutov, +Stanislav Solovev, Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. @@ -16,17 +18,26 @@ limitations under the License. */ /* -This file is part of Terraform (by Hashicorp) provider for Digital Energy Cloud Orchestration -Technology platfom. +Terraform DECORT provider - manage resources provided by DECORT (Digital Energy Cloud +Orchestration Technology) with Terraform by Hashicorp. -Visit https://github.com/rudecs/terraform-provider-decort for full source code package and updates. +Source code: https://github.com/rudecs/terraform-provider-decort + +Please see README.md to learn where to place source code so that it +builds seamlessly. + +Documentation: https://github.com/rudecs/terraform-provider-decort/wiki */ -package decort +package account import ( + "context" + "github.com/google/uuid" - "github.com/hashicorp/terraform-plugin-sdk/helper/schema" + "github.com/hashicorp/terraform-plugin-sdk/v2/diag" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" + "github.com/rudecs/terraform-provider-decort/internal/constants" ) func flattenAccountList(al AccountCloudApiList) []map[string]interface{} { @@ -46,6 +57,22 @@ func flattenAccountList(al AccountCloudApiList) []map[string]interface{} { return res } +func flattenRgAcl(rgAcls []AccountAclRecord) []map[string]interface{} { + res := make([]map[string]interface{}, 0) + for _, rgAcl := range rgAcls { + temp := map[string]interface{}{ + "explicit": rgAcl.IsExplicit, + "guid": rgAcl.Guid, + "right": rgAcl.Rights, + "status": rgAcl.Status, + "type": rgAcl.Type, + "user_group_id": rgAcl.UgroupID, + } + res = append(res, temp) + } + return res +} + /*uncomment for cloudbroker func flattenAccountList(al AccountList) []map[string]interface{} { res := make([]map[string]interface{}, 0) @@ -91,10 +118,10 @@ func flattenAccountList(al AccountList) []map[string]interface{} { } */ -func dataSourceAccountListRead(d *schema.ResourceData, m interface{}) error { +func dataSourceAccountListRead(ctx context.Context, d *schema.ResourceData, m interface{}) diag.Diagnostics { accountList, err := utilityAccountListCheckPresence(d, m) if err != nil { - return err + return diag.FromErr(err) } id := uuid.New() @@ -290,15 +317,15 @@ func dataSourceAccountListSchemaMake() map[string]*schema.Schema { return res } -func dataSourceAccountList() *schema.Resource { +func DataSourceAccountList() *schema.Resource { return &schema.Resource{ SchemaVersion: 1, - Read: dataSourceAccountListRead, + ReadContext: dataSourceAccountListRead, Timeouts: &schema.ResourceTimeout{ - Read: &Timeout30s, - Default: &Timeout60s, + Read: &constants.Timeout30s, + Default: &constants.Timeout60s, }, Schema: dataSourceAccountListSchemaMake(), diff --git a/decort/data_source_account_reserved_units.go b/internal/service/cloudapi/account/data_source_account_reserved_units.go similarity index 62% rename from decort/data_source_account_reserved_units.go rename to internal/service/cloudapi/account/data_source_account_reserved_units.go index b4d48c9..d708129 100644 --- a/decort/data_source_account_reserved_units.go +++ b/internal/service/cloudapi/account/data_source_account_reserved_units.go @@ -1,6 +1,8 @@ /* Copyright (c) 2019-2022 Digital Energy Cloud Solutions LLC. All Rights Reserved. -Author: Stanislav Solovev, +Authors: +Petr Krutov, +Stanislav Solovev, Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. @@ -16,23 +18,32 @@ limitations under the License. */ /* -This file is part of Terraform (by Hashicorp) provider for Digital Energy Cloud Orchestration -Technology platfom. +Terraform DECORT provider - manage resources provided by DECORT (Digital Energy Cloud +Orchestration Technology) with Terraform by Hashicorp. -Visit https://github.com/rudecs/terraform-provider-decort for full source code package and updates. +Source code: https://github.com/rudecs/terraform-provider-decort + +Please see README.md to learn where to place source code so that it +builds seamlessly. + +Documentation: https://github.com/rudecs/terraform-provider-decort/wiki */ -package decort +package account import ( + "context" + "github.com/google/uuid" - "github.com/hashicorp/terraform-plugin-sdk/helper/schema" + "github.com/hashicorp/terraform-plugin-sdk/v2/diag" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" + "github.com/rudecs/terraform-provider-decort/internal/constants" ) -func dataSourceAccountReservedUnitsRead(d *schema.ResourceData, m interface{}) error { +func dataSourceAccountReservedUnitsRead(ctx context.Context, d *schema.ResourceData, m interface{}) diag.Diagnostics { accountReservedUnits, err := utilityAccountReservedUnitsCheckPresence(d, m) if err != nil { - return err + return diag.FromErr(err) } id := uuid.New() @@ -82,15 +93,15 @@ func dataSourceAccountReservedUnitsSchemaMake() map[string]*schema.Schema { return res } -func dataSourceAccountReservedUnits() *schema.Resource { +func DataSourceAccountReservedUnits() *schema.Resource { return &schema.Resource{ SchemaVersion: 1, - Read: dataSourceAccountReservedUnitsRead, + ReadContext: dataSourceAccountReservedUnitsRead, Timeouts: &schema.ResourceTimeout{ - Read: &Timeout30s, - Default: &Timeout60s, + Read: &constants.Timeout30s, + Default: &constants.Timeout60s, }, Schema: dataSourceAccountReservedUnitsSchemaMake(), diff --git a/decort/data_source_account_rg_list.go b/internal/service/cloudapi/account/data_source_account_rg_list.go similarity index 83% rename from decort/data_source_account_rg_list.go rename to internal/service/cloudapi/account/data_source_account_rg_list.go index 40e2284..29f885f 100644 --- a/decort/data_source_account_rg_list.go +++ b/internal/service/cloudapi/account/data_source_account_rg_list.go @@ -1,6 +1,8 @@ /* Copyright (c) 2019-2022 Digital Energy Cloud Solutions LLC. All Rights Reserved. -Author: Stanislav Solovev, +Authors: +Petr Krutov, +Stanislav Solovev, Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. @@ -16,17 +18,26 @@ limitations under the License. */ /* -This file is part of Terraform (by Hashicorp) provider for Digital Energy Cloud Orchestration -Technology platfom. +Terraform DECORT provider - manage resources provided by DECORT (Digital Energy Cloud +Orchestration Technology) with Terraform by Hashicorp. -Visit https://github.com/rudecs/terraform-provider-decort for full source code package and updates. +Source code: https://github.com/rudecs/terraform-provider-decort + +Please see README.md to learn where to place source code so that it +builds seamlessly. + +Documentation: https://github.com/rudecs/terraform-provider-decort/wiki */ -package decort +package account import ( + "context" + "github.com/google/uuid" - "github.com/hashicorp/terraform-plugin-sdk/helper/schema" + "github.com/hashicorp/terraform-plugin-sdk/v2/diag" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" + "github.com/rudecs/terraform-provider-decort/internal/constants" ) func flattenAccountRGList(argl AccountRGList) []map[string]interface{} { @@ -74,10 +85,10 @@ func flattenAccRGResources(argr AccountRGResources) []map[string]interface{} { return res } -func dataSourceAccountRGListRead(d *schema.ResourceData, m interface{}) error { +func dataSourceAccountRGListRead(ctx context.Context, d *schema.ResourceData, m interface{}) diag.Diagnostics { accountRGList, err := utilityAccountRGListCheckPresence(d, m) if err != nil { - return err + return diag.FromErr(err) } id := uuid.New() @@ -278,15 +289,15 @@ func dataSourceAccountRGListSchemaMake() map[string]*schema.Schema { return res } -func dataSourceAccountRGList() *schema.Resource { +func DataSourceAccountRGList() *schema.Resource { return &schema.Resource{ SchemaVersion: 1, - Read: dataSourceAccountRGListRead, + ReadContext: dataSourceAccountRGListRead, Timeouts: &schema.ResourceTimeout{ - Read: &Timeout30s, - Default: &Timeout60s, + Read: &constants.Timeout30s, + Default: &constants.Timeout60s, }, Schema: dataSourceAccountRGListSchemaMake(), diff --git a/decort/data_source_account_templates_list.go b/internal/service/cloudapi/account/data_source_account_templates_list.go similarity index 70% rename from decort/data_source_account_templates_list.go rename to internal/service/cloudapi/account/data_source_account_templates_list.go index 4071088..113d9a7 100644 --- a/decort/data_source_account_templates_list.go +++ b/internal/service/cloudapi/account/data_source_account_templates_list.go @@ -1,6 +1,8 @@ /* Copyright (c) 2019-2022 Digital Energy Cloud Solutions LLC. All Rights Reserved. -Author: Stanislav Solovev, +Authors: +Petr Krutov, +Stanislav Solovev, Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. @@ -16,17 +18,26 @@ limitations under the License. */ /* -This file is part of Terraform (by Hashicorp) provider for Digital Energy Cloud Orchestration -Technology platfom. +Terraform DECORT provider - manage resources provided by DECORT (Digital Energy Cloud +Orchestration Technology) with Terraform by Hashicorp. -Visit https://github.com/rudecs/terraform-provider-decort for full source code package and updates. +Source code: https://github.com/rudecs/terraform-provider-decort + +Please see README.md to learn where to place source code so that it +builds seamlessly. + +Documentation: https://github.com/rudecs/terraform-provider-decort/wiki */ -package decort +package account import ( + "context" + "github.com/google/uuid" - "github.com/hashicorp/terraform-plugin-sdk/helper/schema" + "github.com/hashicorp/terraform-plugin-sdk/v2/diag" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" + "github.com/rudecs/terraform-provider-decort/internal/constants" ) func flattenAccountTemplatesList(atl AccountTemplatesList) []map[string]interface{} { @@ -50,10 +61,10 @@ func flattenAccountTemplatesList(atl AccountTemplatesList) []map[string]interfac } -func dataSourceAccountTemplatesListRead(d *schema.ResourceData, m interface{}) error { +func dataSourceAccountTemplatesListRead(ctx context.Context, d *schema.ResourceData, m interface{}) diag.Diagnostics { accountTemplatesList, err := utilityAccountTemplatesListCheckPresence(d, m) if err != nil { - return err + return diag.FromErr(err) } id := uuid.New() @@ -123,15 +134,15 @@ func dataSourceAccountTemplatesListSchemaMake() map[string]*schema.Schema { return res } -func dataSourceAccountTemplatessList() *schema.Resource { +func DataSourceAccountTemplatessList() *schema.Resource { return &schema.Resource{ SchemaVersion: 1, - Read: dataSourceAccountTemplatesListRead, + ReadContext: dataSourceAccountTemplatesListRead, Timeouts: &schema.ResourceTimeout{ - Read: &Timeout30s, - Default: &Timeout60s, + Read: &constants.Timeout30s, + Default: &constants.Timeout60s, }, Schema: dataSourceAccountTemplatesListSchemaMake(), diff --git a/decort/data_source_account_vins_list.go b/internal/service/cloudapi/account/data_source_account_vins_list.go similarity index 75% rename from decort/data_source_account_vins_list.go rename to internal/service/cloudapi/account/data_source_account_vins_list.go index e9d50e7..6542018 100644 --- a/decort/data_source_account_vins_list.go +++ b/internal/service/cloudapi/account/data_source_account_vins_list.go @@ -1,6 +1,8 @@ /* Copyright (c) 2019-2022 Digital Energy Cloud Solutions LLC. All Rights Reserved. -Author: Stanislav Solovev, +Authors: +Petr Krutov, +Stanislav Solovev, Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. @@ -16,17 +18,26 @@ limitations under the License. */ /* -This file is part of Terraform (by Hashicorp) provider for Digital Energy Cloud Orchestration -Technology platfom. +Terraform DECORT provider - manage resources provided by DECORT (Digital Energy Cloud +Orchestration Technology) with Terraform by Hashicorp. -Visit https://github.com/rudecs/terraform-provider-decort for full source code package and updates. +Source code: https://github.com/rudecs/terraform-provider-decort + +Please see README.md to learn where to place source code so that it +builds seamlessly. + +Documentation: https://github.com/rudecs/terraform-provider-decort/wiki */ -package decort +package account import ( + "context" + "github.com/google/uuid" - "github.com/hashicorp/terraform-plugin-sdk/helper/schema" + "github.com/hashicorp/terraform-plugin-sdk/v2/diag" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" + "github.com/rudecs/terraform-provider-decort/internal/constants" ) func flattenAccountVinsList(avl AccountVinsList) []map[string]interface{} { @@ -57,10 +68,10 @@ func flattenAccountVinsList(avl AccountVinsList) []map[string]interface{} { } -func dataSourceAccountVinsListRead(d *schema.ResourceData, m interface{}) error { +func dataSourceAccountVinsListRead(ctx context.Context, d *schema.ResourceData, m interface{}) diag.Diagnostics { accountVinsList, err := utilityAccountVinsListCheckPresence(d, m) if err != nil { - return err + return diag.FromErr(err) } id := uuid.New() @@ -158,15 +169,15 @@ func dataSourceAccountVinsListSchemaMake() map[string]*schema.Schema { return res } -func dataSourceAccountVinsList() *schema.Resource { +func DataSourceAccountVinsList() *schema.Resource { return &schema.Resource{ SchemaVersion: 1, - Read: dataSourceAccountVinsListRead, + ReadContext: dataSourceAccountVinsListRead, Timeouts: &schema.ResourceTimeout{ - Read: &Timeout30s, - Default: &Timeout60s, + Read: &constants.Timeout30s, + Default: &constants.Timeout60s, }, Schema: dataSourceAccountVinsListSchemaMake(), diff --git a/internal/service/cloudapi/account/models.go b/internal/service/cloudapi/account/models.go new file mode 100644 index 0000000..e7fca15 --- /dev/null +++ b/internal/service/cloudapi/account/models.go @@ -0,0 +1,260 @@ +/* +Copyright (c) 2019-2022 Digital Energy Cloud Solutions LLC. All Rights Reserved. +Authors: +Petr Krutov, +Stanislav Solovev, + +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. +*/ + +/* +Terraform DECORT provider - manage resources provided by DECORT (Digital Energy Cloud +Orchestration Technology) with Terraform by Hashicorp. + +Source code: https://github.com/rudecs/terraform-provider-decort + +Please see README.md to learn where to place source code so that it +builds seamlessly. + +Documentation: https://github.com/rudecs/terraform-provider-decort/wiki +*/ + +package account + +type AccountAclRecord struct { + IsExplicit bool `json:"explicit"` + Guid string `json:"guid"` + Rights string `json:"right"` + Status string `json:"status"` + Type string `json:"type"` + UgroupID string `json:"userGroupId"` + CanBeDeleted bool `json:"canBeDeleted"` +} + +type ResourceLimits struct { + CUC float64 `json:"CU_C"` + CUD float64 `json:"CU_D"` + CUI float64 `json:"CU_I"` + CUM float64 `json:"CU_M"` + CUNP float64 `json:"CU_NP"` + GpuUnits float64 `json:"gpu_units"` +} + +type Account struct { + DCLocation string `json:"DCLocation"` + CKey string `jspn:"_ckey"` + Meta []interface{} `json:"_meta"` + Acl []AccountAclRecord `json:"acl"` + Company string `json:"company"` + CompanyUrl string `json:"companyurl"` + CreatedBy string `jspn:"createdBy"` + CreatedTime int `json:"createdTime"` + DeactiovationTime float64 `json:"deactivationTime"` + DeletedBy string `json:"deletedBy"` + DeletedTime int `json:"deletedTime"` + DisplayName string `json:"displayname"` + GUID int `json:"guid"` + ID int `json:"id"` + Name string `json:"name"` + ResourceLimits ResourceLimits `json:"resourceLimits"` + SendAccessEmails bool `json:"sendAccessEmails"` + ServiceAccount bool `json:"serviceAccount"` + Status string `json:"status"` + UpdatedTime int `json:"updatedTime"` + Version int `json:"version"` + Vins []int `json:"vins"` +} + +type AccountList []Account + +type AccountCloudApi struct { + Acl []AccountAclRecord `json:"acl"` + CreatedTime int `json:"createdTime"` + DeletedTime int `json:"deletedTime"` + ID int `json:"id"` + Name string `json:"name"` + Status string `json:"status"` + UpdatedTime int `json:"updatedTime"` +} + +type AccountCloudApiList []AccountCloudApi + +type Resource struct { + CPU int `json:"cpu"` + Disksize int `json:"disksize"` + Extips int `json:"extips"` + Exttraffic int `json:"exttraffic"` + GPU int `json:"gpu"` + RAM int `json:"ram"` +} + +type Resources struct { + Current Resource `json:"Current"` + Reserved Resource `json:"Reserved"` +} + +type Computes struct { + Started int `json:"started"` + Stopped int `json:"stopped"` +} + +type Machines struct { + Running int `json:"running"` + Halted int `json:"halted"` +} + +type AccountWithResources struct { + Account + Resources Resources `json:"Resources"` + Computes Computes `json:"computes"` + Machines Machines `json:"machines"` + Vinses int `json:"vinses"` +} + +type AccountCompute struct { + AccountId int `json:"accountId"` + AccountName string `json:"accountName"` + CPUs int `json:"cpus"` + CreatedBy string `json:"createdBy"` + CreatedTime int `json:"createdTime"` + DeletedBy string `json:"deletedBy"` + DeletedTime int `json:"deletedTime"` + ComputeId int `json:"id"` + ComputeName string `json:"name"` + RAM int `json:"ram"` + Registered bool `json:"registered"` + RgId int `json:"rgId"` + RgName string `json:"rgName"` + Status string `json:"status"` + TechStatus string `json:"techStatus"` + TotalDisksSize int `json:"totalDisksSize"` + UpdatedBy string `json:"updatedBy"` + UpdatedTime int `json:"updatedTime"` + UserManaged bool `json:"userManaged"` + VinsConnected int `json:"vinsConnected"` +} + +type AccountComputesList []AccountCompute + +type AccountDisk struct { + ID int `json:"id"` + Name string `json:"name"` + Pool string `json:"pool"` + SepId int `json:"sepId"` + SizeMax int `json:"sizeMax"` + Type string `json:"type"` +} + +type AccountDisksList []AccountDisk + +type AccountVin struct { + AccountId int `json:"accountId"` + AccountName string `json:"accountName"` + Computes int `json:"computes"` + CreatedBy string `json:"createdBy"` + CreatedTime int `json:"createdTime"` + DeletedBy string `json:"deletedBy"` + DeletedTime int `json:"deletedTime"` + ExternalIP string `json:"externalIP"` + ID int `json:"id"` + Name string `json:"name"` + Network string `json:"network"` + PriVnfDevId int `json:"priVnfDevId"` + RgId int `json:"rgId"` + RgName string `json:"rgName"` + Status string `json:"status"` + UpdatedBy string `json:"updatedBy"` + UpdatedTime int `json:"updatedTime"` +} + +type AccountVinsList []AccountVin + +type AccountAudit struct { + Call string `json:"call"` + ResponseTime float64 `json:"responsetime"` + StatusCode int `json:"statuscode"` + Timestamp float64 `json:"timestamp"` + User string `json:"user"` +} + +type AccountAuditsList []AccountAudit + +type AccountRGComputes struct { + Started int `json:"Started"` + Stopped int `json:"Stopped"` +} + +type AccountRGResources struct { + Consumed Resource `json:"Consumed"` + Limits Resource `json:"Limits"` + Reserved Resource `json:"Reserved"` +} + +type AccountRG struct { + Computes AccountRGComputes `json:"Computes"` + Resources AccountRGResources `json:"Resources"` + CreatedBy string `json:"createdBy"` + CreatedTime int `json:"createdTime"` + DeletedBy string `json:"deletedBy"` + DeletedTime int `json:"deletedTime"` + RGID int `json:"id"` + Milestones int `json:"milestones"` + RGName string `json:"name"` + Status string `json:"status"` + UpdatedBy string `json:"updatedBy"` + UpdatedTime int `json:"updatedTime"` + Vinses int `json:"vinses"` +} + +type AccountRGList []AccountRG + +type AccountTemplate struct { + UNCPath string `json:"UNCPath"` + AccountId int `json:"accountId"` + Desc string `json:"desc"` + ID int `json:"id"` + Name string `json:"name"` + Public bool `json:"public"` + Size int `json:"size"` + Status string `json:"status"` + Type string `json:"type"` + Username string `json:"username"` +} + +type AccountTemplatesList []AccountTemplate + +type AccountFlipGroup struct { + AccountId int `json:"accountId"` + ClientType string `json:"clientType"` + ConnType string `json:"connType"` + CreatedBy string `json:"createdBy"` + CreatedTime int `json:"createdTime"` + DefaultGW string `json:"defaultGW"` + DeletedBy string `json:"deletedBy"` + DeletedTime int `json:"deletedTime"` + Desc string `json:"desc"` + GID int `json:"gid"` + GUID int `json:"guid"` + ID int `json:"id"` + IP string `json:"ip"` + Milestones int `json:"milestones"` + Name string `json:"name"` + NetID int `json:"netId"` + NetType string `json:"netType"` + NetMask int `json:"netmask"` + Status string `json:"status"` + UpdatedBy string `json:"updatedBy"` + UpdatedTime int `json:"updatedTime"` +} + +type AccountFlipGroupsList []AccountFlipGroup diff --git a/decort/resource_account.go b/internal/service/cloudapi/account/resource_account.go similarity index 81% rename from decort/resource_account.go rename to internal/service/cloudapi/account/resource_account.go index 66fc97c..14a1222 100644 --- a/decort/resource_account.go +++ b/internal/service/cloudapi/account/resource_account.go @@ -1,6 +1,8 @@ /* Copyright (c) 2019-2022 Digital Energy Cloud Solutions LLC. All Rights Reserved. -Author: Stanislav Solovev, +Authors: +Petr Krutov, +Stanislav Solovev, Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. @@ -16,45 +18,54 @@ limitations under the License. */ /* -This file is part of Terraform (by Hashicorp) provider for Digital Energy Cloud Orchestration -Technology platfom. +Terraform DECORT provider - manage resources provided by DECORT (Digital Energy Cloud +Orchestration Technology) with Terraform by Hashicorp. -Visit https://github.com/rudecs/terraform-provider-decort for full source code package and updates. +Source code: https://github.com/rudecs/terraform-provider-decort + +Please see README.md to learn where to place source code so that it +builds seamlessly. + +Documentation: https://github.com/rudecs/terraform-provider-decort/wiki */ -package decort +package account import ( - "errors" + "context" "net/url" "strconv" "strings" "github.com/google/uuid" - "github.com/hashicorp/terraform-plugin-sdk/helper/schema" + "github.com/hashicorp/terraform-plugin-sdk/v2/diag" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" + "github.com/rudecs/terraform-provider-decort/internal/constants" + "github.com/rudecs/terraform-provider-decort/internal/controller" + "github.com/rudecs/terraform-provider-decort/internal/flattens" log "github.com/sirupsen/logrus" ) -func resourceAccountCreate(d *schema.ResourceData, m interface{}) error { +func resourceAccountCreate(ctx context.Context, d *schema.ResourceData, m interface{}) diag.Diagnostics { log.Debugf("resourceAccountCreate") if accountId, ok := d.GetOk("account_id"); ok { if exists, err := resourceAccountExists(d, m); exists { if err != nil { - return err + return diag.FromErr(err) } d.SetId(strconv.Itoa(accountId.(int))) - err = resourceAccountRead(d, m) - if err != nil { - return err + diagnostics := resourceAccountRead(ctx, d, m) + if diagnostics != nil { + return diagnostics } return nil } - return errors.New("provided account id does not exist") + return diag.Errorf("provided account id does not exist") } - controller := m.(*ControllerCfg) + c := m.(*controller.ControllerCfg) urlValues := &url.Values{} urlValues.Add("name", d.Get("account_name").(string)) @@ -122,18 +133,18 @@ func resourceAccountCreate(d *schema.ResourceData, m interface{}) error { } } - accountId, err := controller.decortAPICall("POST", accountCreateAPI, urlValues) + accountId, err := c.DecortAPICall("POST", accountCreateAPI, urlValues) if err != nil { - return err + return diag.FromErr(err) } id := uuid.New() d.SetId(accountId) d.Set("account_id", accountId) - err = resourceAccountRead(d, m) - if err != nil { - return err + diagnostics := resourceAccountRead(ctx, d, m) + if diagnostics != nil { + return diagnostics } d.SetId(id.String()) @@ -141,19 +152,19 @@ func resourceAccountCreate(d *schema.ResourceData, m interface{}) error { return nil } -func resourceAccountRead(d *schema.ResourceData, m interface{}) error { +func resourceAccountRead(ctx context.Context, d *schema.ResourceData, m interface{}) diag.Diagnostics { log.Debugf("resourceAccountRead") acc, err := utilityAccountCheckPresence(d, m) if acc == nil { d.SetId("") - return err + return diag.FromErr(err) } d.Set("dc_location", acc.DCLocation) d.Set("resources", flattenAccResources(acc.Resources)) d.Set("ckey", acc.CKey) - d.Set("meta", flattenMeta(acc.Meta)) + d.Set("meta", flattens.FlattenMeta(acc.Meta)) d.Set("acl", flattenAccAcl(acc.Acl)) d.Set("company", acc.Company) d.Set("companyurl", acc.CompanyUrl) @@ -180,25 +191,25 @@ func resourceAccountRead(d *schema.ResourceData, m interface{}) error { return nil } -func resourceAccountDelete(d *schema.ResourceData, m interface{}) error { +func resourceAccountDelete(ctx context.Context, d *schema.ResourceData, m interface{}) diag.Diagnostics { log.Debugf("resourceAccountDelete") account, err := utilityAccountCheckPresence(d, m) if account == nil { if err != nil { - return err + return diag.FromErr(err) } return nil } - controller := m.(*ControllerCfg) + c := m.(*controller.ControllerCfg) urlValues := &url.Values{} urlValues.Add("accountId", strconv.Itoa(d.Get("account_id").(int))) urlValues.Add("permanently", strconv.FormatBool(d.Get("permanently").(bool))) - _, err = controller.decortAPICall("POST", accountDeleteAPI, urlValues) + _, err = c.DecortAPICall("POST", accountDeleteAPI, urlValues) if err != nil { - return err + return diag.FromErr(err) } d.SetId("") @@ -219,9 +230,9 @@ func resourceAccountExists(d *schema.ResourceData, m interface{}) (bool, error) return true, nil } -func resourceAccountEdit(d *schema.ResourceData, m interface{}) error { +func resourceAccountEdit(ctx context.Context, d *schema.ResourceData, m interface{}) diag.Diagnostics { log.Debugf("resourceAccountEdit") - c := m.(*ControllerCfg) + c := m.(*controller.ControllerCfg) urlValues := &url.Values{} if d.HasChange("enable") { @@ -232,9 +243,9 @@ func resourceAccountEdit(d *schema.ResourceData, m interface{}) error { } urlValues.Add("accountId", strconv.Itoa(d.Get("account_id").(int))) - _, err := c.decortAPICall("POST", api, urlValues) + _, err := c.DecortAPICall("POST", api, urlValues) if err != nil { - return err + return diag.FromErr(err) } urlValues = &url.Values{} @@ -243,9 +254,9 @@ func resourceAccountEdit(d *schema.ResourceData, m interface{}) error { if d.HasChange("account_name") { urlValues.Add("name", d.Get("account_name").(string)) urlValues.Add("accountId", strconv.Itoa(d.Get("account_id").(int))) - _, err := c.decortAPICall("POST", accountUpdateAPI, urlValues) + _, err := c.DecortAPICall("POST", accountUpdateAPI, urlValues) if err != nil { - return err + return diag.FromErr(err) } urlValues = &url.Values{} @@ -307,9 +318,9 @@ func resourceAccountEdit(d *schema.ResourceData, m interface{}) error { } urlValues.Add("accountId", strconv.Itoa(d.Get("account_id").(int))) - _, err := c.decortAPICall("POST", accountUpdateAPI, urlValues) + _, err := c.DecortAPICall("POST", accountUpdateAPI, urlValues) if err != nil { - return err + return diag.FromErr(err) } urlValues = &url.Values{} @@ -318,9 +329,9 @@ func resourceAccountEdit(d *schema.ResourceData, m interface{}) error { if d.HasChange("send_access_emails") { urlValues.Add("sendAccessEmails", strconv.FormatBool(d.Get("send_access_emails").(bool))) urlValues.Add("accountId", strconv.Itoa(d.Get("account_id").(int))) - _, err := c.decortAPICall("POST", accountUpdateAPI, urlValues) + _, err := c.DecortAPICall("POST", accountUpdateAPI, urlValues) if err != nil { - return err + return diag.FromErr(err) } urlValues = &url.Values{} @@ -330,9 +341,9 @@ func resourceAccountEdit(d *schema.ResourceData, m interface{}) error { restore := d.Get("restore").(bool) if restore { urlValues.Add("accountId", strconv.Itoa(d.Get("account_id").(int))) - _, err := c.decortAPICall("POST", accountRestoreAPI, urlValues) + _, err := c.DecortAPICall("POST", accountRestoreAPI, urlValues) if err != nil { - return err + return diag.FromErr(err) } urlValues = &url.Values{} @@ -368,9 +379,9 @@ func resourceAccountEdit(d *schema.ResourceData, m interface{}) error { urlValues.Add("accountId", strconv.Itoa(d.Get("account_id").(int))) urlValues.Add("userId", userConv["user_id"].(string)) urlValues.Add("recursivedelete", strconv.FormatBool(userConv["recursive_delete"].(bool))) - _, err := c.decortAPICall("POST", accountDeleteUserAPI, urlValues) + _, err := c.DecortAPICall("POST", accountDeleteUserAPI, urlValues) if err != nil { - return err + return diag.FromErr(err) } urlValues = &url.Values{} @@ -383,9 +394,9 @@ func resourceAccountEdit(d *schema.ResourceData, m interface{}) error { urlValues.Add("accountId", strconv.Itoa(d.Get("account_id").(int))) urlValues.Add("userId", userConv["user_id"].(string)) urlValues.Add("accesstype", strings.ToUpper(userConv["access_type"].(string))) - _, err := c.decortAPICall("POST", accountAddUserAPI, urlValues) + _, err := c.DecortAPICall("POST", accountAddUserAPI, urlValues) if err != nil { - return err + return diag.FromErr(err) } urlValues = &url.Values{} @@ -398,9 +409,9 @@ func resourceAccountEdit(d *schema.ResourceData, m interface{}) error { urlValues.Add("accountId", strconv.Itoa(d.Get("account_id").(int))) urlValues.Add("userId", userConv["user_id"].(string)) urlValues.Add("accesstype", strings.ToUpper(userConv["access_type"].(string))) - _, err := c.decortAPICall("POST", accountUpdateUserAPI, urlValues) + _, err := c.DecortAPICall("POST", accountUpdateUserAPI, urlValues) if err != nil { - return err + return diag.FromErr(err) } urlValues = &url.Values{} @@ -767,26 +778,26 @@ func resourceAccountSchemaMake() map[string]*schema.Schema { } } -func resourceAccount() *schema.Resource { +func ResourceAccount() *schema.Resource { return &schema.Resource{ SchemaVersion: 1, - Create: resourceAccountCreate, - Read: resourceAccountRead, - Update: resourceAccountEdit, - Delete: resourceAccountDelete, - Exists: resourceAccountExists, + CreateContext: resourceAccountCreate, + ReadContext: resourceAccountRead, + UpdateContext: resourceAccountEdit, + DeleteContext: resourceAccountDelete, + Exists: resourceAccountExists, Importer: &schema.ResourceImporter{ State: schema.ImportStatePassthrough, }, Timeouts: &schema.ResourceTimeout{ - Create: &Timeout60s, - Read: &Timeout30s, - Update: &Timeout60s, - Delete: &Timeout60s, - Default: &Timeout60s, + Create: &constants.Timeout60s, + Read: &constants.Timeout30s, + Update: &constants.Timeout60s, + Delete: &constants.Timeout60s, + Default: &constants.Timeout60s, }, Schema: resourceAccountSchemaMake(), diff --git a/decort/utility_account.go b/internal/service/cloudapi/account/utility_account.go similarity index 63% rename from decort/utility_account.go rename to internal/service/cloudapi/account/utility_account.go index 136a939..5d89df6 100644 --- a/decort/utility_account.go +++ b/internal/service/cloudapi/account/utility_account.go @@ -1,6 +1,8 @@ /* Copyright (c) 2019-2022 Digital Energy Cloud Solutions LLC. All Rights Reserved. -Author: Stanislav Solovev, , +Authors: +Petr Krutov, +Stanislav Solovev, Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. @@ -16,27 +18,33 @@ limitations under the License. */ /* -This file is part of Terraform (by Hashicorp) provider for Digital Energy Cloud Orchestration -Technology platfom. +Terraform DECORT provider - manage resources provided by DECORT (Digital Energy Cloud +Orchestration Technology) with Terraform by Hashicorp. -Visit https://github.com/rudecs/terraform-provider-decort for full source code package and updates. +Source code: https://github.com/rudecs/terraform-provider-decort + +Please see README.md to learn where to place source code so that it +builds seamlessly. + +Documentation: https://github.com/rudecs/terraform-provider-decort/wiki */ -package decort +package account import ( "encoding/json" "net/url" "strconv" + "github.com/rudecs/terraform-provider-decort/internal/controller" log "github.com/sirupsen/logrus" - "github.com/hashicorp/terraform-plugin-sdk/helper/schema" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" ) func utilityAccountCheckPresence(d *schema.ResourceData, m interface{}) (*AccountWithResources, error) { account := &AccountWithResources{} - controller := m.(*ControllerCfg) + c := m.(*controller.ControllerCfg) urlValues := &url.Values{} if (strconv.Itoa(d.Get("account_id").(int))) != "0" { @@ -46,7 +54,7 @@ func utilityAccountCheckPresence(d *schema.ResourceData, m interface{}) (*Accoun } log.Debugf("utilityAccountCheckPresence: load account") - accountRaw, err := controller.decortAPICall("POST", accountGetAPI, urlValues) + accountRaw, err := c.DecortAPICall("POST", accountGetAPI, urlValues) if err != nil { return nil, err } diff --git a/decort/utility_account_audits_list.go b/internal/service/cloudapi/account/utility_account_audits_list.go similarity index 60% rename from decort/utility_account_audits_list.go rename to internal/service/cloudapi/account/utility_account_audits_list.go index 283c513..dc61dc8 100644 --- a/decort/utility_account_audits_list.go +++ b/internal/service/cloudapi/account/utility_account_audits_list.go @@ -1,6 +1,8 @@ /* Copyright (c) 2019-2022 Digital Energy Cloud Solutions LLC. All Rights Reserved. -Author: Stanislav Solovev, , +Authors: +Petr Krutov, +Stanislav Solovev, Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. @@ -16,33 +18,39 @@ limitations under the License. */ /* -This file is part of Terraform (by Hashicorp) provider for Digital Energy Cloud Orchestration -Technology platfom. +Terraform DECORT provider - manage resources provided by DECORT (Digital Energy Cloud +Orchestration Technology) with Terraform by Hashicorp. -Visit https://github.com/rudecs/terraform-provider-decort for full source code package and updates. +Source code: https://github.com/rudecs/terraform-provider-decort + +Please see README.md to learn where to place source code so that it +builds seamlessly. + +Documentation: https://github.com/rudecs/terraform-provider-decort/wiki */ -package decort +package account import ( "encoding/json" "net/url" "strconv" + "github.com/rudecs/terraform-provider-decort/internal/controller" log "github.com/sirupsen/logrus" - "github.com/hashicorp/terraform-plugin-sdk/helper/schema" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" ) func utilityAccountAuditsListCheckPresence(d *schema.ResourceData, m interface{}) (AccountAuditsList, error) { accountAuditsList := AccountAuditsList{} - controller := m.(*ControllerCfg) + c := m.(*controller.ControllerCfg) urlValues := &url.Values{} urlValues.Add("accountId", strconv.Itoa(d.Get("account_id").(int))) log.Debugf("utilityAccountAuditsListCheckPresence: load account list") - accountAuditsListRaw, err := controller.decortAPICall("POST", accountAuditsAPI, urlValues) + accountAuditsListRaw, err := c.DecortAPICall("POST", accountAuditsAPI, urlValues) if err != nil { return nil, err } diff --git a/decort/utility_account_computes_list.go b/internal/service/cloudapi/account/utility_account_computes_list.go similarity index 60% rename from decort/utility_account_computes_list.go rename to internal/service/cloudapi/account/utility_account_computes_list.go index 6c92590..957af49 100644 --- a/decort/utility_account_computes_list.go +++ b/internal/service/cloudapi/account/utility_account_computes_list.go @@ -1,6 +1,8 @@ /* Copyright (c) 2019-2022 Digital Energy Cloud Solutions LLC. All Rights Reserved. -Author: Stanislav Solovev, , +Authors: +Petr Krutov, +Stanislav Solovev, Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. @@ -16,33 +18,39 @@ limitations under the License. */ /* -This file is part of Terraform (by Hashicorp) provider for Digital Energy Cloud Orchestration -Technology platfom. +Terraform DECORT provider - manage resources provided by DECORT (Digital Energy Cloud +Orchestration Technology) with Terraform by Hashicorp. -Visit https://github.com/rudecs/terraform-provider-decort for full source code package and updates. +Source code: https://github.com/rudecs/terraform-provider-decort + +Please see README.md to learn where to place source code so that it +builds seamlessly. + +Documentation: https://github.com/rudecs/terraform-provider-decort/wiki */ -package decort +package account import ( "encoding/json" "net/url" "strconv" + "github.com/rudecs/terraform-provider-decort/internal/controller" log "github.com/sirupsen/logrus" - "github.com/hashicorp/terraform-plugin-sdk/helper/schema" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" ) func utilityAccountComputesListCheckPresence(d *schema.ResourceData, m interface{}) (AccountComputesList, error) { accountComputesList := AccountComputesList{} - controller := m.(*ControllerCfg) + c := m.(*controller.ControllerCfg) urlValues := &url.Values{} urlValues.Add("accountId", strconv.Itoa(d.Get("account_id").(int))) log.Debugf("utilityAccountComputesListCheckPresence: load account list") - accountComputesListRaw, err := controller.decortAPICall("POST", accountListComputesAPI, urlValues) + accountComputesListRaw, err := c.DecortAPICall("POST", accountListComputesAPI, urlValues) if err != nil { return nil, err } diff --git a/decort/utility_account_consumed_units.go b/internal/service/cloudapi/account/utility_account_consumed_units.go similarity index 60% rename from decort/utility_account_consumed_units.go rename to internal/service/cloudapi/account/utility_account_consumed_units.go index b5cdd1e..295a4fe 100644 --- a/decort/utility_account_consumed_units.go +++ b/internal/service/cloudapi/account/utility_account_consumed_units.go @@ -1,6 +1,8 @@ /* Copyright (c) 2019-2022 Digital Energy Cloud Solutions LLC. All Rights Reserved. -Author: Stanislav Solovev, , +Authors: +Petr Krutov, +Stanislav Solovev, Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. @@ -16,33 +18,39 @@ limitations under the License. */ /* -This file is part of Terraform (by Hashicorp) provider for Digital Energy Cloud Orchestration -Technology platfom. +Terraform DECORT provider - manage resources provided by DECORT (Digital Energy Cloud +Orchestration Technology) with Terraform by Hashicorp. -Visit https://github.com/rudecs/terraform-provider-decort for full source code package and updates. +Source code: https://github.com/rudecs/terraform-provider-decort + +Please see README.md to learn where to place source code so that it +builds seamlessly. + +Documentation: https://github.com/rudecs/terraform-provider-decort/wiki */ -package decort +package account import ( "encoding/json" "net/url" "strconv" + "github.com/rudecs/terraform-provider-decort/internal/controller" log "github.com/sirupsen/logrus" - "github.com/hashicorp/terraform-plugin-sdk/helper/schema" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" ) func utilityAccountConsumedUnitsCheckPresence(d *schema.ResourceData, m interface{}) (*ResourceLimits, error) { accountConsumedUnits := &ResourceLimits{} - controller := m.(*ControllerCfg) + c := m.(*controller.ControllerCfg) urlValues := &url.Values{} urlValues.Add("accountId", strconv.Itoa(d.Get("account_id").(int))) log.Debugf("utilityAccountConsumedUnitsCheckPresence: load account list") - accountConsumedUnitsRaw, err := controller.decortAPICall("POST", accountGetConsumedUnitsAPI, urlValues) + accountConsumedUnitsRaw, err := c.DecortAPICall("POST", accountGetConsumedUnitsAPI, urlValues) if err != nil { return nil, err } diff --git a/decort/utility_account_consumed_units_by_type.go b/internal/service/cloudapi/account/utility_account_consumed_units_by_type.go similarity index 59% rename from decort/utility_account_consumed_units_by_type.go rename to internal/service/cloudapi/account/utility_account_consumed_units_by_type.go index d0d65f2..f102c01 100644 --- a/decort/utility_account_consumed_units_by_type.go +++ b/internal/service/cloudapi/account/utility_account_consumed_units_by_type.go @@ -1,6 +1,8 @@ /* Copyright (c) 2019-2022 Digital Energy Cloud Solutions LLC. All Rights Reserved. -Author: Stanislav Solovev, , +Authors: +Petr Krutov, +Stanislav Solovev, Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. @@ -16,33 +18,39 @@ limitations under the License. */ /* -This file is part of Terraform (by Hashicorp) provider for Digital Energy Cloud Orchestration -Technology platfom. +Terraform DECORT provider - manage resources provided by DECORT (Digital Energy Cloud +Orchestration Technology) with Terraform by Hashicorp. -Visit https://github.com/rudecs/terraform-provider-decort for full source code package and updates. +Source code: https://github.com/rudecs/terraform-provider-decort + +Please see README.md to learn where to place source code so that it +builds seamlessly. + +Documentation: https://github.com/rudecs/terraform-provider-decort/wiki */ -package decort +package account import ( "net/url" "strconv" "strings" + "github.com/rudecs/terraform-provider-decort/internal/controller" log "github.com/sirupsen/logrus" - "github.com/hashicorp/terraform-plugin-sdk/helper/schema" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" ) func utilityAccountConsumedUnitsByTypeCheckPresence(d *schema.ResourceData, m interface{}) (float64, error) { - controller := m.(*ControllerCfg) + c := m.(*controller.ControllerCfg) urlValues := &url.Values{} urlValues.Add("accountId", strconv.Itoa(d.Get("account_id").(int))) urlValues.Add("cutype", strings.ToUpper(d.Get("cu_type").(string))) log.Debugf("utilityAccountConsumedUnitsByTypeCheckPresence") - resultRaw, err := controller.decortAPICall("POST", accountGetConsumedUnitsByTypeAPI, urlValues) + resultRaw, err := c.DecortAPICall("POST", accountGetConsumedUnitsByTypeAPI, urlValues) if err != nil { return 0, err } diff --git a/decort/utility_account_deleted_list.go b/internal/service/cloudapi/account/utility_account_deleted_list.go similarity index 61% rename from decort/utility_account_deleted_list.go rename to internal/service/cloudapi/account/utility_account_deleted_list.go index 7c82750..2395001 100644 --- a/decort/utility_account_deleted_list.go +++ b/internal/service/cloudapi/account/utility_account_deleted_list.go @@ -1,6 +1,8 @@ /* Copyright (c) 2019-2022 Digital Energy Cloud Solutions LLC. All Rights Reserved. -Author: Stanislav Solovev, , +Authors: +Petr Krutov, +Stanislav Solovev, Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. @@ -16,27 +18,33 @@ limitations under the License. */ /* -This file is part of Terraform (by Hashicorp) provider for Digital Energy Cloud Orchestration -Technology platfom. +Terraform DECORT provider - manage resources provided by DECORT (Digital Energy Cloud +Orchestration Technology) with Terraform by Hashicorp. -Visit https://github.com/rudecs/terraform-provider-decort for full source code package and updates. +Source code: https://github.com/rudecs/terraform-provider-decort + +Please see README.md to learn where to place source code so that it +builds seamlessly. + +Documentation: https://github.com/rudecs/terraform-provider-decort/wiki */ -package decort +package account import ( "encoding/json" "net/url" "strconv" + "github.com/rudecs/terraform-provider-decort/internal/controller" log "github.com/sirupsen/logrus" - "github.com/hashicorp/terraform-plugin-sdk/helper/schema" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" ) func utilityAccountDeletedListCheckPresence(d *schema.ResourceData, m interface{}) (AccountCloudApiList, error) { accountDeletedList := AccountCloudApiList{} - controller := m.(*ControllerCfg) + c := m.(*controller.ControllerCfg) urlValues := &url.Values{} if page, ok := d.GetOk("page"); ok { @@ -47,7 +55,7 @@ func utilityAccountDeletedListCheckPresence(d *schema.ResourceData, m interface{ } log.Debugf("utilityAccountDeletedListCheckPresence: load") - accountDeletedListRaw, err := controller.decortAPICall("POST", accountListDeletedAPI, urlValues) + accountDeletedListRaw, err := c.DecortAPICall("POST", accountListDeletedAPI, urlValues) if err != nil { return nil, err } diff --git a/decort/utility_account_disks_list.go b/internal/service/cloudapi/account/utility_account_disks_list.go similarity index 59% rename from decort/utility_account_disks_list.go rename to internal/service/cloudapi/account/utility_account_disks_list.go index 941a2bc..4c0dbd3 100644 --- a/decort/utility_account_disks_list.go +++ b/internal/service/cloudapi/account/utility_account_disks_list.go @@ -1,6 +1,8 @@ /* Copyright (c) 2019-2022 Digital Energy Cloud Solutions LLC. All Rights Reserved. -Author: Stanislav Solovev, , +Authors: +Petr Krutov, +Stanislav Solovev, Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. @@ -16,33 +18,39 @@ limitations under the License. */ /* -This file is part of Terraform (by Hashicorp) provider for Digital Energy Cloud Orchestration -Technology platfom. +Terraform DECORT provider - manage resources provided by DECORT (Digital Energy Cloud +Orchestration Technology) with Terraform by Hashicorp. -Visit https://github.com/rudecs/terraform-provider-decort for full source code package and updates. +Source code: https://github.com/rudecs/terraform-provider-decort + +Please see README.md to learn where to place source code so that it +builds seamlessly. + +Documentation: https://github.com/rudecs/terraform-provider-decort/wiki */ -package decort +package account import ( "encoding/json" "net/url" "strconv" + "github.com/rudecs/terraform-provider-decort/internal/controller" log "github.com/sirupsen/logrus" - "github.com/hashicorp/terraform-plugin-sdk/helper/schema" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" ) func utilityAccountDisksListCheckPresence(d *schema.ResourceData, m interface{}) (AccountDisksList, error) { accountDisksList := AccountDisksList{} - controller := m.(*ControllerCfg) + c := m.(*controller.ControllerCfg) urlValues := &url.Values{} urlValues.Add("accountId", strconv.Itoa(d.Get("account_id").(int))) log.Debugf("utilityAccountDisksListCheckPresence: load account list") - accountDisksListRaw, err := controller.decortAPICall("POST", accountListDisksAPI, urlValues) + accountDisksListRaw, err := c.DecortAPICall("POST", accountListDisksAPI, urlValues) if err != nil { return nil, err } diff --git a/decort/utility_account_flip_groups.go b/internal/service/cloudapi/account/utility_account_flip_groups.go similarity index 60% rename from decort/utility_account_flip_groups.go rename to internal/service/cloudapi/account/utility_account_flip_groups.go index df2c36b..d2862b5 100644 --- a/decort/utility_account_flip_groups.go +++ b/internal/service/cloudapi/account/utility_account_flip_groups.go @@ -1,6 +1,8 @@ /* Copyright (c) 2019-2022 Digital Energy Cloud Solutions LLC. All Rights Reserved. -Author: Stanislav Solovev, , +Authors: +Petr Krutov, +Stanislav Solovev, Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. @@ -16,33 +18,39 @@ limitations under the License. */ /* -This file is part of Terraform (by Hashicorp) provider for Digital Energy Cloud Orchestration -Technology platfom. +Terraform DECORT provider - manage resources provided by DECORT (Digital Energy Cloud +Orchestration Technology) with Terraform by Hashicorp. -Visit https://github.com/rudecs/terraform-provider-decort for full source code package and updates. +Source code: https://github.com/rudecs/terraform-provider-decort + +Please see README.md to learn where to place source code so that it +builds seamlessly. + +Documentation: https://github.com/rudecs/terraform-provider-decort/wiki */ -package decort +package account import ( "encoding/json" "net/url" "strconv" + "github.com/rudecs/terraform-provider-decort/internal/controller" log "github.com/sirupsen/logrus" - "github.com/hashicorp/terraform-plugin-sdk/helper/schema" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" ) func utilityAccountFlipGroupsListCheckPresence(d *schema.ResourceData, m interface{}) (AccountFlipGroupsList, error) { accountFlipGroupsList := AccountFlipGroupsList{} - controller := m.(*ControllerCfg) + c := m.(*controller.ControllerCfg) urlValues := &url.Values{} urlValues.Add("accountId", strconv.Itoa(d.Get("account_id").(int))) log.Debugf("utilityAccountFlipGroupsListCheckPresence") - accountFlipGroupsListRaw, err := controller.decortAPICall("POST", accountListFlipGroupsAPI, urlValues) + accountFlipGroupsListRaw, err := c.DecortAPICall("POST", accountListFlipGroupsAPI, urlValues) if err != nil { return nil, err } diff --git a/decort/utility_account_list.go b/internal/service/cloudapi/account/utility_account_list.go similarity index 70% rename from decort/utility_account_list.go rename to internal/service/cloudapi/account/utility_account_list.go index 0dd3514..3d814ff 100644 --- a/decort/utility_account_list.go +++ b/internal/service/cloudapi/account/utility_account_list.go @@ -1,6 +1,8 @@ /* Copyright (c) 2019-2022 Digital Energy Cloud Solutions LLC. All Rights Reserved. -Author: Stanislav Solovev, , +Authors: +Petr Krutov, +Stanislav Solovev, Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. @@ -16,27 +18,33 @@ limitations under the License. */ /* -This file is part of Terraform (by Hashicorp) provider for Digital Energy Cloud Orchestration -Technology platfom. +Terraform DECORT provider - manage resources provided by DECORT (Digital Energy Cloud +Orchestration Technology) with Terraform by Hashicorp. -Visit https://github.com/rudecs/terraform-provider-decort for full source code package and updates. +Source code: https://github.com/rudecs/terraform-provider-decort + +Please see README.md to learn where to place source code so that it +builds seamlessly. + +Documentation: https://github.com/rudecs/terraform-provider-decort/wiki */ -package decort +package account import ( "encoding/json" "net/url" "strconv" + "github.com/rudecs/terraform-provider-decort/internal/controller" log "github.com/sirupsen/logrus" - "github.com/hashicorp/terraform-plugin-sdk/helper/schema" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" ) func utilityAccountListCheckPresence(d *schema.ResourceData, m interface{}) (AccountCloudApiList, error) { accountList := AccountCloudApiList{} - controller := m.(*ControllerCfg) + c := m.(*controller.ControllerCfg) urlValues := &url.Values{} if page, ok := d.GetOk("page"); ok { @@ -47,7 +55,7 @@ func utilityAccountListCheckPresence(d *schema.ResourceData, m interface{}) (Acc } log.Debugf("utilityAccountListCheckPresence: load account list") - accountListRaw, err := controller.decortAPICall("POST", accountListAPI, urlValues) + accountListRaw, err := c.DecortAPICall("POST", accountListAPI, urlValues) if err != nil { return nil, err } diff --git a/decort/utility_account_reserved_units.go b/internal/service/cloudapi/account/utility_account_reserved_units.go similarity index 59% rename from decort/utility_account_reserved_units.go rename to internal/service/cloudapi/account/utility_account_reserved_units.go index 31bd4b9..599964c 100644 --- a/decort/utility_account_reserved_units.go +++ b/internal/service/cloudapi/account/utility_account_reserved_units.go @@ -1,6 +1,8 @@ /* Copyright (c) 2019-2022 Digital Energy Cloud Solutions LLC. All Rights Reserved. -Author: Stanislav Solovev, , +Authors: +Petr Krutov, +Stanislav Solovev, Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. @@ -16,33 +18,39 @@ limitations under the License. */ /* -This file is part of Terraform (by Hashicorp) provider for Digital Energy Cloud Orchestration -Technology platfom. +Terraform DECORT provider - manage resources provided by DECORT (Digital Energy Cloud +Orchestration Technology) with Terraform by Hashicorp. -Visit https://github.com/rudecs/terraform-provider-decort for full source code package and updates. +Source code: https://github.com/rudecs/terraform-provider-decort + +Please see README.md to learn where to place source code so that it +builds seamlessly. + +Documentation: https://github.com/rudecs/terraform-provider-decort/wiki */ -package decort +package account import ( "encoding/json" "net/url" "strconv" + "github.com/rudecs/terraform-provider-decort/internal/controller" log "github.com/sirupsen/logrus" - "github.com/hashicorp/terraform-plugin-sdk/helper/schema" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" ) func utilityAccountReservedUnitsCheckPresence(d *schema.ResourceData, m interface{}) (*ResourceLimits, error) { accountReservedUnits := &ResourceLimits{} - controller := m.(*ControllerCfg) + c := m.(*controller.ControllerCfg) urlValues := &url.Values{} urlValues.Add("accountId", strconv.Itoa(d.Get("account_id").(int))) log.Debugf("utilityAccountReservedUnitsCheckPresence: load units") - accountReservedUnitsRaw, err := controller.decortAPICall("POST", accountGetReservedUnitsAPI, urlValues) + accountReservedUnitsRaw, err := c.DecortAPICall("POST", accountGetReservedUnitsAPI, urlValues) if err != nil { return nil, err } diff --git a/decort/utility_account_rg_list.go b/internal/service/cloudapi/account/utility_account_rg_list.go similarity index 59% rename from decort/utility_account_rg_list.go rename to internal/service/cloudapi/account/utility_account_rg_list.go index 0145b3a..266ba1c 100644 --- a/decort/utility_account_rg_list.go +++ b/internal/service/cloudapi/account/utility_account_rg_list.go @@ -1,6 +1,8 @@ /* Copyright (c) 2019-2022 Digital Energy Cloud Solutions LLC. All Rights Reserved. -Author: Stanislav Solovev, , +Authors: +Petr Krutov, +Stanislav Solovev, Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. @@ -16,33 +18,39 @@ limitations under the License. */ /* -This file is part of Terraform (by Hashicorp) provider for Digital Energy Cloud Orchestration -Technology platfom. +Terraform DECORT provider - manage resources provided by DECORT (Digital Energy Cloud +Orchestration Technology) with Terraform by Hashicorp. -Visit https://github.com/rudecs/terraform-provider-decort for full source code package and updates. +Source code: https://github.com/rudecs/terraform-provider-decort + +Please see README.md to learn where to place source code so that it +builds seamlessly. + +Documentation: https://github.com/rudecs/terraform-provider-decort/wiki */ -package decort +package account import ( "encoding/json" "net/url" "strconv" + "github.com/rudecs/terraform-provider-decort/internal/controller" log "github.com/sirupsen/logrus" - "github.com/hashicorp/terraform-plugin-sdk/helper/schema" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" ) func utilityAccountRGListCheckPresence(d *schema.ResourceData, m interface{}) (AccountRGList, error) { accountRGList := AccountRGList{} - controller := m.(*ControllerCfg) + c := m.(*controller.ControllerCfg) urlValues := &url.Values{} urlValues.Add("accountId", strconv.Itoa(d.Get("account_id").(int))) log.Debugf("utilityAccountRGListCheckPresence: load account list") - accountRGListRaw, err := controller.decortAPICall("POST", accountListRGAPI, urlValues) + accountRGListRaw, err := c.DecortAPICall("POST", accountListRGAPI, urlValues) if err != nil { return nil, err } diff --git a/decort/utility_account_templates_list.go b/internal/service/cloudapi/account/utility_account_templates_list.go similarity index 60% rename from decort/utility_account_templates_list.go rename to internal/service/cloudapi/account/utility_account_templates_list.go index 2dd3a2e..76f9930 100644 --- a/decort/utility_account_templates_list.go +++ b/internal/service/cloudapi/account/utility_account_templates_list.go @@ -1,6 +1,8 @@ /* Copyright (c) 2019-2022 Digital Energy Cloud Solutions LLC. All Rights Reserved. -Author: Stanislav Solovev, , +Authors: +Petr Krutov, +Stanislav Solovev, Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. @@ -16,33 +18,39 @@ limitations under the License. */ /* -This file is part of Terraform (by Hashicorp) provider for Digital Energy Cloud Orchestration -Technology platfom. +Terraform DECORT provider - manage resources provided by DECORT (Digital Energy Cloud +Orchestration Technology) with Terraform by Hashicorp. -Visit https://github.com/rudecs/terraform-provider-decort for full source code package and updates. +Source code: https://github.com/rudecs/terraform-provider-decort + +Please see README.md to learn where to place source code so that it +builds seamlessly. + +Documentation: https://github.com/rudecs/terraform-provider-decort/wiki */ -package decort +package account import ( "encoding/json" "net/url" "strconv" + "github.com/rudecs/terraform-provider-decort/internal/controller" log "github.com/sirupsen/logrus" - "github.com/hashicorp/terraform-plugin-sdk/helper/schema" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" ) func utilityAccountTemplatesListCheckPresence(d *schema.ResourceData, m interface{}) (AccountTemplatesList, error) { accountTemplatesList := AccountTemplatesList{} - controller := m.(*ControllerCfg) + c := m.(*controller.ControllerCfg) urlValues := &url.Values{} urlValues.Add("accountId", strconv.Itoa(d.Get("account_id").(int))) log.Debugf("utilityAccountTemplatesListCheckPresence: load") - accountTemplatesListRaw, err := controller.decortAPICall("POST", accountListTemplatesAPI, urlValues) + accountTemplatesListRaw, err := c.DecortAPICall("POST", accountListTemplatesAPI, urlValues) if err != nil { return nil, err } diff --git a/decort/utility_account_vins_list.go b/internal/service/cloudapi/account/utility_account_vins_list.go similarity index 59% rename from decort/utility_account_vins_list.go rename to internal/service/cloudapi/account/utility_account_vins_list.go index 31291ff..72fc5d6 100644 --- a/decort/utility_account_vins_list.go +++ b/internal/service/cloudapi/account/utility_account_vins_list.go @@ -1,6 +1,8 @@ /* Copyright (c) 2019-2022 Digital Energy Cloud Solutions LLC. All Rights Reserved. -Author: Stanislav Solovev, , +Authors: +Petr Krutov, +Stanislav Solovev, Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. @@ -16,33 +18,39 @@ limitations under the License. */ /* -This file is part of Terraform (by Hashicorp) provider for Digital Energy Cloud Orchestration -Technology platfom. +Terraform DECORT provider - manage resources provided by DECORT (Digital Energy Cloud +Orchestration Technology) with Terraform by Hashicorp. -Visit https://github.com/rudecs/terraform-provider-decort for full source code package and updates. +Source code: https://github.com/rudecs/terraform-provider-decort + +Please see README.md to learn where to place source code so that it +builds seamlessly. + +Documentation: https://github.com/rudecs/terraform-provider-decort/wiki */ -package decort +package account import ( "encoding/json" "net/url" "strconv" + "github.com/rudecs/terraform-provider-decort/internal/controller" log "github.com/sirupsen/logrus" - "github.com/hashicorp/terraform-plugin-sdk/helper/schema" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" ) func utilityAccountVinsListCheckPresence(d *schema.ResourceData, m interface{}) (AccountVinsList, error) { accountVinsList := AccountVinsList{} - controller := m.(*ControllerCfg) + c := m.(*controller.ControllerCfg) urlValues := &url.Values{} urlValues.Add("accountId", strconv.Itoa(d.Get("account_id").(int))) log.Debugf("utilityAccountVinsListCheckPresence: load account list") - accountVinsListRaw, err := controller.decortAPICall("POST", accountListVinsAPI, urlValues) + accountVinsListRaw, err := c.DecortAPICall("POST", accountListVinsAPI, urlValues) if err != nil { return nil, err } diff --git a/internal/service/cloudapi/bservice/api.go b/internal/service/cloudapi/bservice/api.go new file mode 100644 index 0000000..8878915 --- /dev/null +++ b/internal/service/cloudapi/bservice/api.go @@ -0,0 +1,59 @@ +/* +Copyright (c) 2019-2022 Digital Energy Cloud Solutions LLC. All Rights Reserved. +Authors: +Petr Krutov, +Stanislav Solovev, + +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. +*/ + +/* +Terraform DECORT provider - manage resources provided by DECORT (Digital Energy Cloud +Orchestration Technology) with Terraform by Hashicorp. + +Source code: https://github.com/rudecs/terraform-provider-decort + +Please see README.md to learn where to place source code so that it +builds seamlessly. + +Documentation: https://github.com/rudecs/terraform-provider-decort/wiki +*/ + +package bservice + +const bserviceCreateAPI = "/restmachine/cloudapi/bservice/create" +const bserviceDeleteAPI = "/restmachine/cloudapi/bservice/delete" +const bserviceDisableAPI = "/restmachine/cloudapi/bservice/disable" +const bserviceEnableAPI = "/restmachine/cloudapi/bservice/enable" +const bserviceGetAPI = "/restmachine/cloudapi/bservice/get" +const bserviceGroupAddAPI = "/restmachine/cloudapi/bservice/groupAdd" +const bserviceGroupComputeRemoveAPI = "/restmachine/cloudapi/bservice/groupComputeRemove" +const bserviceGroupGetAPI = "/restmachine/cloudapi/bservice/groupGet" +const bserviceGroupParentAddAPI = "/restmachine/cloudapi/bservice/groupParentAdd" +const bserviceGroupParentRemoveAPI = "/restmachine/cloudapi/bservice/groupParentRemove" +const bserviceGroupRemoveAPI = "/restmachine/cloudapi/bservice/groupRemove" +const bserviceGroupResizeAPI = "/restmachine/cloudapi/bservice/groupResize" +const bserviceGroupStartAPI = "/restmachine/cloudapi/bservice/groupStart" +const bserviceGroupStopAPI = "/restmachine/cloudapi/bservice/groupStop" +const bserviceGroupUpdateAPI = "/restmachine/cloudapi/bservice/groupUpdate" +const bserviceGroupUpdateExtnetAPI = "/restmachine/cloudapi/bservice/groupUpdateExtnet" +const bserviceGroupUpdateVinsAPI = "/restmachine/cloudapi/bservice/groupUpdateVins" +const bserviceListAPI = "/restmachine/cloudapi/bservice/list" +const bserviceListDeletedAPI = "/restmachine/cloudapi/bservice/listDeleted" +const bserviceRestoreAPI = "/restmachine/cloudapi/bservice/restore" +const bserviceSnapshotCreateAPI = "/restmachine/cloudapi/bservice/snapshotCreate" +const bserviceSnapshotDeleteAPI = "/restmachine/cloudapi/bservice/snapshotDelete" +const bserviceSnapshotListAPI = "/restmachine/cloudapi/bservice/snapshotList" +const bserviceSnapshotRollbackAPI = "/restmachine/cloudapi/bservice/snapshotRollback" +const bserviceStartAPI = "/restmachine/cloudapi/bservice/start" +const bserviceStopAPI = "/restmachine/cloudapi/bservice/stop" diff --git a/decort/data_source_bservice.go b/internal/service/cloudapi/bservice/data_source_bservice.go similarity index 82% rename from decort/data_source_bservice.go rename to internal/service/cloudapi/bservice/data_source_bservice.go index a013981..ef1fc17 100644 --- a/decort/data_source_bservice.go +++ b/internal/service/cloudapi/bservice/data_source_bservice.go @@ -1,6 +1,8 @@ /* Copyright (c) 2019-2022 Digital Energy Cloud Solutions LLC. All Rights Reserved. -Author: Stanislav Solovev, +Authors: +Petr Krutov, +Stanislav Solovev, Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. @@ -16,23 +18,32 @@ limitations under the License. */ /* -This file is part of Terraform (by Hashicorp) provider for Digital Energy Cloud Orchestration -Technology platfom. +Terraform DECORT provider - manage resources provided by DECORT (Digital Energy Cloud +Orchestration Technology) with Terraform by Hashicorp. -Visit https://github.com/rudecs/terraform-provider-decort for full source code package and updates. +Source code: https://github.com/rudecs/terraform-provider-decort + +Please see README.md to learn where to place source code so that it +builds seamlessly. + +Documentation: https://github.com/rudecs/terraform-provider-decort/wiki */ -package decort +package bservice import ( + "context" + "github.com/google/uuid" - "github.com/hashicorp/terraform-plugin-sdk/helper/schema" + "github.com/hashicorp/terraform-plugin-sdk/v2/diag" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" + "github.com/rudecs/terraform-provider-decort/internal/constants" ) -func dataSourceBasicServiceRead(d *schema.ResourceData, m interface{}) error { +func dataSourceBasicServiceRead(ctx context.Context, d *schema.ResourceData, m interface{}) diag.Diagnostics { bs, err := utilityBasicServiceCheckPresence(d, m) if err != nil { - return err + return diag.FromErr(err) } id := uuid.New() @@ -277,15 +288,15 @@ func dataSourceBasicServiceSchemaMake() map[string]*schema.Schema { return res } -func dataSourceBasicService() *schema.Resource { +func DataSourceBasicService() *schema.Resource { return &schema.Resource{ SchemaVersion: 1, - Read: dataSourceBasicServiceRead, + ReadContext: dataSourceBasicServiceRead, Timeouts: &schema.ResourceTimeout{ - Read: &Timeout30s, - Default: &Timeout60s, + Read: &constants.Timeout30s, + Default: &constants.Timeout60s, }, Schema: dataSourceBasicServiceSchemaMake(), diff --git a/internal/service/cloudapi/bservice/data_source_bservice_deleted_list.go b/internal/service/cloudapi/bservice/data_source_bservice_deleted_list.go new file mode 100644 index 0000000..4341c43 --- /dev/null +++ b/internal/service/cloudapi/bservice/data_source_bservice_deleted_list.go @@ -0,0 +1,69 @@ +/* +Copyright (c) 2019-2022 Digital Energy Cloud Solutions LLC. All Rights Reserved. +Authors: +Petr Krutov, +Stanislav Solovev, + +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. +*/ + +/* +Terraform DECORT provider - manage resources provided by DECORT (Digital Energy Cloud +Orchestration Technology) with Terraform by Hashicorp. + +Source code: https://github.com/rudecs/terraform-provider-decort + +Please see README.md to learn where to place source code so that it +builds seamlessly. + +Documentation: https://github.com/rudecs/terraform-provider-decort/wiki +*/ + +package bservice + +import ( + "context" + + "github.com/google/uuid" + "github.com/hashicorp/terraform-plugin-sdk/v2/diag" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" + "github.com/rudecs/terraform-provider-decort/internal/constants" +) + +func dataSourceBasicServiceDeletedListRead(ctx context.Context, d *schema.ResourceData, m interface{}) diag.Diagnostics { + basicServiceDeletedList, err := utilityBasicServiceDeletedListCheckPresence(d, m) + if err != nil { + return diag.FromErr(err) + } + + id := uuid.New() + d.SetId(id.String()) + d.Set("items", flattenBasicServiceList(basicServiceDeletedList)) + + return nil +} + +func DataSourceBasicServiceDeletedList() *schema.Resource { + return &schema.Resource{ + SchemaVersion: 1, + + ReadContext: dataSourceBasicServiceDeletedListRead, + + Timeouts: &schema.ResourceTimeout{ + Read: &constants.Timeout30s, + Default: &constants.Timeout60s, + }, + + Schema: dataSourceBasicServiceListSchemaMake(), + } +} diff --git a/decort/data_source_bservice_group.go b/internal/service/cloudapi/bservice/data_source_bservice_group.go similarity index 81% rename from decort/data_source_bservice_group.go rename to internal/service/cloudapi/bservice/data_source_bservice_group.go index b8c3d92..f333d1c 100644 --- a/decort/data_source_bservice_group.go +++ b/internal/service/cloudapi/bservice/data_source_bservice_group.go @@ -1,6 +1,8 @@ /* Copyright (c) 2019-2022 Digital Energy Cloud Solutions LLC. All Rights Reserved. -Author: Stanislav Solovev, +Authors: +Petr Krutov, +Stanislav Solovev, Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. @@ -16,23 +18,32 @@ limitations under the License. */ /* -This file is part of Terraform (by Hashicorp) provider for Digital Energy Cloud Orchestration -Technology platfom. +Terraform DECORT provider - manage resources provided by DECORT (Digital Energy Cloud +Orchestration Technology) with Terraform by Hashicorp. -Visit https://github.com/rudecs/terraform-provider-decort for full source code package and updates. +Source code: https://github.com/rudecs/terraform-provider-decort + +Please see README.md to learn where to place source code so that it +builds seamlessly. + +Documentation: https://github.com/rudecs/terraform-provider-decort/wiki */ -package decort +package bservice import ( + "context" + "github.com/google/uuid" - "github.com/hashicorp/terraform-plugin-sdk/helper/schema" + "github.com/hashicorp/terraform-plugin-sdk/v2/diag" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" + "github.com/rudecs/terraform-provider-decort/internal/constants" ) -func dataSourceBasicServiceGroupRead(d *schema.ResourceData, m interface{}) error { +func dataSourceBasicServiceGroupRead(ctx context.Context, d *schema.ResourceData, m interface{}) diag.Diagnostics { bsg, err := utilityBasicServiceGroupCheckPresence(d, m) if err != nil { - return err + return diag.FromErr(err) } id := uuid.New() @@ -275,15 +286,15 @@ func dataSourceBasicServiceGroupSchemaMake() map[string]*schema.Schema { return res } -func dataSourceBasicServiceGroup() *schema.Resource { +func DataSourceBasicServiceGroup() *schema.Resource { return &schema.Resource{ SchemaVersion: 1, - Read: dataSourceBasicServiceGroupRead, + ReadContext: dataSourceBasicServiceGroupRead, Timeouts: &schema.ResourceTimeout{ - Read: &Timeout30s, - Default: &Timeout60s, + Read: &constants.Timeout30s, + Default: &constants.Timeout60s, }, Schema: dataSourceBasicServiceGroupSchemaMake(), diff --git a/decort/data_source_bservice_list.go b/internal/service/cloudapi/bservice/data_source_bservice_list.go similarity index 79% rename from decort/data_source_bservice_list.go rename to internal/service/cloudapi/bservice/data_source_bservice_list.go index 21ead41..d3b2e43 100644 --- a/decort/data_source_bservice_list.go +++ b/internal/service/cloudapi/bservice/data_source_bservice_list.go @@ -1,6 +1,8 @@ /* Copyright (c) 2019-2022 Digital Energy Cloud Solutions LLC. All Rights Reserved. -Author: Stanislav Solovev, +Authors: +Petr Krutov, +Stanislav Solovev, Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. @@ -16,17 +18,26 @@ limitations under the License. */ /* -This file is part of Terraform (by Hashicorp) provider for Digital Energy Cloud Orchestration -Technology platfom. +Terraform DECORT provider - manage resources provided by DECORT (Digital Energy Cloud +Orchestration Technology) with Terraform by Hashicorp. -Visit https://github.com/rudecs/terraform-provider-decort for full source code package and updates. +Source code: https://github.com/rudecs/terraform-provider-decort + +Please see README.md to learn where to place source code so that it +builds seamlessly. + +Documentation: https://github.com/rudecs/terraform-provider-decort/wiki */ -package decort +package bservice import ( + "context" + "github.com/google/uuid" - "github.com/hashicorp/terraform-plugin-sdk/helper/schema" + "github.com/hashicorp/terraform-plugin-sdk/v2/diag" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" + "github.com/rudecs/terraform-provider-decort/internal/constants" ) func flattenBasicServiceList(bsl BasicServiceList) []map[string]interface{} { @@ -61,10 +72,10 @@ func flattenBasicServiceList(bsl BasicServiceList) []map[string]interface{} { return res } -func dataSourceBasicServiceListRead(d *schema.ResourceData, m interface{}) error { +func dataSourceBasicServiceListRead(ctx context.Context, d *schema.ResourceData, m interface{}) diag.Diagnostics { basicServiceList, err := utilityBasicServiceListCheckPresence(d, m) if err != nil { - return err + return diag.FromErr(err) } id := uuid.New() @@ -199,15 +210,15 @@ func dataSourceBasicServiceListSchemaMake() map[string]*schema.Schema { return res } -func dataSourceBasicServiceList() *schema.Resource { +func DataSourceBasicServiceList() *schema.Resource { return &schema.Resource{ SchemaVersion: 1, - Read: dataSourceBasicServiceListRead, + ReadContext: dataSourceBasicServiceListRead, Timeouts: &schema.ResourceTimeout{ - Read: &Timeout30s, - Default: &Timeout60s, + Read: &constants.Timeout30s, + Default: &constants.Timeout60s, }, Schema: dataSourceBasicServiceListSchemaMake(), diff --git a/decort/data_source_bservice_snapshot_list.go b/internal/service/cloudapi/bservice/data_source_bservice_snapshot_list.go similarity index 61% rename from decort/data_source_bservice_snapshot_list.go rename to internal/service/cloudapi/bservice/data_source_bservice_snapshot_list.go index 306ce99..93fe820 100644 --- a/decort/data_source_bservice_snapshot_list.go +++ b/internal/service/cloudapi/bservice/data_source_bservice_snapshot_list.go @@ -1,6 +1,8 @@ /* Copyright (c) 2019-2022 Digital Energy Cloud Solutions LLC. All Rights Reserved. -Author: Stanislav Solovev, +Authors: +Petr Krutov, +Stanislav Solovev, Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. @@ -16,23 +18,32 @@ limitations under the License. */ /* -This file is part of Terraform (by Hashicorp) provider for Digital Energy Cloud Orchestration -Technology platfom. +Terraform DECORT provider - manage resources provided by DECORT (Digital Energy Cloud +Orchestration Technology) with Terraform by Hashicorp. -Visit https://github.com/rudecs/terraform-provider-decort for full source code package and updates. +Source code: https://github.com/rudecs/terraform-provider-decort + +Please see README.md to learn where to place source code so that it +builds seamlessly. + +Documentation: https://github.com/rudecs/terraform-provider-decort/wiki */ -package decort +package bservice import ( + "context" + "github.com/google/uuid" - "github.com/hashicorp/terraform-plugin-sdk/helper/schema" + "github.com/hashicorp/terraform-plugin-sdk/v2/diag" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" + "github.com/rudecs/terraform-provider-decort/internal/constants" ) -func dataSourceBasicServiceSnapshotListRead(d *schema.ResourceData, m interface{}) error { +func dataSourceBasicServiceSnapshotListRead(ctx context.Context, d *schema.ResourceData, m interface{}) diag.Diagnostics { basicServiceSnapshotList, err := utilityBasicServiceSnapshotListCheckPresence(d, m) if err != nil { - return err + return diag.FromErr(err) } id := uuid.New() @@ -77,15 +88,15 @@ func dataSourceBasicServiceSnapshotListSchemaMake() map[string]*schema.Schema { return res } -func dataSourceBasicServiceSnapshotList() *schema.Resource { +func DataSourceBasicServiceSnapshotList() *schema.Resource { return &schema.Resource{ SchemaVersion: 1, - Read: dataSourceBasicServiceSnapshotListRead, + ReadContext: dataSourceBasicServiceSnapshotListRead, Timeouts: &schema.ResourceTimeout{ - Read: &Timeout30s, - Default: &Timeout60s, + Read: &constants.Timeout30s, + Default: &constants.Timeout60s, }, Schema: dataSourceBasicServiceSnapshotListSchemaMake(), diff --git a/internal/service/cloudapi/bservice/models.go b/internal/service/cloudapi/bservice/models.go new file mode 100644 index 0000000..75c5bbf --- /dev/null +++ b/internal/service/cloudapi/bservice/models.go @@ -0,0 +1,144 @@ +/* +Copyright (c) 2019-2022 Digital Energy Cloud Solutions LLC. All Rights Reserved. +Authors: +Petr Krutov, +Stanislav Solovev, + +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. +*/ + +/* +Terraform DECORT provider - manage resources provided by DECORT (Digital Energy Cloud +Orchestration Technology) with Terraform by Hashicorp. + +Source code: https://github.com/rudecs/terraform-provider-decort + +Please see README.md to learn where to place source code so that it +builds seamlessly. + +Documentation: https://github.com/rudecs/terraform-provider-decort/wiki +*/ + +package bservice + +///Structs + +type BasicServiceCompute struct { + CompGroupId int `json:"compgroupId"` + CompGroupName string `json:"compgroupName"` + CompGroupRole string `json:"compgroupRole"` + ID int `json:"id"` + Name string `json:"name"` +} + +type BasicServiceComputes []BasicServiceCompute + +type BasicServiceSnapshot struct { + GUID string `json:"guid"` + Label string `json:"label"` + Timestamp int `json:"timestamp"` + Valid bool `json:"valid"` +} + +type BasicServiceSnapshots []BasicServiceSnapshot + +type BasicService struct { + AccountId int `json:"accountId"` + AccountName string `json:"accountName"` + BaseDomain string `json:"baseDomain"` + + CreatedBy string `json:"createdBy"` + CreatedTime int `json:"createdTime"` + DeletedBy string `json:"deletedBy"` + DeletedTime int `json:"deletedTime"` + GID int `json:"gid"` + Groups []int `json:"groups"` + GUID int `json:"guid"` + ID int `json:"id"` + Name string `json:"name"` + ParentSrvId int `json:"parentSrvId"` + ParentSrvType string `json:"parentSrvType"` + RGID int `json:"rgId"` + RGName string `json:"rgName"` + SSHUser string `json:"sshUser"` + Status string `json:"status"` + TechStatus string `json:"techStatus"` + UpdatedBy string `json:"updatedBy"` + UpdatedTime int `json:"updatedTime"` + UserManaged bool `json:"userManaged"` +} + +type BasicServiceList []BasicService + +type BasicServiceExtend struct { + BasicService + Computes BasicServiceComputes `json:"computes"` + CPUTotal int `json:"cpuTotal"` + DiskTotal int `json:"diskTotal"` + GroupsName []string `json:"groupsName"` + Milestones int `json:"milestones"` + RamTotal int `json:"ramTotal"` + Snapshots BasicServiceSnapshots `json:"snapshots"` + SSHKey string `json:"sshKey"` +} + +type BasicServiceGroupOSUser struct { + Login string `json:"login"` + Password string `json:"password"` +} + +type BasicServiceGroupOSUsers []BasicServiceGroupOSUser + +type BasicServicceGroupCompute struct { + ID int `json:"id"` + IPAdresses []string `json:"ipAddresses"` + Name string `json:"name"` + OSUsers BasicServiceGroupOSUsers `json:"osUsers"` +} + +type BasicServiceGroupComputes []BasicServicceGroupCompute + +type BasicServiceGroup struct { + AccountId int `json:"accountId"` + AccountName string `json:"accountName"` + Computes BasicServiceGroupComputes `json:"computes"` + Consistency bool `json:"consistency"` + CPU int `json:"cpu"` + CreatedBy string `json:"createdBy"` + CreatedTime int `json:"createdTime"` + DeletedBy string `json:"deletedBy"` + DeletedTime int `json:"deletedTime"` + Disk int `json:"disk"` + Driver string `json:"driver"` + Extnets []int `json:"extnets"` + GID int `json:"gid"` + GUID int `json:"guid"` + ID int `json:"id"` + ImageId int `json:"imageId"` + Milestones int `json:"milestones"` + Name string `json:"name"` + Parents []int `json:"parents"` + RAM int `json:"ram"` + RGID int `json:"rgId"` + RGName string `json:"rgName"` + Role string `json:"role"` + SepId int `json:"sepId"` + SeqNo int `json:"seqNo"` + ServiceId int `json:"serviceId"` + Status string `json:"status"` + TechStatus string `json:"techStatus"` + TimeoutStart int `json:"timeoutStart"` + UpdatedBy string `json:"updatedBy"` + UpdatedTime int `json:"updatedTime"` + Vinses []int `json:"vinses"` +} diff --git a/decort/resource_bservice.go b/internal/service/cloudapi/bservice/resource_bservice.go similarity index 77% rename from decort/resource_bservice.go rename to internal/service/cloudapi/bservice/resource_bservice.go index 9f0df09..7456728 100644 --- a/decort/resource_bservice.go +++ b/internal/service/cloudapi/bservice/resource_bservice.go @@ -1,6 +1,8 @@ /* Copyright (c) 2019-2022 Digital Energy Cloud Solutions LLC. All Rights Reserved. -Author: Stanislav Solovev, +Authors: +Petr Krutov, +Stanislav Solovev, Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. @@ -16,46 +18,54 @@ limitations under the License. */ /* -This file is part of Terraform (by Hashicorp) provider for Digital Energy Cloud Orchestration -Technology platfom. +Terraform DECORT provider - manage resources provided by DECORT (Digital Energy Cloud +Orchestration Technology) with Terraform by Hashicorp. -Visit https://github.com/rudecs/terraform-provider-decort for full source code package and updates. +Source code: https://github.com/rudecs/terraform-provider-decort + +Please see README.md to learn where to place source code so that it +builds seamlessly. + +Documentation: https://github.com/rudecs/terraform-provider-decort/wiki */ -package decort +package bservice import ( - "errors" + "context" "net/url" "strconv" "github.com/google/uuid" - "github.com/hashicorp/terraform-plugin-sdk/helper/schema" + "github.com/hashicorp/terraform-plugin-sdk/v2/diag" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" + "github.com/rudecs/terraform-provider-decort/internal/constants" + "github.com/rudecs/terraform-provider-decort/internal/controller" log "github.com/sirupsen/logrus" ) -func resourceBasicServiceCreate(d *schema.ResourceData, m interface{}) error { +func resourceBasicServiceCreate(ctx context.Context, d *schema.ResourceData, m interface{}) diag.Diagnostics { log.Debugf("resourceBasicServiceCreate") if serviceId, ok := d.GetOk("service_id"); ok { if exists, err := resourceBasicServiceExists(d, m); exists { if err != nil { - return err + return diag.FromErr(err) } id := uuid.New() d.SetId(strconv.Itoa(serviceId.(int))) d.Set("service_id", strconv.Itoa(serviceId.(int))) - err = resourceBasicServiceRead(d, m) - if err != nil { - return err + diagnostics := resourceBasicServiceRead(ctx, d, m) + if diagnostics != nil { + return diagnostics } d.SetId(id.String()) return nil } - return errors.New("provided service id does not exist") + return diag.Errorf("provided service id does not exist") } - controller := m.(*ControllerCfg) + c := m.(*controller.ControllerCfg) urlValues := &url.Values{} urlValues.Add("name", d.Get("service_name").(string)) @@ -68,18 +78,18 @@ func resourceBasicServiceCreate(d *schema.ResourceData, m interface{}) error { urlValues.Add("sshUser", sshUser.(string)) } - serviceId, err := controller.decortAPICall("POST", bserviceCreateAPI, urlValues) + serviceId, err := c.DecortAPICall("POST", bserviceCreateAPI, urlValues) if err != nil { - return err + return diag.FromErr(err) } id := uuid.New() d.SetId(serviceId) d.Set("service_id", serviceId) - err = resourceBasicServiceRead(d, m) - if err != nil { - return err + diagnostics := resourceBasicServiceRead(ctx, d, m) + if diagnostics != nil { + return diagnostics } d.SetId(id.String()) @@ -87,13 +97,13 @@ func resourceBasicServiceCreate(d *schema.ResourceData, m interface{}) error { return nil } -func resourceBasicServiceRead(d *schema.ResourceData, m interface{}) error { +func resourceBasicServiceRead(ctx context.Context, d *schema.ResourceData, m interface{}) diag.Diagnostics { log.Debugf("resourceBasicServiceRead") bs, err := utilityBasicServiceCheckPresence(d, m) if bs == nil { d.SetId("") - return err + return diag.FromErr(err) } d.Set("account_id", bs.AccountId) @@ -130,25 +140,25 @@ func resourceBasicServiceRead(d *schema.ResourceData, m interface{}) error { return nil } -func resourceBasicServiceDelete(d *schema.ResourceData, m interface{}) error { +func resourceBasicServiceDelete(ctx context.Context, d *schema.ResourceData, m interface{}) diag.Diagnostics { log.Debugf("resourceBasicServiceDelete") bs, err := utilityBasicServiceCheckPresence(d, m) if bs == nil { if err != nil { - return err + return diag.FromErr(err) } return nil } - controller := m.(*ControllerCfg) + c := m.(*controller.ControllerCfg) urlValues := &url.Values{} urlValues.Add("serviceId", strconv.Itoa(d.Get("service_id").(int))) urlValues.Add("permanently", strconv.FormatBool(d.Get("permanently").(bool))) - _, err = controller.decortAPICall("POST", bserviceDeleteAPI, urlValues) + _, err = c.DecortAPICall("POST", bserviceDeleteAPI, urlValues) if err != nil { - return err + return diag.FromErr(err) } d.SetId("") @@ -169,9 +179,9 @@ func resourceBasicServiceExists(d *schema.ResourceData, m interface{}) (bool, er return true, nil } -func resourceBasicServiceEdit(d *schema.ResourceData, m interface{}) error { +func resourceBasicServiceEdit(ctx context.Context, d *schema.ResourceData, m interface{}) diag.Diagnostics { log.Debugf("resourceBasicServiceEdit") - c := m.(*ControllerCfg) + c := m.(*controller.ControllerCfg) urlValues := &url.Values{} if d.HasChange("enable") { @@ -182,9 +192,9 @@ func resourceBasicServiceEdit(d *schema.ResourceData, m interface{}) error { } urlValues.Add("serviceId", strconv.Itoa(d.Get("service_id").(int))) - _, err := c.decortAPICall("POST", api, urlValues) + _, err := c.DecortAPICall("POST", api, urlValues) if err != nil { - return err + return diag.FromErr(err) } urlValues = &url.Values{} @@ -194,9 +204,9 @@ func resourceBasicServiceEdit(d *schema.ResourceData, m interface{}) error { restore := d.Get("restore").(bool) if restore { urlValues.Add("serviceId", strconv.Itoa(d.Get("service_id").(int))) - _, err := c.decortAPICall("POST", bserviceRestoreAPI, urlValues) + _, err := c.DecortAPICall("POST", bserviceRestoreAPI, urlValues) if err != nil { - return err + return diag.FromErr(err) } urlValues = &url.Values{} @@ -211,9 +221,9 @@ func resourceBasicServiceEdit(d *schema.ResourceData, m interface{}) error { } urlValues.Add("serviceId", strconv.Itoa(d.Get("service_id").(int))) - _, err := c.decortAPICall("POST", api, urlValues) + _, err := c.DecortAPICall("POST", api, urlValues) if err != nil { - return err + return diag.FromErr(err) } urlValues = &url.Values{} @@ -247,9 +257,9 @@ func resourceBasicServiceEdit(d *schema.ResourceData, m interface{}) error { snapshotConv := snapshot.(map[string]interface{}) urlValues.Add("serviceId", strconv.Itoa(d.Get("service_id").(int))) urlValues.Add("label", snapshotConv["label"].(string)) - _, err := c.decortAPICall("POST", bserviceSnapshotDeleteAPI, urlValues) + _, err := c.DecortAPICall("POST", bserviceSnapshotDeleteAPI, urlValues) if err != nil { - return err + return diag.FromErr(err) } urlValues = &url.Values{} @@ -261,9 +271,9 @@ func resourceBasicServiceEdit(d *schema.ResourceData, m interface{}) error { snapshotConv := snapshot.(map[string]interface{}) urlValues.Add("serviceId", strconv.Itoa(d.Get("service_id").(int))) urlValues.Add("label", snapshotConv["label"].(string)) - _, err := c.decortAPICall("POST", bserviceSnapshotCreateAPI, urlValues) + _, err := c.DecortAPICall("POST", bserviceSnapshotCreateAPI, urlValues) if err != nil { - return err + return diag.FromErr(err) } urlValues = &url.Values{} @@ -275,9 +285,9 @@ func resourceBasicServiceEdit(d *schema.ResourceData, m interface{}) error { snapshotConv := snapshot.(map[string]interface{}) urlValues.Add("serviceId", strconv.Itoa(d.Get("service_id").(int))) urlValues.Add("label", snapshotConv["label"].(string)) - _, err := c.decortAPICall("POST", bserviceSnapshotRollbackAPI, urlValues) + _, err := c.DecortAPICall("POST", bserviceSnapshotRollbackAPI, urlValues) if err != nil { - return err + return diag.FromErr(err) } urlValues = &url.Values{} @@ -527,26 +537,26 @@ func resourceBasicServiceSchemaMake() map[string]*schema.Schema { } } -func resourceBasicService() *schema.Resource { +func ResourceBasicService() *schema.Resource { return &schema.Resource{ SchemaVersion: 1, - Create: resourceBasicServiceCreate, - Read: resourceBasicServiceRead, - Update: resourceBasicServiceEdit, - Delete: resourceBasicServiceDelete, - Exists: resourceBasicServiceExists, + CreateContext: resourceBasicServiceCreate, + ReadContext: resourceBasicServiceRead, + UpdateContext: resourceBasicServiceEdit, + DeleteContext: resourceBasicServiceDelete, + Exists: resourceBasicServiceExists, Importer: &schema.ResourceImporter{ State: schema.ImportStatePassthrough, }, Timeouts: &schema.ResourceTimeout{ - Create: &Timeout60s, - Read: &Timeout30s, - Update: &Timeout60s, - Delete: &Timeout60s, - Default: &Timeout60s, + Create: &constants.Timeout60s, + Read: &constants.Timeout30s, + Update: &constants.Timeout60s, + Delete: &constants.Timeout60s, + Default: &constants.Timeout60s, }, Schema: resourceBasicServiceSchemaMake(), diff --git a/decort/resource_bservice_group.go b/internal/service/cloudapi/bservice/resource_bservice_group.go similarity index 78% rename from decort/resource_bservice_group.go rename to internal/service/cloudapi/bservice/resource_bservice_group.go index 6bbff5a..aa2d5a3 100644 --- a/decort/resource_bservice_group.go +++ b/internal/service/cloudapi/bservice/resource_bservice_group.go @@ -1,6 +1,8 @@ /* Copyright (c) 2019-2022 Digital Energy Cloud Solutions LLC. All Rights Reserved. -Author: Stanislav Solovev, +Authors: +Petr Krutov, +Stanislav Solovev, Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. @@ -16,50 +18,58 @@ limitations under the License. */ /* -This file is part of Terraform (by Hashicorp) provider for Digital Energy Cloud Orchestration -Technology platfom. +Terraform DECORT provider - manage resources provided by DECORT (Digital Energy Cloud +Orchestration Technology) with Terraform by Hashicorp. -Visit https://github.com/rudecs/terraform-provider-decort for full source code package and updates. +Source code: https://github.com/rudecs/terraform-provider-decort + +Please see README.md to learn where to place source code so that it +builds seamlessly. + +Documentation: https://github.com/rudecs/terraform-provider-decort/wiki */ -package decort +package bservice import ( - "errors" + "context" "net/url" "strconv" "strings" "github.com/google/uuid" - "github.com/hashicorp/terraform-plugin-sdk/helper/schema" - "github.com/hashicorp/terraform-plugin-sdk/helper/validation" + "github.com/hashicorp/terraform-plugin-sdk/v2/diag" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/validation" + "github.com/rudecs/terraform-provider-decort/internal/constants" + "github.com/rudecs/terraform-provider-decort/internal/controller" log "github.com/sirupsen/logrus" ) -func resourceBasicServiceGroupCreate(d *schema.ResourceData, m interface{}) error { +func resourceBasicServiceGroupCreate(ctx context.Context, d *schema.ResourceData, m interface{}) diag.Diagnostics { log.Debugf("resourceBasicServiceGroupCreate") if compgroupId, ok := d.GetOk("compgroup_id"); ok { if _, ok := d.GetOk("service_id"); ok { if exists, err := resourceBasicServiceGroupExists(d, m); exists { if err != nil { - return err + return diag.FromErr(err) } id := uuid.New() d.SetId(strconv.Itoa(compgroupId.(int))) d.Set("compgroup_id", strconv.Itoa(compgroupId.(int))) - err = resourceBasicServiceGroupRead(d, m) - if err != nil { - return err + diagnostics := resourceBasicServiceGroupRead(ctx, d, m) + if diagnostics != nil { + return diagnostics } d.SetId(id.String()) return nil } - return errors.New("provided compgroup id does not exist") + return diag.Errorf("provided compgroup id does not exist") } } - controller := m.(*ControllerCfg) + c := m.(*controller.ControllerCfg) urlValues := &url.Values{} urlValues.Add("serviceId", strconv.Itoa(d.Get("service_id").(int))) @@ -109,18 +119,18 @@ func resourceBasicServiceGroupCreate(d *schema.ResourceData, m interface{}) erro urlValues.Add("extnets", temp) } - compgroupId, err := controller.decortAPICall("POST", bserviceGroupAddAPI, urlValues) + compgroupId, err := c.DecortAPICall("POST", bserviceGroupAddAPI, urlValues) if err != nil { - return err + return diag.FromErr(err) } id := uuid.New() d.SetId(compgroupId) d.Set("compgroup_id", compgroupId) - err = resourceBasicServiceGroupRead(d, m) - if err != nil { - return err + diagnostics := resourceBasicServiceGroupRead(ctx, d, m) + if diagnostics != nil { + return diagnostics } d.SetId(id.String()) @@ -128,13 +138,13 @@ func resourceBasicServiceGroupCreate(d *schema.ResourceData, m interface{}) erro return nil } -func resourceBasicServiceGroupRead(d *schema.ResourceData, m interface{}) error { +func resourceBasicServiceGroupRead(ctx context.Context, d *schema.ResourceData, m interface{}) diag.Diagnostics { log.Debugf("resourceBasicServiceGroupRead") bsg, err := utilityBasicServiceGroupCheckPresence(d, m) if bsg == nil { d.SetId("") - return err + return diag.FromErr(err) } d.Set("account_id", bsg.AccountId) @@ -172,25 +182,25 @@ func resourceBasicServiceGroupRead(d *schema.ResourceData, m interface{}) error return nil } -func resourceBasicServiceGroupDelete(d *schema.ResourceData, m interface{}) error { +func resourceBasicServiceGroupDelete(ctx context.Context, d *schema.ResourceData, m interface{}) diag.Diagnostics { log.Debugf("resourceBasicServiceGroupDelete") bsg, err := utilityBasicServiceGroupCheckPresence(d, m) if bsg == nil { if err != nil { - return err + return diag.FromErr(err) } return nil } - controller := m.(*ControllerCfg) + c := m.(*controller.ControllerCfg) urlValues := &url.Values{} urlValues.Add("serviceId", strconv.Itoa(d.Get("service_id").(int))) urlValues.Add("compgroupId", strconv.Itoa(d.Get("compgroup_id").(int))) - _, err = controller.decortAPICall("POST", bserviceGroupRemoveAPI, urlValues) + _, err = c.DecortAPICall("POST", bserviceGroupRemoveAPI, urlValues) if err != nil { - return err + return diag.FromErr(err) } d.SetId("") @@ -211,9 +221,9 @@ func resourceBasicServiceGroupExists(d *schema.ResourceData, m interface{}) (boo return true, nil } -func resourceBasicServiceGroupEdit(d *schema.ResourceData, m interface{}) error { +func resourceBasicServiceGroupEdit(ctx context.Context, d *schema.ResourceData, m interface{}) diag.Diagnostics { log.Debugf("resourceBasicServiceGroupEdit") - c := m.(*ControllerCfg) + c := m.(*controller.ControllerCfg) urlValues := &url.Values{} @@ -222,9 +232,9 @@ func resourceBasicServiceGroupEdit(d *schema.ResourceData, m interface{}) error urlValues.Add("compgroupId", strconv.Itoa(d.Get("compgroup_id").(int))) urlValues.Add("count", strconv.Itoa(d.Get("comp_count").(int))) urlValues.Add("mode", strings.ToUpper(d.Get("mode").(string))) - _, err := c.decortAPICall("POST", bserviceGroupResizeAPI, urlValues) + _, err := c.DecortAPICall("POST", bserviceGroupResizeAPI, urlValues) if err != nil { - return err + return diag.FromErr(err) } urlValues = &url.Values{} @@ -241,9 +251,9 @@ func resourceBasicServiceGroupEdit(d *schema.ResourceData, m interface{}) error urlValues.Add("serviceId", strconv.Itoa(d.Get("service_id").(int))) urlValues.Add("compgroupId", strconv.Itoa(d.Get("compgroup_id").(int))) - _, err := c.decortAPICall("POST", api, urlValues) + _, err := c.DecortAPICall("POST", api, urlValues) if err != nil { - return err + return diag.FromErr(err) } urlValues = &url.Values{} @@ -260,9 +270,9 @@ func resourceBasicServiceGroupEdit(d *schema.ResourceData, m interface{}) error urlValues.Add("serviceId", strconv.Itoa(d.Get("service_id").(int))) urlValues.Add("compgroupId", strconv.Itoa(d.Get("compgroup_id").(int))) - _, err := c.decortAPICall("POST", bserviceGroupUpdateAPI, urlValues) + _, err := c.DecortAPICall("POST", bserviceGroupUpdateAPI, urlValues) if err != nil { - return err + return diag.FromErr(err) } urlValues = &url.Values{} @@ -286,9 +296,9 @@ func resourceBasicServiceGroupEdit(d *schema.ResourceData, m interface{}) error urlValues.Add("serviceId", strconv.Itoa(d.Get("service_id").(int))) urlValues.Add("compgroupId", strconv.Itoa(d.Get("compgroup_id").(int))) urlValues.Add("extnets", temp) - _, err := c.decortAPICall("POST", bserviceGroupUpdateExtnetAPI, urlValues) + _, err := c.DecortAPICall("POST", bserviceGroupUpdateExtnetAPI, urlValues) if err != nil { - return err + return diag.FromErr(err) } urlValues = &url.Values{} @@ -312,9 +322,9 @@ func resourceBasicServiceGroupEdit(d *schema.ResourceData, m interface{}) error urlValues.Add("serviceId", strconv.Itoa(d.Get("service_id").(int))) urlValues.Add("compgroupId", strconv.Itoa(d.Get("compgroup_id").(int))) urlValues.Add("vinses", temp) - _, err := c.decortAPICall("POST", bserviceGroupUpdateVinsAPI, urlValues) + _, err := c.DecortAPICall("POST", bserviceGroupUpdateVinsAPI, urlValues) if err != nil { - return err + return diag.FromErr(err) } urlValues = &url.Values{} @@ -346,9 +356,9 @@ func resourceBasicServiceGroupEdit(d *schema.ResourceData, m interface{}) error urlValues.Add("compgroupId", strconv.Itoa(d.Get("compgroup_id").(int))) urlValues.Add("parentId", strconv.Itoa(parentConv)) - _, err := c.decortAPICall("POST", bserviceGroupParentRemoveAPI, urlValues) + _, err := c.DecortAPICall("POST", bserviceGroupParentRemoveAPI, urlValues) if err != nil { - return err + return diag.FromErr(err) } urlValues = &url.Values{} @@ -361,9 +371,9 @@ func resourceBasicServiceGroupEdit(d *schema.ResourceData, m interface{}) error urlValues.Add("serviceId", strconv.Itoa(d.Get("service_id").(int))) urlValues.Add("compgroupId", strconv.Itoa(d.Get("compgroup_id").(int))) urlValues.Add("parentId", strconv.Itoa(parentConv)) - _, err := c.decortAPICall("POST", bserviceGroupParentAddAPI, urlValues) + _, err := c.DecortAPICall("POST", bserviceGroupParentAddAPI, urlValues) if err != nil { - return err + return diag.FromErr(err) } urlValues = &url.Values{} @@ -379,9 +389,9 @@ func resourceBasicServiceGroupEdit(d *schema.ResourceData, m interface{}) error urlValues.Add("compgroupId", strconv.Itoa(d.Get("compgroup_id").(int))) urlValues.Add("computeId", strconv.Itoa(rc.(int))) - _, err := c.decortAPICall("POST", bserviceGroupComputeRemoveAPI, urlValues) + _, err := c.DecortAPICall("POST", bserviceGroupComputeRemoveAPI, urlValues) if err != nil { - return err + return diag.FromErr(err) } urlValues = &url.Values{} @@ -634,26 +644,26 @@ func resourceBasicServiceGroupSchemaMake() map[string]*schema.Schema { } } -func resourceBasicServiceGroup() *schema.Resource { +func ResourceBasicServiceGroup() *schema.Resource { return &schema.Resource{ SchemaVersion: 1, - Create: resourceBasicServiceGroupCreate, - Read: resourceBasicServiceGroupRead, - Update: resourceBasicServiceGroupEdit, - Delete: resourceBasicServiceGroupDelete, - Exists: resourceBasicServiceGroupExists, + CreateContext: resourceBasicServiceGroupCreate, + ReadContext: resourceBasicServiceGroupRead, + UpdateContext: resourceBasicServiceGroupEdit, + DeleteContext: resourceBasicServiceGroupDelete, + Exists: resourceBasicServiceGroupExists, Importer: &schema.ResourceImporter{ State: schema.ImportStatePassthrough, }, Timeouts: &schema.ResourceTimeout{ - Create: &Timeout60s, - Read: &Timeout30s, - Update: &Timeout60s, - Delete: &Timeout60s, - Default: &Timeout60s, + Create: &constants.Timeout60s, + Read: &constants.Timeout30s, + Update: &constants.Timeout60s, + Delete: &constants.Timeout60s, + Default: &constants.Timeout60s, }, Schema: resourceBasicServiceGroupSchemaMake(), diff --git a/decort/utility_bservicce_deleted_list.go b/internal/service/cloudapi/bservice/utility_bservicce_deleted_list.go similarity index 65% rename from decort/utility_bservicce_deleted_list.go rename to internal/service/cloudapi/bservice/utility_bservicce_deleted_list.go index d52ebee..29d1b7f 100644 --- a/decort/utility_bservicce_deleted_list.go +++ b/internal/service/cloudapi/bservice/utility_bservicce_deleted_list.go @@ -1,6 +1,8 @@ /* Copyright (c) 2019-2022 Digital Energy Cloud Solutions LLC. All Rights Reserved. -Author: Stanislav Solovev, , +Authors: +Petr Krutov, +Stanislav Solovev, Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. @@ -16,27 +18,33 @@ limitations under the License. */ /* -This file is part of Terraform (by Hashicorp) provider for Digital Energy Cloud Orchestration -Technology platfom. +Terraform DECORT provider - manage resources provided by DECORT (Digital Energy Cloud +Orchestration Technology) with Terraform by Hashicorp. -Visit https://github.com/rudecs/terraform-provider-decort for full source code package and updates. +Source code: https://github.com/rudecs/terraform-provider-decort + +Please see README.md to learn where to place source code so that it +builds seamlessly. + +Documentation: https://github.com/rudecs/terraform-provider-decort/wiki */ -package decort +package bservice import ( "encoding/json" "net/url" "strconv" + "github.com/rudecs/terraform-provider-decort/internal/controller" log "github.com/sirupsen/logrus" - "github.com/hashicorp/terraform-plugin-sdk/helper/schema" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" ) func utilityBasicServiceDeletedListCheckPresence(d *schema.ResourceData, m interface{}) (BasicServiceList, error) { basicServiceDeletedList := BasicServiceList{} - controller := m.(*ControllerCfg) + c := m.(*controller.ControllerCfg) urlValues := &url.Values{} if accountId, ok := d.GetOk("account_id"); ok { @@ -53,7 +61,7 @@ func utilityBasicServiceDeletedListCheckPresence(d *schema.ResourceData, m inter } log.Debugf("utilityBasicServiceDeletedListCheckPresence") - basicServiceDeletedListRaw, err := controller.decortAPICall("POST", bserviceListDeletedAPI, urlValues) + basicServiceDeletedListRaw, err := c.DecortAPICall("POST", bserviceListDeletedAPI, urlValues) if err != nil { return nil, err } diff --git a/decort/utility_bservice.go b/internal/service/cloudapi/bservice/utility_bservice.go similarity index 61% rename from decort/utility_bservice.go rename to internal/service/cloudapi/bservice/utility_bservice.go index 65c41d8..57ff329 100644 --- a/decort/utility_bservice.go +++ b/internal/service/cloudapi/bservice/utility_bservice.go @@ -1,6 +1,8 @@ /* Copyright (c) 2019-2022 Digital Energy Cloud Solutions LLC. All Rights Reserved. -Author: Stanislav Solovev, , +Authors: +Petr Krutov, +Stanislav Solovev, Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. @@ -16,27 +18,33 @@ limitations under the License. */ /* -This file is part of Terraform (by Hashicorp) provider for Digital Energy Cloud Orchestration -Technology platfom. +Terraform DECORT provider - manage resources provided by DECORT (Digital Energy Cloud +Orchestration Technology) with Terraform by Hashicorp. -Visit https://github.com/rudecs/terraform-provider-decort for full source code package and updates. +Source code: https://github.com/rudecs/terraform-provider-decort + +Please see README.md to learn where to place source code so that it +builds seamlessly. + +Documentation: https://github.com/rudecs/terraform-provider-decort/wiki */ -package decort +package bservice import ( "encoding/json" "net/url" "strconv" + "github.com/rudecs/terraform-provider-decort/internal/controller" log "github.com/sirupsen/logrus" - "github.com/hashicorp/terraform-plugin-sdk/helper/schema" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" ) func utilityBasicServiceCheckPresence(d *schema.ResourceData, m interface{}) (*BasicServiceExtend, error) { bservice := &BasicServiceExtend{} - controller := m.(*ControllerCfg) + c := m.(*controller.ControllerCfg) urlValues := &url.Values{} if (strconv.Itoa(d.Get("service_id").(int))) != "0" { @@ -46,7 +54,7 @@ func utilityBasicServiceCheckPresence(d *schema.ResourceData, m interface{}) (*B } log.Debugf("utilityBasicServiceCheckPresence") - bserviceRaw, err := controller.decortAPICall("POST", bserviceGetAPI, urlValues) + bserviceRaw, err := c.DecortAPICall("POST", bserviceGetAPI, urlValues) if err != nil { return nil, err } diff --git a/decort/utility_bservice_group.go b/internal/service/cloudapi/bservice/utility_bservice_group.go similarity index 62% rename from decort/utility_bservice_group.go rename to internal/service/cloudapi/bservice/utility_bservice_group.go index 6f75dc0..b91d2a7 100644 --- a/decort/utility_bservice_group.go +++ b/internal/service/cloudapi/bservice/utility_bservice_group.go @@ -1,6 +1,8 @@ /* Copyright (c) 2019-2022 Digital Energy Cloud Solutions LLC. All Rights Reserved. -Author: Stanislav Solovev, , +Authors: +Petr Krutov, +Stanislav Solovev, Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. @@ -16,27 +18,33 @@ limitations under the License. */ /* -This file is part of Terraform (by Hashicorp) provider for Digital Energy Cloud Orchestration -Technology platfom. +Terraform DECORT provider - manage resources provided by DECORT (Digital Energy Cloud +Orchestration Technology) with Terraform by Hashicorp. -Visit https://github.com/rudecs/terraform-provider-decort for full source code package and updates. +Source code: https://github.com/rudecs/terraform-provider-decort + +Please see README.md to learn where to place source code so that it +builds seamlessly. + +Documentation: https://github.com/rudecs/terraform-provider-decort/wiki */ -package decort +package bservice import ( "encoding/json" "net/url" "strconv" + "github.com/rudecs/terraform-provider-decort/internal/controller" log "github.com/sirupsen/logrus" - "github.com/hashicorp/terraform-plugin-sdk/helper/schema" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" ) func utilityBasicServiceGroupCheckPresence(d *schema.ResourceData, m interface{}) (*BasicServiceGroup, error) { bserviceGroup := &BasicServiceGroup{} - controller := m.(*ControllerCfg) + c := m.(*controller.ControllerCfg) urlValues := &url.Values{} urlValues.Add("serviceId", strconv.Itoa(d.Get("service_id").(int))) @@ -47,7 +55,7 @@ func utilityBasicServiceGroupCheckPresence(d *schema.ResourceData, m interface{} } log.Debugf("utilityBasicServiceGroupCheckPresence") - bserviceGroupRaw, err := controller.decortAPICall("POST", bserviceGroupGetAPI, urlValues) + bserviceGroupRaw, err := c.DecortAPICall("POST", bserviceGroupGetAPI, urlValues) if err != nil { return nil, err } diff --git a/decort/utility_bservice_list.go b/internal/service/cloudapi/bservice/utility_bservice_list.go similarity index 64% rename from decort/utility_bservice_list.go rename to internal/service/cloudapi/bservice/utility_bservice_list.go index efbe623..73ec82d 100644 --- a/decort/utility_bservice_list.go +++ b/internal/service/cloudapi/bservice/utility_bservice_list.go @@ -1,6 +1,8 @@ /* Copyright (c) 2019-2022 Digital Energy Cloud Solutions LLC. All Rights Reserved. -Author: Stanislav Solovev, , +Authors: +Petr Krutov, +Stanislav Solovev, Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. @@ -16,27 +18,33 @@ limitations under the License. */ /* -This file is part of Terraform (by Hashicorp) provider for Digital Energy Cloud Orchestration -Technology platfom. +Terraform DECORT provider - manage resources provided by DECORT (Digital Energy Cloud +Orchestration Technology) with Terraform by Hashicorp. -Visit https://github.com/rudecs/terraform-provider-decort for full source code package and updates. +Source code: https://github.com/rudecs/terraform-provider-decort + +Please see README.md to learn where to place source code so that it +builds seamlessly. + +Documentation: https://github.com/rudecs/terraform-provider-decort/wiki */ -package decort +package bservice import ( "encoding/json" "net/url" "strconv" + "github.com/rudecs/terraform-provider-decort/internal/controller" log "github.com/sirupsen/logrus" - "github.com/hashicorp/terraform-plugin-sdk/helper/schema" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" ) func utilityBasicServiceListCheckPresence(d *schema.ResourceData, m interface{}) (BasicServiceList, error) { basicServiceList := BasicServiceList{} - controller := m.(*ControllerCfg) + c := m.(*controller.ControllerCfg) urlValues := &url.Values{} if accountId, ok := d.GetOk("account_id"); ok { @@ -53,7 +61,7 @@ func utilityBasicServiceListCheckPresence(d *schema.ResourceData, m interface{}) } log.Debugf("utilityBasicServiceListCheckPresence") - basicServiceListRaw, err := controller.decortAPICall("POST", bserviceListAPI, urlValues) + basicServiceListRaw, err := c.DecortAPICall("POST", bserviceListAPI, urlValues) if err != nil { return nil, err } diff --git a/decort/utility_bservice_snapshot_list.go b/internal/service/cloudapi/bservice/utility_bservice_snapshot_list.go similarity index 61% rename from decort/utility_bservice_snapshot_list.go rename to internal/service/cloudapi/bservice/utility_bservice_snapshot_list.go index 1f310f3..3bacdbe 100644 --- a/decort/utility_bservice_snapshot_list.go +++ b/internal/service/cloudapi/bservice/utility_bservice_snapshot_list.go @@ -1,6 +1,8 @@ /* Copyright (c) 2019-2022 Digital Energy Cloud Solutions LLC. All Rights Reserved. -Author: Stanislav Solovev, , +Authors: +Petr Krutov, +Stanislav Solovev, Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. @@ -16,27 +18,33 @@ limitations under the License. */ /* -This file is part of Terraform (by Hashicorp) provider for Digital Energy Cloud Orchestration -Technology platfom. +Terraform DECORT provider - manage resources provided by DECORT (Digital Energy Cloud +Orchestration Technology) with Terraform by Hashicorp. -Visit https://github.com/rudecs/terraform-provider-decort for full source code package and updates. +Source code: https://github.com/rudecs/terraform-provider-decort + +Please see README.md to learn where to place source code so that it +builds seamlessly. + +Documentation: https://github.com/rudecs/terraform-provider-decort/wiki */ -package decort +package bservice import ( "encoding/json" "net/url" "strconv" + "github.com/rudecs/terraform-provider-decort/internal/controller" log "github.com/sirupsen/logrus" - "github.com/hashicorp/terraform-plugin-sdk/helper/schema" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" ) func utilityBasicServiceSnapshotListCheckPresence(d *schema.ResourceData, m interface{}) (BasicServiceSnapshots, error) { basicServiceSnapshotList := BasicServiceSnapshots{} - controller := m.(*ControllerCfg) + c := m.(*controller.ControllerCfg) urlValues := &url.Values{} if serviceId, ok := d.GetOk("service_id"); ok { @@ -44,7 +52,7 @@ func utilityBasicServiceSnapshotListCheckPresence(d *schema.ResourceData, m inte } log.Debugf("utilityBasicServiceSnapshotListCheckPresence") - basicServiceSnapshotListRaw, err := controller.decortAPICall("POST", bserviceSnapshotListAPI, urlValues) + basicServiceSnapshotListRaw, err := c.DecortAPICall("POST", bserviceSnapshotListAPI, urlValues) if err != nil { return nil, err } diff --git a/internal/service/cloudapi/disks/api.go b/internal/service/cloudapi/disks/api.go new file mode 100644 index 0000000..678cd69 --- /dev/null +++ b/internal/service/cloudapi/disks/api.go @@ -0,0 +1,39 @@ +/* +Copyright (c) 2019-2022 Digital Energy Cloud Solutions LLC. All Rights Reserved. +Authors: +Petr Krutov, +Stanislav Solovev, + +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. +*/ + +/* +Terraform DECORT provider - manage resources provided by DECORT (Digital Energy Cloud +Orchestration Technology) with Terraform by Hashicorp. + +Source code: https://github.com/rudecs/terraform-provider-decort + +Please see README.md to learn where to place source code so that it +builds seamlessly. + +Documentation: https://github.com/rudecs/terraform-provider-decort/wiki +*/ + +package disks + +const DisksCreateAPI = "/restmachine/cloudapi/disks/create" +const DisksGetAPI = "/restmachine/cloudapi/disks/get" // Returns single DiskRecord on success +const DisksListAPI = "/restmachine/cloudapi/disks/list" // Returns list of DiskRecord on success +const DisksResizeAPI = "/restmachine/cloudapi/disks/resize2" +const DisksRenameAPI = "/restmachine/cloudapi/disks/rename" +const DisksDeleteAPI = "/restmachine/cloudapi/disks/delete" diff --git a/decort/data_source_disk.go b/internal/service/cloudapi/disks/data_source_disk.go similarity index 69% rename from decort/data_source_disk.go rename to internal/service/cloudapi/disks/data_source_disk.go index 8236f4a..acaeb0a 100644 --- a/decort/data_source_disk.go +++ b/internal/service/cloudapi/disks/data_source_disk.go @@ -1,6 +1,8 @@ /* -Copyright (c) 2019-2021 Digital Energy Cloud Solutions LLC. All Rights Reserved. -Author: Sergey Shubin, , +Copyright (c) 2019-2022 Digital Energy Cloud Solutions LLC. All Rights Reserved. +Authors: +Petr Krutov, +Stanislav Solovev, Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. @@ -16,23 +18,31 @@ limitations under the License. */ /* -This file is part of Terraform (by Hashicorp) provider for Digital Energy Cloud Orchestration -Technology platfom. +Terraform DECORT provider - manage resources provided by DECORT (Digital Energy Cloud +Orchestration Technology) with Terraform by Hashicorp. -Visit https://github.com/rudecs/terraform-provider-decort for full source code package and updates. +Source code: https://github.com/rudecs/terraform-provider-decort + +Please see README.md to learn where to place source code so that it +builds seamlessly. + +Documentation: https://github.com/rudecs/terraform-provider-decort/wiki */ -package decort +package disks import ( + "context" "encoding/json" "fmt" + // "net/url" + "github.com/rudecs/terraform-provider-decort/internal/constants" log "github.com/sirupsen/logrus" - "github.com/hashicorp/terraform-plugin-sdk/helper/schema" - // "github.com/hashicorp/terraform-plugin-sdk/helper/validation" + "github.com/hashicorp/terraform-plugin-sdk/v2/diag" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" ) func flattenDisk(d *schema.ResourceData, disk_facts string) error { @@ -44,7 +54,7 @@ func flattenDisk(d *schema.ResourceData, disk_facts string) error { log.Debugf("flattenDisk: ready to unmarshal string %s", disk_facts) model := DiskRecord{} - + err := json.Unmarshal([]byte(disk_facts), &model) if err != nil { return err @@ -71,16 +81,16 @@ func flattenDisk(d *schema.ResourceData, disk_facts string) error { return nil } -func dataSourceDiskRead(d *schema.ResourceData, m interface{}) error { +func dataSourceDiskRead(ctx context.Context, d *schema.ResourceData, m interface{}) diag.Diagnostics { disk_facts, err := utilityDiskCheckPresence(d, m) if disk_facts == "" { // if empty string is returned from utilityDiskCheckPresence then there is no // such Disk and err tells so - just return it to the calling party d.SetId("") // ensure ID is empty - return err + return diag.FromErr(err) } - return flattenDisk(d, disk_facts) + return diag.FromErr(flattenDisk(d, disk_facts)) } func dataSourceDiskSchemaMake() map[string]*schema.Schema { @@ -103,7 +113,7 @@ func dataSourceDiskSchemaMake() map[string]*schema.Schema { Description: "ID of the account this disk belongs to. If disk ID is specified, then account ID is ignored.", }, - // The rest of the data source Disk schema are all computed + // The rest of the data source Disk schema are all computed "sep_id": { Type: schema.TypeInt, Computed: true, @@ -153,47 +163,47 @@ func dataSourceDiskSchemaMake() map[string]*schema.Schema { }, /* - "snapshots": { - Type: schema.TypeList, - Computed: true, - Elem: &schema.Resource { - Schema: snapshotSubresourceSchemaMake(), + "snapshots": { + Type: schema.TypeList, + Computed: true, + Elem: &schema.Resource { + Schema: snapshotSubresourceSchemaMake(), + }, + Description: "List of user-created snapshots for this disk." }, - Description: "List of user-created snapshots for this disk." - }, - "status": { - Type: schema.TypeString, - Computed: true, - Description: "Current model status of this disk.", - }, + "status": { + Type: schema.TypeString, + Computed: true, + Description: "Current model status of this disk.", + }, - "tech_status": { - Type: schema.TypeString, - Computed: true, - Description: "Current technical status of this disk.", - }, + "tech_status": { + Type: schema.TypeString, + Computed: true, + Description: "Current technical status of this disk.", + }, - "compute_id": { - Type: schema.TypeInt, - Computed: true, - Description: "ID of the compute instance where this disk is attached to, or 0 for unattached disk.", - }, + "compute_id": { + Type: schema.TypeInt, + Computed: true, + Description: "ID of the compute instance where this disk is attached to, or 0 for unattached disk.", + }, */ } return rets } -func dataSourceDisk() *schema.Resource { +func DataSourceDisk() *schema.Resource { return &schema.Resource{ SchemaVersion: 1, - Read: dataSourceDiskRead, + ReadContext: dataSourceDiskRead, Timeouts: &schema.ResourceTimeout{ - Read: &Timeout30s, - Default: &Timeout60s, + Read: &constants.Timeout30s, + Default: &constants.Timeout60s, }, Schema: dataSourceDiskSchemaMake(), diff --git a/decort/data_source_disk_list.go b/internal/service/cloudapi/disks/data_source_disk_list.go similarity index 86% rename from decort/data_source_disk_list.go rename to internal/service/cloudapi/disks/data_source_disk_list.go index fa118aa..86914ef 100644 --- a/decort/data_source_disk_list.go +++ b/internal/service/cloudapi/disks/data_source_disk_list.go @@ -1,6 +1,8 @@ /* -Copyright (c) 2019-2021 Digital Energy Cloud Solutions LLC. All Rights Reserved. -Author: Sergey Shubin, , +Copyright (c) 2019-2022 Digital Energy Cloud Solutions LLC. All Rights Reserved. +Authors: +Petr Krutov, +Stanislav Solovev, Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. @@ -16,19 +18,27 @@ limitations under the License. */ /* -This file is part of Terraform (by Hashicorp) provider for Digital Energy Cloud Orchestration -Technology platfom. +Terraform DECORT provider - manage resources provided by DECORT (Digital Energy Cloud +Orchestration Technology) with Terraform by Hashicorp. -Visit https://github.com/rudecs/terraform-provider-decort for full source code package and updates. +Source code: https://github.com/rudecs/terraform-provider-decort + +Please see README.md to learn where to place source code so that it +builds seamlessly. + +Documentation: https://github.com/rudecs/terraform-provider-decort/wiki */ -package decort +package disks import ( + "context" "encoding/json" "github.com/google/uuid" - "github.com/hashicorp/terraform-plugin-sdk/helper/schema" + "github.com/hashicorp/terraform-plugin-sdk/v2/diag" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" + "github.com/rudecs/terraform-provider-decort/internal/constants" ) func flattenDiskList(dl DisksListResp) []map[string]interface{} { @@ -109,10 +119,10 @@ func flattendDiskSnapshotList(sl SnapshotRecordList) []interface{} { } -func dataSourceDiskListRead(d *schema.ResourceData, m interface{}) error { +func dataSourceDiskListRead(ctx context.Context, d *schema.ResourceData, m interface{}) diag.Diagnostics { diskList, err := utilityDiskListCheckPresence(d, m) if err != nil { - return err + return diag.FromErr(err) } id := uuid.New() @@ -375,15 +385,15 @@ func dataSourceDiskListSchemaMake() map[string]*schema.Schema { return res } -func dataSourceDiskList() *schema.Resource { +func DataSourceDiskList() *schema.Resource { return &schema.Resource{ SchemaVersion: 1, - Read: dataSourceDiskListRead, + ReadContext: dataSourceDiskListRead, Timeouts: &schema.ResourceTimeout{ - Read: &Timeout30s, - Default: &Timeout60s, + Read: &constants.Timeout30s, + Default: &constants.Timeout60s, }, Schema: dataSourceDiskListSchemaMake(), diff --git a/internal/service/cloudapi/disks/models.go b/internal/service/cloudapi/disks/models.go new file mode 100644 index 0000000..8b997ea --- /dev/null +++ b/internal/service/cloudapi/disks/models.go @@ -0,0 +1,95 @@ +/* +Copyright (c) 2019-2022 Digital Energy Cloud Solutions LLC. All Rights Reserved. +Authors: +Petr Krutov, +Stanislav Solovev, + +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. +*/ + +/* +Terraform DECORT provider - manage resources provided by DECORT (Digital Energy Cloud +Orchestration Technology) with Terraform by Hashicorp. + +Source code: https://github.com/rudecs/terraform-provider-decort + +Please see README.md to learn where to place source code so that it +builds seamlessly. + +Documentation: https://github.com/rudecs/terraform-provider-decort/wiki +*/ + +package disks + +type DiskRecord struct { + Acl map[string]interface{} `json:"acl"` + AccountID int `json:"accountId"` + AccountName string `json:"accountName"` + BootPartition int `json:"bootPartition"` + CreatedTime uint64 `json:"creationTime"` + ComputeID int `json:"computeId"` + ComputeName string `json:"computeName"` + DeletedTime uint64 `json:"deletionTime"` + DeviceName string `json:"devicename"` + Desc string `json:"desc"` + DestructionTime uint64 `json:"destructionTime"` + DiskPath string `json:"diskPath"` + GridID int `json:"gid"` + GUID int `json:"guid"` + ID uint `json:"id"` + ImageID int `json:"imageId"` + Images []int `json:"images"` + IOTune map[string]interface{} `json:"iotune"` + IQN string `json:"iqn"` + Login string `json:"login"` + Name string `json:"name"` + MachineId int `json:"machineId"` + MachineName string `json:"machineName"` + Milestones uint64 `json:"milestones"` + Order int `json:"order"` + Params string `json:"params"` + Passwd string `json:"passwd"` + ParentId int `json:"parentId"` + PciSlot int `json:"pciSlot"` + Pool string `json:"pool"` + PurgeTime uint64 `json:"purgeTime"` + PurgeAttempts uint64 `json:"purgeAttempts"` + RealityDeviceNumber int `json:"realityDeviceNumber"` + ReferenceId string `json:"referenceId"` + ResID string `json:"resId"` + ResName string `json:"resName"` + Role string `json:"role"` + SepType string `json:"sepType"` + SepID int `json:"sepId"` // NOTE: absent from compute/get output + SizeMax int `json:"sizeMax"` + SizeUsed int `json:"sizeUsed"` // sum over all snapshots of this disk to report total consumed space + Snapshots []SnapshotRecord `json:"snapshots"` + Status string `json:"status"` + TechStatus string `json:"techStatus"` + Type string `json:"type"` + UpdateBy uint64 `json:"updateBy"` + VMID int `json:"vmid"` +} + +type SnapshotRecord struct { + Guid string `json:"guid"` + Label string `json:"label"` + ResId string `json:"resId"` + SnapSetGuid string `json:"snapSetGuid"` + SnapSetTime uint64 `json:"snapSetTime"` + TimeStamp uint64 `json:"timestamp"` +} + +type SnapshotRecordList []SnapshotRecord + +type DisksListResp []DiskRecord diff --git a/decort/resource_disk.go b/internal/service/cloudapi/disks/resource_disk.go similarity index 76% rename from decort/resource_disk.go rename to internal/service/cloudapi/disks/resource_disk.go index efee695..b29f199 100644 --- a/decort/resource_disk.go +++ b/internal/service/cloudapi/disks/resource_disk.go @@ -1,6 +1,8 @@ /* -Copyright (c) 2019-2021 Digital Energy Cloud Solutions LLC. All Rights Reserved. -Author: Sergey Shubin, , +Copyright (c) 2019-2022 Digital Energy Cloud Solutions LLC. All Rights Reserved. +Authors: +Petr Krutov, +Stanislav Solovev, Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. @@ -16,34 +18,44 @@ limitations under the License. */ /* -This file is part of Terraform (by Hashicorp) provider for Digital Energy Cloud Orchestration -Technology platfom. +Terraform DECORT provider - manage resources provided by DECORT (Digital Energy Cloud +Orchestration Technology) with Terraform by Hashicorp. -Visit https://github.com/rudecs/terraform-provider-decort for full source code package and updates. +Source code: https://github.com/rudecs/terraform-provider-decort + +Please see README.md to learn where to place source code so that it +builds seamlessly. + +Documentation: https://github.com/rudecs/terraform-provider-decort/wiki */ -package decort +package disks import ( // "encoding/json" + "context" "fmt" "net/url" "strconv" + "github.com/rudecs/terraform-provider-decort/internal/constants" + "github.com/rudecs/terraform-provider-decort/internal/controller" + "github.com/rudecs/terraform-provider-decort/internal/location" log "github.com/sirupsen/logrus" - "github.com/hashicorp/terraform-plugin-sdk/helper/schema" - "github.com/hashicorp/terraform-plugin-sdk/helper/validation" + "github.com/hashicorp/terraform-plugin-sdk/v2/diag" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/validation" ) -func resourceDiskCreate(d *schema.ResourceData, m interface{}) error { +func resourceDiskCreate(ctx context.Context, d *schema.ResourceData, m interface{}) diag.Diagnostics { log.Debugf("resourceDiskCreate: called for Disk name %q, Account ID %d", d.Get("name").(string), d.Get("account_id").(int)) - controller := m.(*ControllerCfg) + c := m.(*controller.ControllerCfg) urlValues := &url.Values{} // accountId, gid, name, description, size, type, sep_id, pool urlValues.Add("accountId", fmt.Sprintf("%d", d.Get("account_id").(int))) - urlValues.Add("gid", fmt.Sprintf("%d", DefaultGridID)) // we use default Grid ID, which was obtained along with DECORT Controller init + urlValues.Add("gid", fmt.Sprintf("%d", location.DefaultGridID)) // we use default Grid ID, which was obtained along with DECORT Controller init urlValues.Add("name", d.Get("name").(string)) urlValues.Add("size", fmt.Sprintf("%d", d.Get("size").(int))) urlValues.Add("type", "D") // NOTE: only disks of Data type are managed via plugin @@ -61,9 +73,9 @@ func resourceDiskCreate(d *schema.ResourceData, m interface{}) error { urlValues.Add("description", argVal.(string)) } - apiResp, err := controller.decortAPICall("POST", DisksCreateAPI, urlValues) + apiResp, err := c.DecortAPICall("POST", DisksCreateAPI, urlValues) if err != nil { - return err + return diag.FromErr(err) } d.SetId(apiResp) // update ID of the resource to tell Terraform that the disk resource exists @@ -75,22 +87,22 @@ func resourceDiskCreate(d *schema.ResourceData, m interface{}) error { // between Disk resource and Disk data source schemas // Disk resource read function will also update resource ID on success, so that Terraform // will know the resource exists (however, we already did it a few lines before) - return dataSourceDiskRead(d, m) + return dataSourceDiskRead(ctx, d, m) } -func resourceDiskRead(d *schema.ResourceData, m interface{}) error { +func resourceDiskRead(ctx context.Context, d *schema.ResourceData, m interface{}) diag.Diagnostics { diskFacts, err := utilityDiskCheckPresence(d, m) if diskFacts == "" { // if empty string is returned from utilityDiskCheckPresence then there is no // such Disk and err tells so - just return it to the calling party d.SetId("") // ensure ID is empty - return err + return diag.FromErr(err) } - return flattenDisk(d, diskFacts) + return diag.FromErr(flattenDisk(d, diskFacts)) } -func resourceDiskUpdate(d *schema.ResourceData, m interface{}) error { +func resourceDiskUpdate(ctx context.Context, d *schema.ResourceData, m interface{}) diag.Diagnostics { // Update will only change the following attributes of the disk: // - Size; to keep data safe, shrinking disk is not allowed. // - Name @@ -100,9 +112,7 @@ func resourceDiskUpdate(d *schema.ResourceData, m interface{}) error { log.Debugf("resourceDiskUpdate: called for Disk ID / name %s / %s, Account ID %d", d.Id(), d.Get("name").(string), d.Get("account_id").(int)) - d.Partial(true) - - controller := m.(*ControllerCfg) + c := m.(*controller.ControllerCfg) oldSize, newSize := d.GetChange("size") if oldSize.(int) < newSize.(int) { @@ -111,13 +121,13 @@ func resourceDiskUpdate(d *schema.ResourceData, m interface{}) error { sizeParams := &url.Values{} sizeParams.Add("diskId", d.Id()) sizeParams.Add("size", fmt.Sprintf("%d", newSize.(int))) - _, err := controller.decortAPICall("POST", DisksResizeAPI, sizeParams) + _, err := c.DecortAPICall("POST", DisksResizeAPI, sizeParams) if err != nil { - return err + return diag.FromErr(err) } - d.SetPartial("size") + d.Set("size", newSize) } else if oldSize.(int) > newSize.(int) { - return fmt.Errorf("resourceDiskUpdate: Disk ID %s - reducing disk size is not allowed", d.Id()) + return diag.FromErr(fmt.Errorf("resourceDiskUpdate: Disk ID %s - reducing disk size is not allowed", d.Id())) } oldName, newName := d.GetChange("name") @@ -127,11 +137,10 @@ func resourceDiskUpdate(d *schema.ResourceData, m interface{}) error { renameParams := &url.Values{} renameParams.Add("diskId", d.Id()) renameParams.Add("name", newName.(string)) - _, err := controller.decortAPICall("POST", DisksRenameAPI, renameParams) + _, err := c.DecortAPICall("POST", DisksRenameAPI, renameParams) if err != nil { - return err + return diag.FromErr(err) } - d.SetPartial("name") } /* @@ -143,14 +152,12 @@ func resourceDiskUpdate(d *schema.ResourceData, m interface{}) error { } */ - d.Partial(false) - // we may reuse dataSourceDiskRead here as we maintain similarity // between Compute resource and Compute data source schemas - return dataSourceDiskRead(d, m) + return dataSourceDiskRead(ctx, d, m) } -func resourceDiskDelete(d *schema.ResourceData, m interface{}) error { +func resourceDiskDelete(ctx context.Context, d *schema.ResourceData, m interface{}) diag.Diagnostics { // NOTE: this function tries to detach and destroy target Disk "permanently", so // there is no way to restore it. // If, however, the disk is attached to a compute, the method will @@ -161,7 +168,7 @@ func resourceDiskDelete(d *schema.ResourceData, m interface{}) error { diskFacts, err := utilityDiskCheckPresence(d, m) if diskFacts == "" { if err != nil { - return err + return diag.FromErr(err) } // the specified Disk does not exist - in this case according to Terraform best practice // we exit from Destroy method without error @@ -179,10 +186,10 @@ func resourceDiskDelete(d *schema.ResourceData, m interface{}) error { params.Add("detach", "0") params.Add("permanently", "1") - controller := m.(*ControllerCfg) - _, err = controller.decortAPICall("POST", DisksDeleteAPI, params) + c := m.(*controller.ControllerCfg) + _, err = c.DecortAPICall("POST", DisksDeleteAPI, params) if err != nil { - return err + return diag.FromErr(err) } return nil @@ -305,26 +312,26 @@ func resourceDiskSchemaMake() map[string]*schema.Schema { return rets } -func resourceDisk() *schema.Resource { +func ResourceDisk() *schema.Resource { return &schema.Resource{ SchemaVersion: 1, - Create: resourceDiskCreate, - Read: resourceDiskRead, - Update: resourceDiskUpdate, - Delete: resourceDiskDelete, - Exists: resourceDiskExists, + CreateContext: resourceDiskCreate, + ReadContext: resourceDiskRead, + UpdateContext: resourceDiskUpdate, + DeleteContext: resourceDiskDelete, + Exists: resourceDiskExists, Importer: &schema.ResourceImporter{ State: schema.ImportStatePassthrough, }, Timeouts: &schema.ResourceTimeout{ - Create: &Timeout180s, - Read: &Timeout30s, - Update: &Timeout180s, - Delete: &Timeout60s, - Default: &Timeout60s, + Create: &constants.Timeout180s, + Read: &constants.Timeout30s, + Update: &constants.Timeout180s, + Delete: &constants.Timeout60s, + Default: &constants.Timeout60s, }, Schema: resourceDiskSchemaMake(), diff --git a/decort/utility_disk.go b/internal/service/cloudapi/disks/utility_disk.go similarity index 82% rename from decort/utility_disk.go rename to internal/service/cloudapi/disks/utility_disk.go index c9a8605..a76edf0 100644 --- a/decort/utility_disk.go +++ b/internal/service/cloudapi/disks/utility_disk.go @@ -1,6 +1,8 @@ /* -Copyright (c) 2019-2021 Digital Energy Cloud Solutions LLC. All Rights Reserved. -Author: Sergey Shubin, , +Copyright (c) 2019-2022 Digital Energy Cloud Solutions LLC. All Rights Reserved. +Authors: +Petr Krutov, +Stanislav Solovev, Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. @@ -16,13 +18,18 @@ limitations under the License. */ /* -This file is part of Terraform (by Hashicorp) provider for Digital Energy Cloud Orchestration -Technology platfom. +Terraform DECORT provider - manage resources provided by DECORT (Digital Energy Cloud +Orchestration Technology) with Terraform by Hashicorp. -Visit https://github.com/rudecs/terraform-provider-decort for full source code package and updates. +Source code: https://github.com/rudecs/terraform-provider-decort + +Please see README.md to learn where to place source code so that it +builds seamlessly. + +Documentation: https://github.com/rudecs/terraform-provider-decort/wiki */ -package decort +package disks import ( "encoding/json" @@ -30,9 +37,10 @@ import ( "net/url" "strconv" + "github.com/rudecs/terraform-provider-decort/internal/controller" log "github.com/sirupsen/logrus" - "github.com/hashicorp/terraform-plugin-sdk/helper/schema" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" ) func utilityDiskCheckPresence(d *schema.ResourceData, m interface{}) (string, error) { @@ -52,7 +60,7 @@ func utilityDiskCheckPresence(d *schema.ResourceData, m interface{}) (string, er // method for resource's Exists method. // - controller := m.(*ControllerCfg) + c := m.(*controller.ControllerCfg) urlValues := &url.Values{} // make it possible to use "read" & "check presence" functions with disk ID set so @@ -73,7 +81,7 @@ func utilityDiskCheckPresence(d *schema.ResourceData, m interface{}) (string, er // disk ID is specified, try to get disk instance straight by this ID log.Debugf("utilityDiskCheckPresence: locating disk by its ID %d", theId) urlValues.Add("diskId", fmt.Sprintf("%d", theId)) - diskFacts, err := controller.decortAPICall("POST", DisksGetAPI, urlValues) + diskFacts, err := c.DecortAPICall("POST", DisksGetAPI, urlValues) if err != nil { return "", err } @@ -92,7 +100,7 @@ func utilityDiskCheckPresence(d *schema.ResourceData, m interface{}) (string, er // obtain Account ID by account name - it should not be zero on success urlValues.Add("accountId", fmt.Sprintf("%d", d.Get("account_id").(int))) - diskFacts, err := controller.decortAPICall("POST", DisksListAPI, urlValues) + diskFacts, err := c.DecortAPICall("POST", DisksListAPI, urlValues) if err != nil { return "", err } diff --git a/decort/utility_disk_list.go b/internal/service/cloudapi/disks/utility_disk_list.go similarity index 65% rename from decort/utility_disk_list.go rename to internal/service/cloudapi/disks/utility_disk_list.go index 447f92c..9100172 100644 --- a/decort/utility_disk_list.go +++ b/internal/service/cloudapi/disks/utility_disk_list.go @@ -1,6 +1,8 @@ /* Copyright (c) 2019-2022 Digital Energy Cloud Solutions LLC. All Rights Reserved. -Author: Stanislav Solovev, , +Authors: +Petr Krutov, +Stanislav Solovev, Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. @@ -16,13 +18,18 @@ limitations under the License. */ /* -This file is part of Terraform (by Hashicorp) provider for Digital Energy Cloud Orchestration -Technology platfom. +Terraform DECORT provider - manage resources provided by DECORT (Digital Energy Cloud +Orchestration Technology) with Terraform by Hashicorp. -Visit https://github.com/rudecs/terraform-provider-decort for full source code package and updates. +Source code: https://github.com/rudecs/terraform-provider-decort + +Please see README.md to learn where to place source code so that it +builds seamlessly. + +Documentation: https://github.com/rudecs/terraform-provider-decort/wiki */ -package decort +package disks import ( "encoding/json" @@ -30,14 +37,15 @@ import ( "strconv" "strings" + "github.com/rudecs/terraform-provider-decort/internal/controller" log "github.com/sirupsen/logrus" - "github.com/hashicorp/terraform-plugin-sdk/helper/schema" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" ) func utilityDiskListCheckPresence(d *schema.ResourceData, m interface{}) (DisksListResp, error) { diskList := DisksListResp{} - controller := m.(*ControllerCfg) + c := m.(*controller.ControllerCfg) urlValues := &url.Values{} if page, ok := d.GetOk("page"); ok { @@ -54,7 +62,7 @@ func utilityDiskListCheckPresence(d *schema.ResourceData, m interface{}) (DisksL } log.Debugf("utilityDiskListCheckPresence: load grid list") - diskListRaw, err := controller.decortAPICall("POST", DisksListAPI, urlValues) + diskListRaw, err := c.DecortAPICall("POST", DisksListAPI, urlValues) if err != nil { return nil, err } diff --git a/internal/service/cloudapi/extnet/api.go b/internal/service/cloudapi/extnet/api.go new file mode 100644 index 0000000..d0421b6 --- /dev/null +++ b/internal/service/cloudapi/extnet/api.go @@ -0,0 +1,37 @@ +/* +Copyright (c) 2019-2022 Digital Energy Cloud Solutions LLC. All Rights Reserved. +Authors: +Petr Krutov, +Stanislav Solovev, + +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. +*/ + +/* +Terraform DECORT provider - manage resources provided by DECORT (Digital Energy Cloud +Orchestration Technology) with Terraform by Hashicorp. + +Source code: https://github.com/rudecs/terraform-provider-decort + +Please see README.md to learn where to place source code so that it +builds seamlessly. + +Documentation: https://github.com/rudecs/terraform-provider-decort/wiki +*/ + +package extnet + +const extnetListAPI = "/restmachine/cloudapi/extnet/list" +const extnetListComputesAPI = "/restmachine/cloudapi/extnet/listComputes" +const extnetGetDefaultAPI = "/restmachine/cloudapi/extnet/getDefault" +const extnetGetAPI = "/restmachine/cloudapi/extnet/get" diff --git a/decort/data_source_extnet.go b/internal/service/cloudapi/extnet/data_source_extnet.go similarity index 81% rename from decort/data_source_extnet.go rename to internal/service/cloudapi/extnet/data_source_extnet.go index e28445f..ec16727 100644 --- a/decort/data_source_extnet.go +++ b/internal/service/cloudapi/extnet/data_source_extnet.go @@ -1,6 +1,8 @@ /* Copyright (c) 2019-2022 Digital Energy Cloud Solutions LLC. All Rights Reserved. -Author: Stanislav Solovev, +Authors: +Petr Krutov, +Stanislav Solovev, Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. @@ -16,29 +18,39 @@ limitations under the License. */ /* -This file is part of Terraform (by Hashicorp) provider for Digital Energy Cloud Orchestration -Technology platfom. +Terraform DECORT provider - manage resources provided by DECORT (Digital Energy Cloud +Orchestration Technology) with Terraform by Hashicorp. -Visit https://github.com/rudecs/terraform-provider-decort for full source code package and updates. +Source code: https://github.com/rudecs/terraform-provider-decort + +Please see README.md to learn where to place source code so that it +builds seamlessly. + +Documentation: https://github.com/rudecs/terraform-provider-decort/wiki */ -package decort +package extnet import ( + "context" + "github.com/google/uuid" - "github.com/hashicorp/terraform-plugin-sdk/helper/schema" + "github.com/hashicorp/terraform-plugin-sdk/v2/diag" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" + "github.com/rudecs/terraform-provider-decort/internal/constants" + "github.com/rudecs/terraform-provider-decort/internal/flattens" ) -func dataSourceExtnetRead(d *schema.ResourceData, m interface{}) error { +func dataSourceExtnetRead(ctx context.Context, d *schema.ResourceData, m interface{}) diag.Diagnostics { e, err := utilityExtnetCheckPresence(d, m) if err != nil { - return err + return diag.FromErr(err) } id := uuid.New() d.SetId(id.String()) d.Set("ckey", e.CKey) - d.Set("meta", flattenMeta(e.Meta)) + d.Set("meta", flattens.FlattenMeta(e.Meta)) d.Set("check__ips", e.CheckIPs) d.Set("check_ips", e.CheckIps) d.Set("default", e.Default) @@ -305,15 +317,15 @@ func dataSourceExtnetSchemaMake() map[string]*schema.Schema { return res } -func dataSourceExtnet() *schema.Resource { +func DataSourceExtnet() *schema.Resource { return &schema.Resource{ SchemaVersion: 1, - Read: dataSourceExtnetRead, + ReadContext: dataSourceExtnetRead, Timeouts: &schema.ResourceTimeout{ - Read: &Timeout30s, - Default: &Timeout60s, + Read: &constants.Timeout30s, + Default: &constants.Timeout60s, }, Schema: dataSourceExtnetSchemaMake(), diff --git a/decort/data_source_extnet_computes_list.go b/internal/service/cloudapi/extnet/data_source_extnet_computes_list.go similarity index 73% rename from decort/data_source_extnet_computes_list.go rename to internal/service/cloudapi/extnet/data_source_extnet_computes_list.go index c963a61..521f2a7 100644 --- a/decort/data_source_extnet_computes_list.go +++ b/internal/service/cloudapi/extnet/data_source_extnet_computes_list.go @@ -1,6 +1,8 @@ /* Copyright (c) 2019-2022 Digital Energy Cloud Solutions LLC. All Rights Reserved. -Author: Stanislav Solovev, +Authors: +Petr Krutov, +Stanislav Solovev, Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. @@ -16,17 +18,26 @@ limitations under the License. */ /* -This file is part of Terraform (by Hashicorp) provider for Digital Energy Cloud Orchestration -Technology platfom. +Terraform DECORT provider - manage resources provided by DECORT (Digital Energy Cloud +Orchestration Technology) with Terraform by Hashicorp. -Visit https://github.com/rudecs/terraform-provider-decort for full source code package and updates. +Source code: https://github.com/rudecs/terraform-provider-decort + +Please see README.md to learn where to place source code so that it +builds seamlessly. + +Documentation: https://github.com/rudecs/terraform-provider-decort/wiki */ -package decort +package extnet import ( + "context" + "github.com/google/uuid" - "github.com/hashicorp/terraform-plugin-sdk/helper/schema" + "github.com/hashicorp/terraform-plugin-sdk/v2/diag" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" + "github.com/rudecs/terraform-provider-decort/internal/constants" ) func flattenExtnetsComputes(ecs ExtnetExtendList) []map[string]interface{} { @@ -60,10 +71,10 @@ func flattenExtnetComputesList(ecl ExtnetComputesList) []map[string]interface{} return res } -func dataSourceExtnetComputesListRead(d *schema.ResourceData, m interface{}) error { +func dataSourceExtnetComputesListRead(ctx context.Context, d *schema.ResourceData, m interface{}) diag.Diagnostics { extnetComputesList, err := utilityExtnetComputesListCheckPresence(d, m) if err != nil { - return err + return diag.FromErr(err) } id := uuid.New() @@ -140,15 +151,15 @@ func dataSourceExtnetComputesListSchemaMake() map[string]*schema.Schema { return res } -func dataSourceExtnetComputesList() *schema.Resource { +func DataSourceExtnetComputesList() *schema.Resource { return &schema.Resource{ SchemaVersion: 1, - Read: dataSourceExtnetComputesListRead, + ReadContext: dataSourceExtnetComputesListRead, Timeouts: &schema.ResourceTimeout{ - Read: &Timeout30s, - Default: &Timeout60s, + Read: &constants.Timeout30s, + Default: &constants.Timeout60s, }, Schema: dataSourceExtnetComputesListSchemaMake(), diff --git a/decort/data_source_extnet_default.go b/internal/service/cloudapi/extnet/data_source_extnet_default.go similarity index 53% rename from decort/data_source_extnet_default.go rename to internal/service/cloudapi/extnet/data_source_extnet_default.go index de5585f..bf14365 100644 --- a/decort/data_source_extnet_default.go +++ b/internal/service/cloudapi/extnet/data_source_extnet_default.go @@ -1,6 +1,8 @@ /* Copyright (c) 2019-2022 Digital Energy Cloud Solutions LLC. All Rights Reserved. -Author: Stanislav Solovev, +Authors: +Petr Krutov, +Stanislav Solovev, Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. @@ -16,32 +18,40 @@ limitations under the License. */ /* -This file is part of Terraform (by Hashicorp) provider for Digital Energy Cloud Orchestration -Technology platfom. +Terraform DECORT provider - manage resources provided by DECORT (Digital Energy Cloud +Orchestration Technology) with Terraform by Hashicorp. -Visit https://github.com/rudecs/terraform-provider-decort for full source code package and updates. +Source code: https://github.com/rudecs/terraform-provider-decort + +Please see README.md to learn where to place source code so that it +builds seamlessly. + +Documentation: https://github.com/rudecs/terraform-provider-decort/wiki */ -package decort +package extnet import ( + "context" "strconv" "github.com/google/uuid" - "github.com/hashicorp/terraform-plugin-sdk/helper/schema" + "github.com/hashicorp/terraform-plugin-sdk/v2/diag" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" + "github.com/rudecs/terraform-provider-decort/internal/constants" ) -func dataSourceExtnetDefaultRead(d *schema.ResourceData, m interface{}) error { +func dataSourceExtnetDefaultRead(ctx context.Context, d *schema.ResourceData, m interface{}) diag.Diagnostics { extnetId, err := utilityExtnetDefaultCheckPresence(d, m) if err != nil { - return err + return diag.FromErr(err) } id := uuid.New() d.SetId(id.String()) extnetIdInt, err := strconv.ParseInt(extnetId, 10, 32) if err != nil { - return err + return diag.FromErr(err) } d.Set("net_id", extnetIdInt) @@ -58,15 +68,15 @@ func dataSourceExtnetDefaultSchemaMake() map[string]*schema.Schema { return res } -func dataSourceExtnetDefault() *schema.Resource { +func DataSourceExtnetDefault() *schema.Resource { return &schema.Resource{ SchemaVersion: 1, - Read: dataSourceExtnetDefaultRead, + ReadContext: dataSourceExtnetDefaultRead, Timeouts: &schema.ResourceTimeout{ - Read: &Timeout30s, - Default: &Timeout60s, + Read: &constants.Timeout30s, + Default: &constants.Timeout60s, }, Schema: dataSourceExtnetDefaultSchemaMake(), diff --git a/decort/data_source_extnet_list.go b/internal/service/cloudapi/extnet/data_source_extnet_list.go similarity index 65% rename from decort/data_source_extnet_list.go rename to internal/service/cloudapi/extnet/data_source_extnet_list.go index 4789f33..4d88625 100644 --- a/decort/data_source_extnet_list.go +++ b/internal/service/cloudapi/extnet/data_source_extnet_list.go @@ -1,6 +1,8 @@ /* Copyright (c) 2019-2022 Digital Energy Cloud Solutions LLC. All Rights Reserved. -Author: Stanislav Solovev, +Authors: +Petr Krutov, +Stanislav Solovev, Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. @@ -16,17 +18,26 @@ limitations under the License. */ /* -This file is part of Terraform (by Hashicorp) provider for Digital Energy Cloud Orchestration -Technology platfom. +Terraform DECORT provider - manage resources provided by DECORT (Digital Energy Cloud +Orchestration Technology) with Terraform by Hashicorp. -Visit https://github.com/rudecs/terraform-provider-decort for full source code package and updates. +Source code: https://github.com/rudecs/terraform-provider-decort + +Please see README.md to learn where to place source code so that it +builds seamlessly. + +Documentation: https://github.com/rudecs/terraform-provider-decort/wiki */ -package decort +package extnet import ( + "context" + "github.com/google/uuid" - "github.com/hashicorp/terraform-plugin-sdk/helper/schema" + "github.com/hashicorp/terraform-plugin-sdk/v2/diag" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" + "github.com/rudecs/terraform-provider-decort/internal/constants" ) func flattenExtnetList(el ExtnetList) []map[string]interface{} { @@ -42,10 +53,10 @@ func flattenExtnetList(el ExtnetList) []map[string]interface{} { return res } -func dataSourceExtnetListRead(d *schema.ResourceData, m interface{}) error { +func dataSourceExtnetListRead(ctx context.Context, d *schema.ResourceData, m interface{}) diag.Diagnostics { extnetList, err := utilityExtnetListCheckPresence(d, m) if err != nil { - return err + return diag.FromErr(err) } id := uuid.New() @@ -96,15 +107,15 @@ func dataSourceExtnetListSchemaMake() map[string]*schema.Schema { return res } -func dataSourceExtnetList() *schema.Resource { +func DataSourceExtnetList() *schema.Resource { return &schema.Resource{ SchemaVersion: 1, - Read: dataSourceExtnetListRead, + ReadContext: dataSourceExtnetListRead, Timeouts: &schema.ResourceTimeout{ - Read: &Timeout30s, - Default: &Timeout60s, + Read: &constants.Timeout30s, + Default: &constants.Timeout60s, }, Schema: dataSourceExtnetListSchemaMake(), diff --git a/internal/service/cloudapi/extnet/models.go b/internal/service/cloudapi/extnet/models.go new file mode 100644 index 0000000..207e06b --- /dev/null +++ b/internal/service/cloudapi/extnet/models.go @@ -0,0 +1,111 @@ +/* +Copyright (c) 2019-2022 Digital Energy Cloud Solutions LLC. All Rights Reserved. +Authors: +Petr Krutov, +Stanislav Solovev, + +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. +*/ + +/* +Terraform DECORT provider - manage resources provided by DECORT (Digital Energy Cloud +Orchestration Technology) with Terraform by Hashicorp. + +Source code: https://github.com/rudecs/terraform-provider-decort + +Please see README.md to learn where to place source code so that it +builds seamlessly. + +Documentation: https://github.com/rudecs/terraform-provider-decort/wiki +*/ + +package extnet + +type Extnet struct { + ID int `json:"id"` + IPCidr string `json:"ipcidr"` + Name string `json:"name"` +} +type ExtnetExtend struct { + Extnet + IPAddr string `json:"ipaddr"` +} + +type ExtnetList []Extnet +type ExtnetExtendList []ExtnetExtend + +type ExtnetComputes struct { + AccountId int `json:"accountId"` + AccountName string `json:"accountName"` + Extnets ExtnetExtendList `json:"extnets"` + ID int `json:"id"` + Name string `json:"name"` + RGID int `json:"rgId"` + RGName string `json:"rgName"` +} + +type ExtnetComputesList []ExtnetComputes + +type ExtnetQos struct { + ERate int `json:"eRate"` + GUID string `json:"guid"` + InBurst int `json:"inBurst"` + InRate int `json:"inRate"` +} + +type ExtnetReservation struct { + ClientType string `json:"clientType"` + Desc string `json:"desc"` + DomainName string `json:"domainname"` + HostName string `json:"hostname"` + IP string `json:"ip"` + MAC string `json:"mac"` + Type string `json:"type"` + VMID int `json:"vmId"` +} + +type ExtnetReservations []ExtnetReservation + +type ExtnetVNFS struct { + DHCP int `json:"dhcp"` +} + +type ExtnetDetailed struct { + CKey string `json:"_ckey"` + Meta []interface{} `json:"_meta"` + CheckIPs []string `json:"checkIPs"` + CheckIps []string `json:"checkIps"` + Default bool `json:"default"` + DefaultQos ExtnetQos `json:"defaultQos"` + Desc string `json:"desc"` + Dns []string `json:"dns"` + Excluded []string `json:"excluded"` + FreeIps int `json:"free_ips"` + Gateway string `json:"gateway"` + GID int `json:"gid"` + GUID int `json:"guid"` + ID int `json:"id"` + IPCidr string `json:"ipcidr"` + Milestones int `json:"milestones"` + Name string `json:"name"` + Network string `json:"network"` + NetworkId int `json:"networkId"` + PreReservationsNum int `json:"preReservationsNum"` + Prefix int `json:"prefix"` + PriVnfDevId int `json:"priVnfDevId"` + Reservations ExtnetReservations `json:"reservations"` + SharedWith []int `json:"sharedWith"` + Status string `json:"status"` + VlanID int `json:"vlanId"` + VNFS ExtnetVNFS `json:"vnfs"` +} diff --git a/decort/utility_extnet.go b/internal/service/cloudapi/extnet/utility_extnet.go similarity index 58% rename from decort/utility_extnet.go rename to internal/service/cloudapi/extnet/utility_extnet.go index f7cb0b4..037dcf9 100644 --- a/decort/utility_extnet.go +++ b/internal/service/cloudapi/extnet/utility_extnet.go @@ -1,6 +1,8 @@ /* Copyright (c) 2019-2022 Digital Energy Cloud Solutions LLC. All Rights Reserved. -Author: Stanislav Solovev, , +Authors: +Petr Krutov, +Stanislav Solovev, Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. @@ -16,33 +18,39 @@ limitations under the License. */ /* -This file is part of Terraform (by Hashicorp) provider for Digital Energy Cloud Orchestration -Technology platfom. +Terraform DECORT provider - manage resources provided by DECORT (Digital Energy Cloud +Orchestration Technology) with Terraform by Hashicorp. -Visit https://github.com/rudecs/terraform-provider-decort for full source code package and updates. +Source code: https://github.com/rudecs/terraform-provider-decort + +Please see README.md to learn where to place source code so that it +builds seamlessly. + +Documentation: https://github.com/rudecs/terraform-provider-decort/wiki */ -package decort +package extnet import ( "encoding/json" "net/url" "strconv" + "github.com/rudecs/terraform-provider-decort/internal/controller" log "github.com/sirupsen/logrus" - "github.com/hashicorp/terraform-plugin-sdk/helper/schema" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" ) func utilityExtnetCheckPresence(d *schema.ResourceData, m interface{}) (*ExtnetDetailed, error) { extnet := &ExtnetDetailed{} - controller := m.(*ControllerCfg) + c := m.(*controller.ControllerCfg) urlValues := &url.Values{} urlValues.Add("net_id", strconv.Itoa(d.Get("net_id").(int))) log.Debugf("utilityExtnetCheckPresence") - extnetRaw, err := controller.decortAPICall("POST", extnetGetAPI, urlValues) + extnetRaw, err := c.DecortAPICall("POST", extnetGetAPI, urlValues) if err != nil { return nil, err } diff --git a/decort/utility_extnet_computes_list.go b/internal/service/cloudapi/extnet/utility_extnet_computes_list.go similarity index 59% rename from decort/utility_extnet_computes_list.go rename to internal/service/cloudapi/extnet/utility_extnet_computes_list.go index 2f5c629..69f0c5e 100644 --- a/decort/utility_extnet_computes_list.go +++ b/internal/service/cloudapi/extnet/utility_extnet_computes_list.go @@ -1,6 +1,8 @@ /* Copyright (c) 2019-2022 Digital Energy Cloud Solutions LLC. All Rights Reserved. -Author: Stanislav Solovev, , +Authors: +Petr Krutov, +Stanislav Solovev, Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. @@ -16,33 +18,39 @@ limitations under the License. */ /* -This file is part of Terraform (by Hashicorp) provider for Digital Energy Cloud Orchestration -Technology platfom. +Terraform DECORT provider - manage resources provided by DECORT (Digital Energy Cloud +Orchestration Technology) with Terraform by Hashicorp. -Visit https://github.com/rudecs/terraform-provider-decort for full source code package and updates. +Source code: https://github.com/rudecs/terraform-provider-decort + +Please see README.md to learn where to place source code so that it +builds seamlessly. + +Documentation: https://github.com/rudecs/terraform-provider-decort/wiki */ -package decort +package extnet import ( "encoding/json" "net/url" "strconv" + "github.com/rudecs/terraform-provider-decort/internal/controller" log "github.com/sirupsen/logrus" - "github.com/hashicorp/terraform-plugin-sdk/helper/schema" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" ) func utilityExtnetComputesListCheckPresence(d *schema.ResourceData, m interface{}) (ExtnetComputesList, error) { extnetComputesList := ExtnetComputesList{} - controller := m.(*ControllerCfg) + c := m.(*controller.ControllerCfg) urlValues := &url.Values{} urlValues.Add("accountId", strconv.Itoa(d.Get("account_id").(int))) log.Debugf("utilityExtnetComputesListCheckPresence") - extnetComputesListRaw, err := controller.decortAPICall("POST", extnetListComputesAPI, urlValues) + extnetComputesListRaw, err := c.DecortAPICall("POST", extnetListComputesAPI, urlValues) if err != nil { return nil, err } diff --git a/decort/utility_extnet_default.go b/internal/service/cloudapi/extnet/utility_extnet_default.go similarity index 53% rename from decort/utility_extnet_default.go rename to internal/service/cloudapi/extnet/utility_extnet_default.go index a76b93c..cdf6686 100644 --- a/decort/utility_extnet_default.go +++ b/internal/service/cloudapi/extnet/utility_extnet_default.go @@ -1,6 +1,8 @@ /* Copyright (c) 2019-2022 Digital Energy Cloud Solutions LLC. All Rights Reserved. -Author: Stanislav Solovev, , +Authors: +Petr Krutov, +Stanislav Solovev, Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. @@ -16,28 +18,34 @@ limitations under the License. */ /* -This file is part of Terraform (by Hashicorp) provider for Digital Energy Cloud Orchestration -Technology platfom. +Terraform DECORT provider - manage resources provided by DECORT (Digital Energy Cloud +Orchestration Technology) with Terraform by Hashicorp. -Visit https://github.com/rudecs/terraform-provider-decort for full source code package and updates. +Source code: https://github.com/rudecs/terraform-provider-decort + +Please see README.md to learn where to place source code so that it +builds seamlessly. + +Documentation: https://github.com/rudecs/terraform-provider-decort/wiki */ -package decort +package extnet import ( "net/url" + "github.com/rudecs/terraform-provider-decort/internal/controller" log "github.com/sirupsen/logrus" - "github.com/hashicorp/terraform-plugin-sdk/helper/schema" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" ) func utilityExtnetDefaultCheckPresence(_ *schema.ResourceData, m interface{}) (string, error) { - controller := m.(*ControllerCfg) + c := m.(*controller.ControllerCfg) urlValues := &url.Values{} log.Debugf("utilityExtnetDefaultCheckPresence") - res, err := controller.decortAPICall("POST", extnetGetDefaultAPI, urlValues) + res, err := c.DecortAPICall("POST", extnetGetDefaultAPI, urlValues) if err != nil { return "", err } diff --git a/decort/utility_extnet_list.go b/internal/service/cloudapi/extnet/utility_extnet_list.go similarity index 63% rename from decort/utility_extnet_list.go rename to internal/service/cloudapi/extnet/utility_extnet_list.go index a0abe60..56411bf 100644 --- a/decort/utility_extnet_list.go +++ b/internal/service/cloudapi/extnet/utility_extnet_list.go @@ -1,6 +1,8 @@ /* Copyright (c) 2019-2022 Digital Energy Cloud Solutions LLC. All Rights Reserved. -Author: Stanislav Solovev, , +Authors: +Petr Krutov, +Stanislav Solovev, Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. @@ -16,27 +18,33 @@ limitations under the License. */ /* -This file is part of Terraform (by Hashicorp) provider for Digital Energy Cloud Orchestration -Technology platfom. +Terraform DECORT provider - manage resources provided by DECORT (Digital Energy Cloud +Orchestration Technology) with Terraform by Hashicorp. -Visit https://github.com/rudecs/terraform-provider-decort for full source code package and updates. +Source code: https://github.com/rudecs/terraform-provider-decort + +Please see README.md to learn where to place source code so that it +builds seamlessly. + +Documentation: https://github.com/rudecs/terraform-provider-decort/wiki */ -package decort +package extnet import ( "encoding/json" "net/url" "strconv" + "github.com/rudecs/terraform-provider-decort/internal/controller" log "github.com/sirupsen/logrus" - "github.com/hashicorp/terraform-plugin-sdk/helper/schema" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" ) func utilityExtnetListCheckPresence(d *schema.ResourceData, m interface{}) (ExtnetList, error) { extnetList := ExtnetList{} - controller := m.(*ControllerCfg) + c := m.(*controller.ControllerCfg) urlValues := &url.Values{} if accountId, ok := d.GetOk("account_id"); ok { @@ -50,7 +58,7 @@ func utilityExtnetListCheckPresence(d *schema.ResourceData, m interface{}) (Extn } log.Debugf("utilityExtnetListCheckPresence") - extnetListRaw, err := controller.decortAPICall("POST", extnetListAPI, urlValues) + extnetListRaw, err := c.DecortAPICall("POST", extnetListAPI, urlValues) if err != nil { return nil, err } diff --git a/internal/service/cloudapi/k8s/api.go b/internal/service/cloudapi/k8s/api.go new file mode 100644 index 0000000..ab5bf88 --- /dev/null +++ b/internal/service/cloudapi/k8s/api.go @@ -0,0 +1,49 @@ +/* +Copyright (c) 2019-2022 Digital Energy Cloud Solutions LLC. All Rights Reserved. +Authors: +Petr Krutov, +Stanislav Solovev, + +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. +*/ + +/* +Terraform DECORT provider - manage resources provided by DECORT (Digital Energy Cloud +Orchestration Technology) with Terraform by Hashicorp. + +Source code: https://github.com/rudecs/terraform-provider-decort + +Please see README.md to learn where to place source code so that it +builds seamlessly. + +Documentation: https://github.com/rudecs/terraform-provider-decort/wiki +*/ + +package k8s + +const K8sCreateAPI = "/restmachine/cloudapi/k8s/create" +const K8sGetAPI = "/restmachine/cloudapi/k8s/get" +const K8sUpdateAPI = "/restmachine/cloudapi/k8s/update" +const K8sDeleteAPI = "/restmachine/cloudapi/k8s/delete" + +const K8sWgCreateAPI = "/restmachine/cloudapi/k8s/workersGroupAdd" +const K8sWgDeleteAPI = "/restmachine/cloudapi/k8s/workersGroupDelete" + +const K8sWorkerAddAPI = "/restmachine/cloudapi/k8s/workerAdd" +const K8sWorkerDeleteAPI = "/restmachine/cloudapi/k8s/deleteWorkerFromGroup" + +const K8sGetConfigAPI = "/restmachine/cloudapi/k8s/getConfig" + +const LbGetAPI = "/restmachine/cloudapi/lb/get" + +const AsyncTaskGetAPI = "/restmachine/cloudapi/tasks/get" diff --git a/internal/service/cloudapi/k8s/models.go b/internal/service/cloudapi/k8s/models.go new file mode 100644 index 0000000..7634dd0 --- /dev/null +++ b/internal/service/cloudapi/k8s/models.go @@ -0,0 +1,131 @@ +/* +Copyright (c) 2019-2022 Digital Energy Cloud Solutions LLC. All Rights Reserved. +Authors: +Petr Krutov, +Stanislav Solovev, + +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. +*/ + +/* +Terraform DECORT provider - manage resources provided by DECORT (Digital Energy Cloud +Orchestration Technology) with Terraform by Hashicorp. + +Source code: https://github.com/rudecs/terraform-provider-decort + +Please see README.md to learn where to place source code so that it +builds seamlessly. + +Documentation: https://github.com/rudecs/terraform-provider-decort/wiki +*/ + +package k8s + +import ( + "encoding/json" + "fmt" + "strconv" +) + +type K8sNodeRecord struct { + ID int `json:"id"` + Name string `json:"name"` + Disk int `json:"disk"` + Cpu int `json:"cpu"` + Num int `json:"num"` + Ram int `json:"ram"` + DetailedInfo []struct { + ID int `json:"id"` + Name string `json:"name"` + } `json:"detailedInfo"` +} + +//K8sRecord represents k8s instance +type K8sRecord struct { + AccountID int `json:"accountId"` + AccountName string `json:"accountName"` + CI int `json:"ciId"` + ID int `json:"id"` + Groups struct { + Masters K8sNodeRecord `json:"masters"` + Workers []K8sNodeRecord `json:"workers"` + } `json:"k8sGroups"` + LbID int `json:"lbId"` + Name string `json:"name"` + RgID int `json:"rgId"` + RgName string `json:"rgName"` +} + +//LbRecord represents load balancer instance +type LbRecord struct { + ID int `json:"id"` + Name string `json:"name"` + RgID int `json:"rgId"` + VinsID int `json:"vinsId"` + ExtNetID int `json:"extnetId"` + PrimaryNode struct { + BackendIP string `json:"backendIp"` + ComputeID int `json:"computeId"` + FrontendIP string `json:"frontendIp"` + NetworkID int `json:"networkId"` + } `json:"primaryNode"` +} + +//Blasphemous workaround for parsing Result value +type TaskResult int + +func (r *TaskResult) UnmarshalJSON(b []byte) error { + if b[0] == '"' { + b := b[1 : len(b)-1] + if len(b) == 0 { + *r = 0 + return nil + } + n, err := strconv.Atoi(string(b)) + if err != nil { + return err + } + *r = TaskResult(n) + } else if b[0] == '[' { + res := []interface{}{} + if err := json.Unmarshal(b, &res); err != nil { + return err + } + if n, ok := res[0].(float64); ok { + *r = TaskResult(n) + } else { + return fmt.Errorf("could not unmarshal %v into int", res[0]) + } + } + + return nil +} + +//AsyncTask represents a long task completion status +type AsyncTask struct { + AuditID string `json:"auditId"` + Completed bool `json:"completed"` + Error string `json:"error"` + Log []string `json:"log"` + Result TaskResult `json:"result"` + Stage string `json:"stage"` + Status string `json:"status"` + UpdateTime uint64 `json:"updateTime"` + UpdatedTime uint64 `json:"updatedTime"` +} + +type SshKeyConfig struct { + User string + SshKey string + UserShell string +} diff --git a/decort/node_subresource.go b/internal/service/cloudapi/k8s/node_subresource.go similarity index 77% rename from decort/node_subresource.go rename to internal/service/cloudapi/k8s/node_subresource.go index 96040c5..78fc9ce 100644 --- a/decort/node_subresource.go +++ b/internal/service/cloudapi/k8s/node_subresource.go @@ -1,6 +1,8 @@ /* Copyright (c) 2019-2022 Digital Energy Cloud Solutions LLC. All Rights Reserved. -Author: Petr Krutov, +Authors: +Petr Krutov, +Stanislav Solovev, Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. @@ -16,15 +18,20 @@ limitations under the License. */ /* -This file is part of Terraform (by Hashicorp) provider for Digital Energy Cloud Orchestration -Technology platfom. +Terraform DECORT provider - manage resources provided by DECORT (Digital Energy Cloud +Orchestration Technology) with Terraform by Hashicorp. -Visit https://github.com/rudecs/terraform-provider-decort for full source code package and updates. +Source code: https://github.com/rudecs/terraform-provider-decort + +Please see README.md to learn where to place source code so that it +builds seamlessly. + +Documentation: https://github.com/rudecs/terraform-provider-decort/wiki */ -package decort +package k8s -import "github.com/hashicorp/terraform-plugin-sdk/helper/schema" +import "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" func nodeMasterDefault() K8sNodeRecord { return K8sNodeRecord{ diff --git a/decort/resource_k8s.go b/internal/service/cloudapi/k8s/resource_k8s.go similarity index 73% rename from decort/resource_k8s.go rename to internal/service/cloudapi/k8s/resource_k8s.go index e0f3cb0..59d240c 100644 --- a/decort/resource_k8s.go +++ b/internal/service/cloudapi/k8s/resource_k8s.go @@ -1,6 +1,8 @@ /* Copyright (c) 2019-2022 Digital Energy Cloud Solutions LLC. All Rights Reserved. -Author: Petr Krutov, +Authors: +Petr Krutov, +Stanislav Solovev, Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. @@ -16,15 +18,21 @@ limitations under the License. */ /* -This file is part of Terraform (by Hashicorp) provider for Digital Energy Cloud Orchestration -Technology platfom. +Terraform DECORT provider - manage resources provided by DECORT (Digital Energy Cloud +Orchestration Technology) with Terraform by Hashicorp. -Visit https://github.com/rudecs/terraform-provider-decort for full source code package and updates. +Source code: https://github.com/rudecs/terraform-provider-decort + +Please see README.md to learn where to place source code so that it +builds seamlessly. + +Documentation: https://github.com/rudecs/terraform-provider-decort/wiki */ -package decort +package k8s import ( + "context" "encoding/json" "fmt" "net/url" @@ -32,14 +40,17 @@ import ( "strings" "time" - "github.com/hashicorp/terraform-plugin-sdk/helper/schema" + "github.com/hashicorp/terraform-plugin-sdk/v2/diag" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" + "github.com/rudecs/terraform-provider-decort/internal/constants" + "github.com/rudecs/terraform-provider-decort/internal/controller" log "github.com/sirupsen/logrus" ) -func resourceK8sCreate(d *schema.ResourceData, m interface{}) error { +func resourceK8sCreate(ctx context.Context, d *schema.ResourceData, m interface{}) diag.Diagnostics { log.Debugf("resourceK8sCreate: called with name %s, rg %d", d.Get("name").(string), d.Get("rg_id").(int)) - controller := m.(*ControllerCfg) + c := m.(*controller.ControllerCfg) urlValues := &url.Values{} urlValues.Add("name", d.Get("name").(string)) urlValues.Add("rgId", strconv.Itoa(d.Get("rg_id").(int))) @@ -83,29 +94,29 @@ func resourceK8sCreate(d *schema.ResourceData, m interface{}) error { //urlValues.Add("desc", desc.(string)) //} - resp, err := controller.decortAPICall("POST", K8sCreateAPI, urlValues) + resp, err := c.DecortAPICall("POST", K8sCreateAPI, urlValues) if err != nil { - return err + return diag.FromErr(err) } urlValues = &url.Values{} urlValues.Add("auditId", strings.Trim(resp, `"`)) for { - resp, err := controller.decortAPICall("POST", AsyncTaskGetAPI, urlValues) + resp, err := c.DecortAPICall("POST", AsyncTaskGetAPI, urlValues) if err != nil { - return err + return diag.FromErr(err) } task := AsyncTask{} if err := json.Unmarshal([]byte(resp), &task); err != nil { - return err + return diag.FromErr(err) } log.Debugf("resourceK8sCreate: instance creating - %s", task.Stage) if task.Completed { if task.Error != "" { - return fmt.Errorf("cannot create k8s instance: %v", task.Error) + return diag.FromErr(fmt.Errorf("cannot create k8s instance: %v", task.Error)) } d.SetId(strconv.Itoa(int(task.Result))) @@ -117,7 +128,7 @@ func resourceK8sCreate(d *schema.ResourceData, m interface{}) error { k8s, err := utilityK8sCheckPresence(d, m) if err != nil { - return err + return diag.FromErr(err) } d.Set("default_wg_id", k8s.Groups.Workers[0].ID) @@ -125,21 +136,21 @@ func resourceK8sCreate(d *schema.ResourceData, m interface{}) error { urlValues = &url.Values{} urlValues.Add("lbId", strconv.Itoa(k8s.LbID)) - resp, err = controller.decortAPICall("POST", LbGetAPI, urlValues) + resp, err = c.DecortAPICall("POST", LbGetAPI, urlValues) if err != nil { - return err + return diag.FromErr(err) } var lb LbRecord if err := json.Unmarshal([]byte(resp), &lb); err != nil { - return err + return diag.FromErr(err) } d.Set("extnet_id", lb.ExtNetID) d.Set("lb_ip", lb.PrimaryNode.FrontendIP) urlValues = &url.Values{} urlValues.Add("k8sId", d.Id()) - kubeconfig, err := controller.decortAPICall("POST", K8sGetConfigAPI, urlValues) + kubeconfig, err := c.DecortAPICall("POST", K8sGetConfigAPI, urlValues) if err != nil { log.Warnf("could not get kubeconfig: %v", err) } @@ -148,13 +159,13 @@ func resourceK8sCreate(d *schema.ResourceData, m interface{}) error { return nil } -func resourceK8sRead(d *schema.ResourceData, m interface{}) error { +func resourceK8sRead(ctx context.Context, d *schema.ResourceData, m interface{}) diag.Diagnostics { log.Debugf("resourceK8sRead: called with id %s, rg %d", d.Id(), d.Get("rg_id").(int)) k8s, err := utilityK8sCheckPresence(d, m) if k8s == nil { d.SetId("") - return err + return diag.FromErr(err) } d.Set("name", k8s.Name) @@ -165,25 +176,25 @@ func resourceK8sRead(d *schema.ResourceData, m interface{}) error { d.Set("workers", nodeToResource(k8s.Groups.Workers[0])) d.Set("default_wg_id", k8s.Groups.Workers[0].ID) - controller := m.(*ControllerCfg) + c := m.(*controller.ControllerCfg) urlValues := &url.Values{} urlValues.Add("lbId", strconv.Itoa(k8s.LbID)) - resp, err := controller.decortAPICall("POST", LbGetAPI, urlValues) + resp, err := c.DecortAPICall("POST", LbGetAPI, urlValues) if err != nil { - return err + return diag.FromErr(err) } var lb LbRecord if err := json.Unmarshal([]byte(resp), &lb); err != nil { - return err + return diag.FromErr(err) } d.Set("extnet_id", lb.ExtNetID) d.Set("lb_ip", lb.PrimaryNode.FrontendIP) urlValues = &url.Values{} urlValues.Add("k8sId", d.Id()) - kubeconfig, err := controller.decortAPICall("POST", K8sGetConfigAPI, urlValues) + kubeconfig, err := c.DecortAPICall("POST", K8sGetConfigAPI, urlValues) if err != nil { log.Warnf("could not get kubeconfig: %v", err) } @@ -192,26 +203,26 @@ func resourceK8sRead(d *schema.ResourceData, m interface{}) error { return nil } -func resourceK8sUpdate(d *schema.ResourceData, m interface{}) error { +func resourceK8sUpdate(ctx context.Context, d *schema.ResourceData, m interface{}) diag.Diagnostics { log.Debugf("resourceK8sUpdate: called with id %s, rg %d", d.Id(), d.Get("rg_id").(int)) - controller := m.(*ControllerCfg) + c := m.(*controller.ControllerCfg) if d.HasChange("name") { urlValues := &url.Values{} urlValues.Add("k8sId", d.Id()) urlValues.Add("name", d.Get("name").(string)) - _, err := controller.decortAPICall("POST", K8sUpdateAPI, urlValues) + _, err := c.DecortAPICall("POST", K8sUpdateAPI, urlValues) if err != nil { - return err + return diag.FromErr(err) } } if d.HasChange("workers") { k8s, err := utilityK8sCheckPresence(d, m) if err != nil { - return err + return diag.FromErr(err) } wg := k8s.Groups.Workers[0] @@ -223,14 +234,14 @@ func resourceK8sUpdate(d *schema.ResourceData, m interface{}) error { if newWorkers.Num > wg.Num { urlValues.Add("num", strconv.Itoa(newWorkers.Num-wg.Num)) - if _, err := controller.decortAPICall("POST", K8sWorkerAddAPI, urlValues); err != nil { - return err + if _, err := c.DecortAPICall("POST", K8sWorkerAddAPI, urlValues); err != nil { + return diag.FromErr(err) } } else { for i := wg.Num - 1; i >= newWorkers.Num; i-- { urlValues.Set("workerId", strconv.Itoa(wg.DetailedInfo[i].ID)) - if _, err := controller.decortAPICall("POST", K8sWorkerDeleteAPI, urlValues); err != nil { - return err + if _, err := c.DecortAPICall("POST", K8sWorkerDeleteAPI, urlValues); err != nil { + return diag.FromErr(err) } } } @@ -239,25 +250,25 @@ func resourceK8sUpdate(d *schema.ResourceData, m interface{}) error { return nil } -func resourceK8sDelete(d *schema.ResourceData, m interface{}) error { +func resourceK8sDelete(ctx context.Context, d *schema.ResourceData, m interface{}) diag.Diagnostics { log.Debugf("resourceK8sDelete: called with id %s, rg %d", d.Id(), d.Get("rg_id").(int)) k8s, err := utilityK8sCheckPresence(d, m) if k8s == nil { if err != nil { - return err + return diag.FromErr(err) } return nil } - controller := m.(*ControllerCfg) + c := m.(*controller.ControllerCfg) urlValues := &url.Values{} urlValues.Add("k8sId", d.Id()) urlValues.Add("permanently", "true") - _, err = controller.decortAPICall("POST", K8sDeleteAPI, urlValues) + _, err = c.DecortAPICall("POST", K8sDeleteAPI, urlValues) if err != nil { - return err + return diag.FromErr(err) } return nil @@ -366,26 +377,26 @@ func resourceK8sSchemaMake() map[string]*schema.Schema { } } -func resourceK8s() *schema.Resource { +func ResourceK8s() *schema.Resource { return &schema.Resource{ SchemaVersion: 1, - Create: resourceK8sCreate, - Read: resourceK8sRead, - Update: resourceK8sUpdate, - Delete: resourceK8sDelete, - Exists: resourceK8sExists, + CreateContext: resourceK8sCreate, + ReadContext: resourceK8sRead, + UpdateContext: resourceK8sUpdate, + DeleteContext: resourceK8sDelete, + Exists: resourceK8sExists, Importer: &schema.ResourceImporter{ State: schema.ImportStatePassthrough, }, Timeouts: &schema.ResourceTimeout{ - Create: &Timeout20m, - Read: &Timeout30s, - Update: &Timeout20m, - Delete: &Timeout60s, - Default: &Timeout60s, + Create: &constants.Timeout20m, + Read: &constants.Timeout30s, + Update: &constants.Timeout20m, + Delete: &constants.Timeout60s, + Default: &constants.Timeout60s, }, Schema: resourceK8sSchemaMake(), diff --git a/decort/resource_k8s_wg.go b/internal/service/cloudapi/k8s/resource_k8s_wg.go similarity index 68% rename from decort/resource_k8s_wg.go rename to internal/service/cloudapi/k8s/resource_k8s_wg.go index d9f4054..420130d 100644 --- a/decort/resource_k8s_wg.go +++ b/internal/service/cloudapi/k8s/resource_k8s_wg.go @@ -1,6 +1,8 @@ /* Copyright (c) 2019-2022 Digital Energy Cloud Solutions LLC. All Rights Reserved. -Author: Petr Krutov, +Authors: +Petr Krutov, +Stanislav Solovev, Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. @@ -16,26 +18,35 @@ limitations under the License. */ /* -This file is part of Terraform (by Hashicorp) provider for Digital Energy Cloud Orchestration -Technology platfom. +Terraform DECORT provider - manage resources provided by DECORT (Digital Energy Cloud +Orchestration Technology) with Terraform by Hashicorp. -Visit https://github.com/rudecs/terraform-provider-decort for full source code package and updates. +Source code: https://github.com/rudecs/terraform-provider-decort + +Please see README.md to learn where to place source code so that it +builds seamlessly. + +Documentation: https://github.com/rudecs/terraform-provider-decort/wiki */ -package decort +package k8s import ( + "context" "net/url" "strconv" - "github.com/hashicorp/terraform-plugin-sdk/helper/schema" + "github.com/hashicorp/terraform-plugin-sdk/v2/diag" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" + "github.com/rudecs/terraform-provider-decort/internal/constants" + "github.com/rudecs/terraform-provider-decort/internal/controller" log "github.com/sirupsen/logrus" ) -func resourceK8sWgCreate(d *schema.ResourceData, m interface{}) error { +func resourceK8sWgCreate(ctx context.Context, d *schema.ResourceData, m interface{}) diag.Diagnostics { log.Debugf("resourceK8sWgCreate: called with k8s id %d", d.Get("k8s_id").(int)) - controller := m.(*ControllerCfg) + c := m.(*controller.ControllerCfg) urlValues := &url.Values{} urlValues.Add("k8sId", strconv.Itoa(d.Get("k8s_id").(int))) urlValues.Add("name", d.Get("name").(string)) @@ -44,9 +55,9 @@ func resourceK8sWgCreate(d *schema.ResourceData, m interface{}) error { urlValues.Add("workerRam", strconv.Itoa(d.Get("ram").(int))) urlValues.Add("workerDisk", strconv.Itoa(d.Get("disk").(int))) - resp, err := controller.decortAPICall("POST", K8sWgCreateAPI, urlValues) + resp, err := c.DecortAPICall("POST", K8sWgCreateAPI, urlValues) if err != nil { - return err + return diag.FromErr(err) } d.SetId(resp) @@ -83,13 +94,13 @@ func resourceK8sWgCreate(d *schema.ResourceData, m interface{}) error { return nil } -func resourceK8sWgRead(d *schema.ResourceData, m interface{}) error { +func resourceK8sWgRead(ctx context.Context, d *schema.ResourceData, m interface{}) diag.Diagnostics { log.Debugf("resourceK8sWgRead: called with k8s id %d", d.Get("k8s_id").(int)) wg, err := utilityK8sWgCheckPresence(d, m) if wg == nil { d.SetId("") - return err + return diag.FromErr(err) } d.Set("name", wg.Name) @@ -101,14 +112,14 @@ func resourceK8sWgRead(d *schema.ResourceData, m interface{}) error { return nil } -func resourceK8sWgUpdate(d *schema.ResourceData, m interface{}) error { +func resourceK8sWgUpdate(ctx context.Context, d *schema.ResourceData, m interface{}) diag.Diagnostics { log.Debugf("resourceK8sWgUpdate: called with k8s id %d", d.Get("k8s_id").(int)) - controller := m.(*ControllerCfg) + c := m.(*controller.ControllerCfg) wg, err := utilityK8sWgCheckPresence(d, m) if err != nil { - return err + return diag.FromErr(err) } urlValues := &url.Values{} @@ -117,16 +128,16 @@ func resourceK8sWgUpdate(d *schema.ResourceData, m interface{}) error { if newNum := d.Get("num").(int); newNum > wg.Num { urlValues.Add("num", strconv.Itoa(newNum-wg.Num)) - _, err := controller.decortAPICall("POST", K8sWorkerAddAPI, urlValues) + _, err := c.DecortAPICall("POST", K8sWorkerAddAPI, urlValues) if err != nil { - return err + return diag.FromErr(err) } } else { for i := wg.Num - 1; i >= newNum; i-- { urlValues.Set("workerId", strconv.Itoa(wg.DetailedInfo[i].ID)) - _, err := controller.decortAPICall("POST", K8sWorkerDeleteAPI, urlValues) + _, err := c.DecortAPICall("POST", K8sWorkerDeleteAPI, urlValues) if err != nil { - return err + return diag.FromErr(err) } } } @@ -134,25 +145,25 @@ func resourceK8sWgUpdate(d *schema.ResourceData, m interface{}) error { return nil } -func resourceK8sWgDelete(d *schema.ResourceData, m interface{}) error { +func resourceK8sWgDelete(ctx context.Context, d *schema.ResourceData, m interface{}) diag.Diagnostics { log.Debugf("resourceK8sWgDelete: called with k8s id %d", d.Get("k8s_id").(int)) wg, err := utilityK8sWgCheckPresence(d, m) if wg == nil { if err != nil { - return err + return diag.FromErr(err) } return nil } - controller := m.(*ControllerCfg) + c := m.(*controller.ControllerCfg) urlValues := &url.Values{} urlValues.Add("k8sId", strconv.Itoa(d.Get("k8s_id").(int))) urlValues.Add("workersGroupId", strconv.Itoa(wg.ID)) - _, err = controller.decortAPICall("POST", K8sWgDeleteAPI, urlValues) + _, err = c.DecortAPICall("POST", K8sWgDeleteAPI, urlValues) if err != nil { - return err + return diag.FromErr(err) } return nil @@ -221,26 +232,26 @@ func resourceK8sWgSchemaMake() map[string]*schema.Schema { } } -func resourceK8sWg() *schema.Resource { +func ResourceK8sWg() *schema.Resource { return &schema.Resource{ SchemaVersion: 1, - Create: resourceK8sWgCreate, - Read: resourceK8sWgRead, - Update: resourceK8sWgUpdate, - Delete: resourceK8sWgDelete, - Exists: resourceK8sWgExists, + CreateContext: resourceK8sWgCreate, + ReadContext: resourceK8sWgRead, + UpdateContext: resourceK8sWgUpdate, + DeleteContext: resourceK8sWgDelete, + Exists: resourceK8sWgExists, Importer: &schema.ResourceImporter{ State: schema.ImportStatePassthrough, }, Timeouts: &schema.ResourceTimeout{ - Create: &Timeout20m, - Read: &Timeout30s, - Update: &Timeout20m, - Delete: &Timeout60s, - Default: &Timeout60s, + Create: &constants.Timeout20m, + Read: &constants.Timeout30s, + Update: &constants.Timeout20m, + Delete: &constants.Timeout60s, + Default: &constants.Timeout60s, }, Schema: resourceK8sWgSchemaMake(), diff --git a/decort/utility_k8s.go b/internal/service/cloudapi/k8s/utility_k8s.go similarity index 58% rename from decort/utility_k8s.go rename to internal/service/cloudapi/k8s/utility_k8s.go index 2a3fcdb..b9a5db7 100644 --- a/decort/utility_k8s.go +++ b/internal/service/cloudapi/k8s/utility_k8s.go @@ -1,6 +1,8 @@ /* Copyright (c) 2019-2022 Digital Energy Cloud Solutions LLC. All Rights Reserved. -Author: Petr Krutov, +Authors: +Petr Krutov, +Stanislav Solovev, Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. @@ -16,27 +18,33 @@ limitations under the License. */ /* -This file is part of Terraform (by Hashicorp) provider for Digital Energy Cloud Orchestration -Technology platfom. +Terraform DECORT provider - manage resources provided by DECORT (Digital Energy Cloud +Orchestration Technology) with Terraform by Hashicorp. -Visit https://github.com/rudecs/terraform-provider-decort for full source code package and updates. +Source code: https://github.com/rudecs/terraform-provider-decort + +Please see README.md to learn where to place source code so that it +builds seamlessly. + +Documentation: https://github.com/rudecs/terraform-provider-decort/wiki */ -package decort +package k8s import ( "encoding/json" "net/url" - "github.com/hashicorp/terraform-plugin-sdk/helper/schema" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" + "github.com/rudecs/terraform-provider-decort/internal/controller" ) func utilityK8sCheckPresence(d *schema.ResourceData, m interface{}) (*K8sRecord, error) { - controller := m.(*ControllerCfg) + c := m.(*controller.ControllerCfg) urlValues := &url.Values{} urlValues.Add("k8sId", d.Id()) - resp, err := controller.decortAPICall("POST", K8sGetAPI, urlValues) + resp, err := c.DecortAPICall("POST", K8sGetAPI, urlValues) if err != nil { return nil, err } diff --git a/decort/utility_k8s_wg.go b/internal/service/cloudapi/k8s/utility_k8s_wg.go similarity index 63% rename from decort/utility_k8s_wg.go rename to internal/service/cloudapi/k8s/utility_k8s_wg.go index f4ed797..e95f6c6 100644 --- a/decort/utility_k8s_wg.go +++ b/internal/service/cloudapi/k8s/utility_k8s_wg.go @@ -1,6 +1,8 @@ /* Copyright (c) 2019-2022 Digital Energy Cloud Solutions LLC. All Rights Reserved. -Author: Petr Krutov, +Authors: +Petr Krutov, +Stanislav Solovev, Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. @@ -16,28 +18,34 @@ limitations under the License. */ /* -This file is part of Terraform (by Hashicorp) provider for Digital Energy Cloud Orchestration -Technology platfom. +Terraform DECORT provider - manage resources provided by DECORT (Digital Energy Cloud +Orchestration Technology) with Terraform by Hashicorp. -Visit https://github.com/rudecs/terraform-provider-decort for full source code package and updates. +Source code: https://github.com/rudecs/terraform-provider-decort + +Please see README.md to learn where to place source code so that it +builds seamlessly. + +Documentation: https://github.com/rudecs/terraform-provider-decort/wiki */ -package decort +package k8s import ( "encoding/json" "net/url" "strconv" - "github.com/hashicorp/terraform-plugin-sdk/helper/schema" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" + "github.com/rudecs/terraform-provider-decort/internal/controller" ) func utilityK8sWgCheckPresence(d *schema.ResourceData, m interface{}) (*K8sNodeRecord, error) { - controller := m.(*ControllerCfg) + c := m.(*controller.ControllerCfg) urlValues := &url.Values{} urlValues.Add("k8sId", strconv.Itoa(d.Get("k8s_id").(int))) - resp, err := controller.decortAPICall("POST", K8sGetAPI, urlValues) + resp, err := c.DecortAPICall("POST", K8sGetAPI, urlValues) if err != nil { return nil, err } diff --git a/internal/service/cloudapi/kvmvm/api.go b/internal/service/cloudapi/kvmvm/api.go new file mode 100644 index 0000000..97678d9 --- /dev/null +++ b/internal/service/cloudapi/kvmvm/api.go @@ -0,0 +1,46 @@ +/* +Copyright (c) 2019-2022 Digital Energy Cloud Solutions LLC. All Rights Reserved. +Authors: +Petr Krutov, +Stanislav Solovev, + +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. +*/ + +/* +Terraform DECORT provider - manage resources provided by DECORT (Digital Energy Cloud +Orchestration Technology) with Terraform by Hashicorp. + +Source code: https://github.com/rudecs/terraform-provider-decort + +Please see README.md to learn where to place source code so that it +builds seamlessly. + +Documentation: https://github.com/rudecs/terraform-provider-decort/wiki +*/ + +package kvmvm + +const KvmX86CreateAPI = "/restmachine/cloudapi/kvmx86/create" +const KvmPPCCreateAPI = "/restmachine/cloudapi/kvmppc/create" +const ComputeGetAPI = "/restmachine/cloudapi/compute/get" +const RgListComputesAPI = "/restmachine/cloudapi/rg/listComputes" +const ComputeNetAttachAPI = "/restmachine/cloudapi/compute/netAttach" +const ComputeNetDetachAPI = "/restmachine/cloudapi/compute/netDetach" +const ComputeDiskAttachAPI = "/restmachine/cloudapi/compute/diskAttach" +const ComputeDiskDetachAPI = "/restmachine/cloudapi/compute/diskDetach" +const ComputeStartAPI = "/restmachine/cloudapi/compute/start" +const ComputeStopAPI = "/restmachine/cloudapi/compute/stop" +const ComputeResizeAPI = "/restmachine/cloudapi/compute/resize" +const DisksResizeAPI = "/restmachine/cloudapi/disks/resize2" +const ComputeDeleteAPI = "/restmachine/cloudapi/compute/delete" diff --git a/decort/data_source_compute.go b/internal/service/cloudapi/kvmvm/data_source_compute.go similarity index 89% rename from decort/data_source_compute.go rename to internal/service/cloudapi/kvmvm/data_source_compute.go index e1b4169..6e66b98 100644 --- a/decort/data_source_compute.go +++ b/internal/service/cloudapi/kvmvm/data_source_compute.go @@ -1,6 +1,8 @@ /* -Copyright (c) 2019-2021 Digital Energy Cloud Solutions LLC. All Rights Reserved. -Author: Sergey Shubin, , +Copyright (c) 2019-2022 Digital Energy Cloud Solutions LLC. All Rights Reserved. +Authors: +Petr Krutov, +Stanislav Solovev, Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. @@ -16,24 +18,31 @@ limitations under the License. */ /* -This file is part of Terraform (by Hashicorp) provider for Digital Energy Cloud Orchestration -Technology platfom. +Terraform DECORT provider - manage resources provided by DECORT (Digital Energy Cloud +Orchestration Technology) with Terraform by Hashicorp. -Visit https://github.com/rudecs/terraform-provider-decort for full source code package and updates. +Source code: https://github.com/rudecs/terraform-provider-decort + +Please see README.md to learn where to place source code so that it +builds seamlessly. + +Documentation: https://github.com/rudecs/terraform-provider-decort/wiki */ -package decort +package kvmvm import ( + "context" "encoding/json" "fmt" // "net/url" + "github.com/rudecs/terraform-provider-decort/internal/constants" log "github.com/sirupsen/logrus" - "github.com/hashicorp/terraform-plugin-sdk/helper/schema" - // "github.com/hashicorp/terraform-plugin-sdk/helper/validation" + "github.com/hashicorp/terraform-plugin-sdk/v2/diag" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" ) // Parse list of all disks from API compute/get into a list of "extra disks" attached to this compute @@ -186,27 +195,27 @@ func flattenCompute(d *schema.ResourceData, compFacts string) error { return nil } -func dataSourceComputeRead(d *schema.ResourceData, m interface{}) error { +func dataSourceComputeRead(ctx context.Context, d *schema.ResourceData, m interface{}) diag.Diagnostics { compFacts, err := utilityComputeCheckPresence(d, m) if compFacts == "" { // if empty string is returned from utilityComputeCheckPresence then there is no // such Compute and err tells so - just return it to the calling party d.SetId("") // ensure ID is empty - return err + return diag.FromErr(err) } - return flattenCompute(d, compFacts) + return diag.FromErr(flattenCompute(d, compFacts)) } func dataSourceCompute() *schema.Resource { return &schema.Resource{ SchemaVersion: 1, - Read: dataSourceComputeRead, + ReadContext: dataSourceComputeRead, Timeouts: &schema.ResourceTimeout{ - Read: &Timeout30s, - Default: &Timeout60s, + Read: &constants.Timeout30s, + Default: &constants.Timeout60s, }, Schema: map[string]*schema.Schema{ @@ -293,7 +302,7 @@ func dataSourceCompute() *schema.Resource { "extra_disks": { Type: schema.TypeSet, Computed: true, - MaxItems: MaxExtraDisksPerCompute, + MaxItems: constants.MaxExtraDisksPerCompute, Elem: &schema.Schema{ Type: schema.TypeInt, }, @@ -314,7 +323,7 @@ func dataSourceCompute() *schema.Resource { "network": { Type: schema.TypeSet, Optional: true, - MaxItems: MaxNetworksPerCompute, + MaxItems: constants.MaxNetworksPerCompute, Elem: &schema.Resource{ Schema: networkSubresourceSchemaMake(), }, diff --git a/internal/service/cloudapi/kvmvm/models.go b/internal/service/cloudapi/kvmvm/models.go new file mode 100644 index 0000000..220fafd --- /dev/null +++ b/internal/service/cloudapi/kvmvm/models.go @@ -0,0 +1,190 @@ +/* +Copyright (c) 2019-2022 Digital Energy Cloud Solutions LLC. All Rights Reserved. +Authors: +Petr Krutov, +Stanislav Solovev, + +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. +*/ + +/* +Terraform DECORT provider - manage resources provided by DECORT (Digital Energy Cloud +Orchestration Technology) with Terraform by Hashicorp. + +Source code: https://github.com/rudecs/terraform-provider-decort + +Please see README.md to learn where to place source code so that it +builds seamlessly. + +Documentation: https://github.com/rudecs/terraform-provider-decort/wiki +*/ + +package kvmvm + +type DiskRecord struct { + Acl map[string]interface{} `json:"acl"` + AccountID int `json:"accountId"` + AccountName string `json:"accountName"` + BootPartition int `json:"bootPartition"` + CreatedTime uint64 `json:"creationTime"` + ComputeID int `json:"computeId"` + ComputeName string `json:"computeName"` + DeletedTime uint64 `json:"deletionTime"` + DeviceName string `json:"devicename"` + Desc string `json:"desc"` + DestructionTime uint64 `json:"destructionTime"` + DiskPath string `json:"diskPath"` + GridID int `json:"gid"` + GUID int `json:"guid"` + ID uint `json:"id"` + ImageID int `json:"imageId"` + Images []int `json:"images"` + IOTune map[string]interface{} `json:"iotune"` + IQN string `json:"iqn"` + Login string `json:"login"` + Name string `json:"name"` + MachineId int `json:"machineId"` + MachineName string `json:"machineName"` + Milestones uint64 `json:"milestones"` + Order int `json:"order"` + Params string `json:"params"` + Passwd string `json:"passwd"` + ParentId int `json:"parentId"` + PciSlot int `json:"pciSlot"` + Pool string `json:"pool"` + PurgeTime uint64 `json:"purgeTime"` + PurgeAttempts uint64 `json:"purgeAttempts"` + RealityDeviceNumber int `json:"realityDeviceNumber"` + ReferenceId string `json:"referenceId"` + ResID string `json:"resId"` + ResName string `json:"resName"` + Role string `json:"role"` + SepType string `json:"sepType"` + SepID int `json:"sepId"` // NOTE: absent from compute/get output + SizeMax int `json:"sizeMax"` + SizeUsed int `json:"sizeUsed"` // sum over all snapshots of this disk to report total consumed space + Snapshots []SnapshotRecord `json:"snapshots"` + Status string `json:"status"` + TechStatus string `json:"techStatus"` + Type string `json:"type"` + UpdateBy uint64 `json:"updateBy"` + VMID int `json:"vmid"` +} + +type InterfaceRecord struct { + ConnID int `json:"connId"` // This is VLAN ID or VxLAN ID, depending on ConnType + ConnType string `json:"connType"` // Either "VLAN" or "VXLAN" tag + DefaultGW string `json:"defGw"` + Guid string `json:"guid"` + IPAddress string `json:"ipAddress"` // without trailing network mask, i.e. "192.168.1.3" + MAC string `json:"mac"` + Name string `json:"name"` + NetID int `json:"netId"` // This is either ExtNet ID or ViNS ID, depending on NetType + NetMask int `json:"netMask"` + NetType string `json:"netType"` // Either "EXTNET" or "VINS" tag + PciSlot int `json:"pciSlot"` + Target string `json:"target"` + Type string `json:"type"` + VNFs []int `json:"vnfs"` + QOS InterfaceQosRecord `json:"qos"` +} + +type InterfaceQosRecord struct { + ERate int `json:"eRate"` + Guid string `json:"guid"` + InBurst int `json:"inBurst"` + InRate int `json:"inRate"` +} + +type SnapshotRecord struct { + Guid string `json:"guid"` + Label string `json:"label"` + ResId string `json:"resId"` + SnapSetGuid string `json:"snapSetGuid"` + SnapSetTime uint64 `json:"snapSetTime"` + TimeStamp uint64 `json:"timestamp"` +} + +type SnapshotRecordList []SnapshotRecord + +type ComputeGetResp struct { + // ACLs `json:"ACL"` - it is a dictionary, special parsing required + AccountID int `json:"accountId"` + AccountName string `json:"accountName"` + Arch string `json:"arch"` + BootDiskSize int `json:"bootdiskSize"` + CloneReference int `json:"cloneReference"` + Clones []int `json:"clones"` + Cpu int `json:"cpus"` + Desc string `json:"desc"` + Disks []DiskRecord `json:"disks"` + Driver string `json:"driver"` + GridID int `json:"gid"` + ID uint `json:"id"` + ImageID int `json:"imageId"` + ImageName string `json:"imageName"` + Interfaces []InterfaceRecord `json:"interfaces"` + LockStatus string `json:"lockStatus"` + ManagerID int `json:"managerId"` + ManagerType string `json:"manageType"` + Name string `json:"name"` + NatableVinsID int `json:"natableVinsId"` + NatableVinsIP string `json:"natableVinsIp"` + NatableVinsName string `json:"natableVinsName"` + NatableVinsNet string `json:"natableVinsNetwork"` + NatableVinsNetName string `json:"natableVinsNetworkName"` + OsUsers []OsUserRecord `json:"osUsers"` + Ram int `json:"ram"` + RgID int `json:"rgId"` + RgName string `json:"rgName"` + SnapSets []SnapSetRecord `json:"snapSets"` + Status string `json:"status"` + // Tags []string `json:"tags"` // Tags were reworked since DECORT 3.7.1 + TechStatus string `json:"techStatus"` + TotalDiskSize int `json:"totalDiskSize"` + UpdatedBy string `json:"updatedBy"` + UpdateTime uint64 `json:"updateTime"` + UserManaged bool `json:"userManaged"` + Vgpus []int `json:"vgpus"` + VinsConnected int `json:"vinsConnected"` + VirtualImageID int `json:"virtualImageId"` +} + +type OsUserRecord struct { + Guid string `json:"guid"` + Login string `json:"login"` + Password string `json:"password"` + PubKey string `json:"pubkey"` +} + +type SnapSetRecord struct { + Disks []int `json:"disks"` + Guid string `json:"guid"` + Label string `json:"label"` + TimeStamp uint64 `json:"timestamp"` +} + +type ComputeBriefRecord struct { // this is a brief compute specifiaction as returned by API rg/listComputes + // we do not even include here all fields as returned by this API, but only the most important that + // are really necessary to identify and distinguish computes + AccountID int `json:"accountId"` + AccountName string `json:"accountName"` + Name string `json:"name"` + ID uint `json:"id"` + RgID int `json:"rgId"` + RgName string `json:"rgName"` + Status string `json:"status"` + TechStatus string `json:"techStatus"` +} + +type RgListComputesResp []ComputeBriefRecord diff --git a/decort/network_subresource.go b/internal/service/cloudapi/kvmvm/network_subresource.go similarity index 83% rename from decort/network_subresource.go rename to internal/service/cloudapi/kvmvm/network_subresource.go index 183fe5a..4a0663f 100644 --- a/decort/network_subresource.go +++ b/internal/service/cloudapi/kvmvm/network_subresource.go @@ -1,6 +1,8 @@ /* -Copyright (c) 2019-2021 Digital Energy Cloud Solutions LLC. All Rights Reserved. -Author: Sergey Shubin, , +Copyright (c) 2019-2022 Digital Energy Cloud Solutions LLC. All Rights Reserved. +Authors: +Petr Krutov, +Stanislav Solovev, Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. @@ -15,23 +17,31 @@ See the License for the specific language governing permissions and limitations under the License. */ -package decort +/* +Terraform DECORT provider - manage resources provided by DECORT (Digital Energy Cloud +Orchestration Technology) with Terraform by Hashicorp. -import ( +Source code: https://github.com/rudecs/terraform-provider-decort - // "encoding/json" - // "fmt" +Please see README.md to learn where to place source code so that it +builds seamlessly. + +Documentation: https://github.com/rudecs/terraform-provider-decort/wiki +*/ + +package kvmvm + +import ( "bytes" "hash/fnv" + "github.com/rudecs/terraform-provider-decort/internal/provider" log "github.com/sirupsen/logrus" - // "net/url" "sort" - "github.com/hashicorp/terraform-plugin-sdk/helper/schema" - "github.com/hashicorp/terraform-plugin-sdk/helper/validation" - // "github.com/hashicorp/terraform-plugin-sdk/v2/internal/helper/hashcode" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/validation" ) // This is subresource of compute resource used when creating/managing compute network connections @@ -115,7 +125,7 @@ func networkSubresourceSchemaMake() map[string]*schema.Schema { "net_type": { Type: schema.TypeString, Required: true, - StateFunc: stateFuncToUpper, + StateFunc: provider.StateFuncToUpper, ValidateFunc: validation.StringInSlice([]string{"EXTNET", "VINS"}, false), // observe case while validating Description: "Type of the network for this connection, either EXTNET or VINS.", }, diff --git a/decort/osusers_subresource.go b/internal/service/cloudapi/kvmvm/osusers_subresource.go similarity index 73% rename from decort/osusers_subresource.go rename to internal/service/cloudapi/kvmvm/osusers_subresource.go index f146f85..2e6787f 100644 --- a/decort/osusers_subresource.go +++ b/internal/service/cloudapi/kvmvm/osusers_subresource.go @@ -1,6 +1,8 @@ /* -Copyright (c) 2019-2021 Digital Energy Cloud Solutions LLC. All Rights Reserved. -Author: Sergey Shubin, , +Copyright (c) 2019-2022 Digital Energy Cloud Solutions LLC. All Rights Reserved. +Authors: +Petr Krutov, +Stanislav Solovev, Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. @@ -15,13 +17,24 @@ See the License for the specific language governing permissions and limitations under the License. */ -package decort +/* +Terraform DECORT provider - manage resources provided by DECORT (Digital Energy Cloud +Orchestration Technology) with Terraform by Hashicorp. + +Source code: https://github.com/rudecs/terraform-provider-decort + +Please see README.md to learn where to place source code so that it +builds seamlessly. + +Documentation: https://github.com/rudecs/terraform-provider-decort/wiki +*/ + +package kvmvm import ( log "github.com/sirupsen/logrus" - "github.com/hashicorp/terraform-plugin-sdk/helper/schema" - // "github.com/hashicorp/terraform-plugin-sdk/helper/validation" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" ) func parseOsUsers(logins []OsUserRecord) []interface{} { diff --git a/decort/resource_compute.go b/internal/service/cloudapi/kvmvm/resource_compute.go similarity index 80% rename from decort/resource_compute.go rename to internal/service/cloudapi/kvmvm/resource_compute.go index ea43785..575c2a8 100644 --- a/decort/resource_compute.go +++ b/internal/service/cloudapi/kvmvm/resource_compute.go @@ -1,6 +1,8 @@ /* -Copyright (c) 2019-2021 Digital Energy Cloud Solutions LLC. All Rights Reserved. -Author: Sergey Shubin, , +Copyright (c) 2019-2022 Digital Energy Cloud Solutions LLC. All Rights Reserved. +Authors: +Petr Krutov, +Stanislav Solovev, Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. @@ -16,24 +18,34 @@ limitations under the License. */ /* -This file is part of Terraform (by Hashicorp) provider for Digital Energy Cloud Orchestration -Technology platfom. +Terraform DECORT provider - manage resources provided by DECORT (Digital Energy Cloud +Orchestration Technology) with Terraform by Hashicorp. -Visit https://github.com/rudecs/terraform-provider-decort for full source code package and updates. +Source code: https://github.com/rudecs/terraform-provider-decort + +Please see README.md to learn where to place source code so that it +builds seamlessly. + +Documentation: https://github.com/rudecs/terraform-provider-decort/wiki */ -package decort +package kvmvm import ( + "context" "encoding/json" "fmt" "net/url" "strconv" + "github.com/rudecs/terraform-provider-decort/internal/constants" + "github.com/rudecs/terraform-provider-decort/internal/controller" + "github.com/rudecs/terraform-provider-decort/internal/provider" log "github.com/sirupsen/logrus" - "github.com/hashicorp/terraform-plugin-sdk/helper/schema" - "github.com/hashicorp/terraform-plugin-sdk/helper/validation" + "github.com/hashicorp/terraform-plugin-sdk/v2/diag" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/validation" ) func cloudInitDiffSupperss(key, oldVal, newVal string, d *schema.ResourceData) bool { @@ -49,7 +61,7 @@ func cloudInitDiffSupperss(key, oldVal, newVal string, d *schema.ResourceData) b return true // suppress difference } -func resourceComputeCreate(d *schema.ResourceData, m interface{}) error { +func resourceComputeCreate(ctx context.Context, d *schema.ResourceData, m interface{}) diag.Diagnostics { // we assume all mandatory parameters it takes to create a comptue instance are properly // specified - we rely on schema "Required" attributes to let Terraform validate them for us @@ -57,9 +69,7 @@ func resourceComputeCreate(d *schema.ResourceData, m interface{}) error { // create basic Compute (i.e. without extra disks and network connections - those will be attached // by subsequent individual API calls). - // creating Compute is a multi-step workflow, which may fail at some step, so we use "partial" feature of Terraform - d.Partial(true) - controller := m.(*ControllerCfg) + c := m.(*controller.ControllerCfg) urlValues := &url.Values{} urlValues.Add("rgId", fmt.Sprintf("%d", d.Get("rg_id").(int))) urlValues.Add("name", d.Get("name").(string)) @@ -102,25 +112,14 @@ func resourceComputeCreate(d *schema.ResourceData, m interface{}) error { } } - apiResp, err := controller.decortAPICall("POST", computeCreateAPI, urlValues) + apiResp, err := c.DecortAPICall("POST", computeCreateAPI, urlValues) if err != nil { - return err + return diag.FromErr(err) } // Compute create API returns ID of the new Compute instance on success d.SetId(apiResp) // update ID of the resource to tell Terraform that the resource exists, albeit partially compId, _ := strconv.Atoi(apiResp) - d.SetPartial("name") - d.SetPartial("description") - d.SetPartial("cpu") - d.SetPartial("ram") - d.SetPartial("image_id") - d.SetPartial("boot_disk_size") - /* - if sshKeysSet { - d.SetPartial("ssh_keys") - } - */ log.Debugf("resourceComputeCreate: new simple Compute ID %d, name %s created", compId, d.Get("name").(string)) @@ -130,7 +129,7 @@ func resourceComputeCreate(d *schema.ResourceData, m interface{}) error { if argSet && argVal.(*schema.Set).Len() > 0 { // urlValues.Add("desc", argVal.(string)) log.Debugf("resourceComputeCreate: calling utilityComputeExtraDisksConfigure to attach %d extra disk(s)", argVal.(*schema.Set).Len()) - err = controller.utilityComputeExtraDisksConfigure(d, false) // do_delta=false, as we are working on a new compute + err = utilityComputeExtraDisksConfigure(d, m, false) // do_delta=false, as we are working on a new compute if err != nil { log.Errorf("resourceComputeCreate: error when attaching extra disk(s) to a new Compute ID %d: %v", compId, err) extraDisksOk = false @@ -145,7 +144,7 @@ func resourceComputeCreate(d *schema.ResourceData, m interface{}) error { argVal, argSet = d.GetOk("network") if argSet && argVal.(*schema.Set).Len() > 0 { log.Debugf("resourceComputeCreate: calling utilityComputeNetworksConfigure to attach %d network(s)", argVal.(*schema.Set).Len()) - err = controller.utilityComputeNetworksConfigure(d, false) // do_delta=false, as we are working on a new compute + err = utilityComputeNetworksConfigure(d, m, false) // do_delta=false, as we are working on a new compute if err != nil { log.Errorf("resourceComputeCreate: error when attaching networks to a new Compute ID %d: %s", compId, err) netsOk = false @@ -167,8 +166,8 @@ func resourceComputeCreate(d *schema.ResourceData, m interface{}) error { reqValues := &url.Values{} reqValues.Add("computeId", fmt.Sprintf("%d", compId)) log.Debugf("resourceComputeCreate: starting Compute ID %d after completing its resource configuration", compId) - if _, err := controller.decortAPICall("POST", ComputeStartAPI, reqValues); err != nil { - return err + if _, err := c.DecortAPICall("POST", ComputeStartAPI, reqValues); err != nil { + return diag.FromErr(err) } } @@ -178,24 +177,24 @@ func resourceComputeCreate(d *schema.ResourceData, m interface{}) error { // between Compute resource and Compute data source schemas // Compute read function will also update resource ID on success, so that Terraform // will know the resource exists - return dataSourceComputeRead(d, m) + return dataSourceComputeRead(ctx, d, m) } -func resourceComputeRead(d *schema.ResourceData, m interface{}) error { +func resourceComputeRead(ctx context.Context, d *schema.ResourceData, m interface{}) diag.Diagnostics { log.Debugf("resourceComputeRead: called for Compute name %s, RG ID %d", d.Get("name").(string), d.Get("rg_id").(int)) compFacts, err := utilityComputeCheckPresence(d, m) if compFacts == "" { if err != nil { - return err + return diag.FromErr(err) } // Compute with such name and RG ID was not found return nil } if err = flattenCompute(d, compFacts); err != nil { - return err + return diag.FromErr(err) } log.Debugf("resourceComputeRead: after flattenCompute: Compute ID %s, name %q, RG ID %d", @@ -204,11 +203,11 @@ func resourceComputeRead(d *schema.ResourceData, m interface{}) error { return nil } -func resourceComputeUpdate(d *schema.ResourceData, m interface{}) error { +func resourceComputeUpdate(ctx context.Context, d *schema.ResourceData, m interface{}) diag.Diagnostics { log.Debugf("resourceComputeUpdate: called for Compute ID %s / name %s, RGID %d", d.Id(), d.Get("name").(string), d.Get("rg_id").(int)) - controller := m.(*ControllerCfg) + c := m.(*controller.ControllerCfg) /* 1. Resize CPU/RAM @@ -246,10 +245,11 @@ func resourceComputeUpdate(d *schema.ResourceData, m interface{}) error { oldCpu.(int), newCpu.(int), oldRam.(int), newRam.(int)) params.Add("force", "true") - _, err := controller.decortAPICall("POST", ComputeResizeAPI, params) + _, err := c.DecortAPICall("POST", ComputeResizeAPI, params) if err != nil { - return err + return diag.FromErr(err) } + d.SetPartial("cpu") d.SetPartial("ram") } @@ -262,9 +262,9 @@ func resourceComputeUpdate(d *schema.ResourceData, m interface{}) error { bdsParams.Add("size", fmt.Sprintf("%d", newSize.(int))) log.Debugf("resourceComputeUpdate: compute ID %s, boot disk ID %d resize %d -> %d", d.Id(), d.Get("boot_disk_id").(int), oldSize.(int), newSize.(int)) - _, err := controller.decortAPICall("POST", DisksResizeAPI, bdsParams) + _, err := c.DecortAPICall("POST", DisksResizeAPI, bdsParams) if err != nil { - return err + return diag.FromErr(err) } d.SetPartial("boot_disk_size") } else if oldSize.(int) > newSize.(int) { @@ -272,44 +272,37 @@ func resourceComputeUpdate(d *schema.ResourceData, m interface{}) error { } // 3. Calculate and apply changes to data disks - err := controller.utilityComputeExtraDisksConfigure(d, true) // pass do_delta = true to apply changes, if any + err := utilityComputeExtraDisksConfigure(d, m, true) // pass do_delta = true to apply changes, if any if err != nil { - return err - } else { - d.SetPartial("extra_disks") + return diag.FromErr(err) } // 4. Calculate and apply changes to network connections - err = controller.utilityComputeNetworksConfigure(d, true) // pass do_delta = true to apply changes, if any + err = utilityComputeNetworksConfigure(d, m, true) // pass do_delta = true to apply changes, if any if err != nil { - return err - } else { - d.SetPartial("network") + return diag.FromErr(err) } if d.HasChange("started") { params := &url.Values{} params.Add("computeId", d.Id()) if d.Get("started").(bool) { - if _, err := controller.decortAPICall("POST", ComputeStartAPI, params); err != nil { - return err + if _, err := c.DecortAPICall("POST", ComputeStartAPI, params); err != nil { + return diag.FromErr(err) } } else { - if _, err := controller.decortAPICall("POST", ComputeStopAPI, params); err != nil { - return err + if _, err := c.DecortAPICall("POST", ComputeStopAPI, params); err != nil { + return diag.FromErr(err) } } - d.SetPartial("started") } - d.Partial(false) - // we may reuse dataSourceComputeRead here as we maintain similarity // between Compute resource and Compute data source schemas - return dataSourceComputeRead(d, m) + return dataSourceComputeRead(ctx, d, m) } -func resourceComputeDelete(d *schema.ResourceData, m interface{}) error { +func resourceComputeDelete(ctx context.Context, d *schema.ResourceData, m interface{}) diag.Diagnostics { // NOTE: this function destroys target Compute instance "permanently", so // there is no way to restore it. // If compute being destroyed has some extra disks attached, they are @@ -320,14 +313,14 @@ func resourceComputeDelete(d *schema.ResourceData, m interface{}) error { compFacts, err := utilityComputeCheckPresence(d, m) if compFacts == "" { if err != nil { - return err + return diag.FromErr(err) } // the target Compute does not exist - in this case according to Terraform best practice // we exit from Destroy method without error return nil } - controller := m.(*ControllerCfg) + c := m.(*controller.ControllerCfg) model := ComputeGetResp{} log.Debugf("resourceComputeDelete: ready to unmarshal string %s", compFacts) @@ -347,7 +340,7 @@ func resourceComputeDelete(d *schema.ResourceData, m interface{}) error { detachParams.Add("computeId", d.Id()) detachParams.Add("diskId", fmt.Sprintf("%d", diskFacts.ID)) - _, err = controller.decortAPICall("POST", ComputeDiskDetachAPI, detachParams) + _, err = c.DecortAPICall("POST", ComputeDiskDetachAPI, detachParams) if err != nil { // We do not fail compute deletion on data disk detach errors log.Errorf("resourceComputeDelete: error when detaching Disk ID %d: %s", diskFacts.ID, err) @@ -360,9 +353,9 @@ func resourceComputeDelete(d *schema.ResourceData, m interface{}) error { params.Add("permanently", "1") // TODO: this is for the upcoming API update - params.Add("detachdisks", "1") - _, err = controller.decortAPICall("POST", ComputeDeleteAPI, params) + _, err = c.DecortAPICall("POST", ComputeDeleteAPI, params) if err != nil { - return err + return diag.FromErr(err) } return nil @@ -383,26 +376,26 @@ func resourceComputeExists(d *schema.ResourceData, m interface{}) (bool, error) return true, nil } -func resourceCompute() *schema.Resource { +func ResourceCompute() *schema.Resource { return &schema.Resource{ SchemaVersion: 1, - Create: resourceComputeCreate, - Read: resourceComputeRead, - Update: resourceComputeUpdate, - Delete: resourceComputeDelete, - Exists: resourceComputeExists, + CreateContext: resourceComputeCreate, + ReadContext: resourceComputeRead, + UpdateContext: resourceComputeUpdate, + DeleteContext: resourceComputeDelete, + Exists: resourceComputeExists, Importer: &schema.ResourceImporter{ State: schema.ImportStatePassthrough, }, Timeouts: &schema.ResourceTimeout{ - Create: &Timeout180s, - Read: &Timeout30s, - Update: &Timeout180s, - Delete: &Timeout60s, - Default: &Timeout60s, + Create: &constants.Timeout180s, + Read: &constants.Timeout30s, + Update: &constants.Timeout180s, + Delete: &constants.Timeout60s, + Default: &constants.Timeout60s, }, Schema: map[string]*schema.Schema{ @@ -423,7 +416,7 @@ func resourceCompute() *schema.Resource { Type: schema.TypeString, Required: true, ForceNew: true, - StateFunc: stateFuncToUpper, + StateFunc: provider.StateFuncToUpper, ValidateFunc: validation.StringInSlice([]string{"KVM_X86", "KVM_PPC"}, false), // observe case while validating Description: "Hardware architecture of this compute instance.", }, @@ -431,14 +424,14 @@ func resourceCompute() *schema.Resource { "cpu": { Type: schema.TypeInt, Required: true, - ValidateFunc: validation.IntBetween(1, MaxCpusPerCompute), + ValidateFunc: validation.IntBetween(1, constants.MaxCpusPerCompute), Description: "Number of CPUs to allocate to this compute instance.", }, "ram": { Type: schema.TypeInt, Required: true, - ValidateFunc: validation.IntAtLeast(MinRamPerCompute), + ValidateFunc: validation.IntAtLeast(constants.MinRamPerCompute), Description: "Amount of RAM in MB to allocate to this compute instance.", }, @@ -459,7 +452,7 @@ func resourceCompute() *schema.Resource { "extra_disks": { Type: schema.TypeSet, Optional: true, - MaxItems: MaxExtraDisksPerCompute, + MaxItems: constants.MaxExtraDisksPerCompute, Elem: &schema.Schema{ Type: schema.TypeInt, }, @@ -469,7 +462,7 @@ func resourceCompute() *schema.Resource { "network": { Type: schema.TypeSet, Optional: true, - MaxItems: MaxNetworksPerCompute, + MaxItems: constants.MaxNetworksPerCompute, Elem: &schema.Resource{ Schema: networkSubresourceSchemaMake(), }, diff --git a/decort/utility_compute.go b/internal/service/cloudapi/kvmvm/utility_compute.go similarity index 86% rename from decort/utility_compute.go rename to internal/service/cloudapi/kvmvm/utility_compute.go index d8b559d..894e81d 100644 --- a/decort/utility_compute.go +++ b/internal/service/cloudapi/kvmvm/utility_compute.go @@ -1,6 +1,8 @@ /* -Copyright (c) 2019-2021 Digital Energy Cloud Solutions LLC. All Rights Reserved. -Author: Sergey Shubin, , +Copyright (c) 2019-2022 Digital Energy Cloud Solutions LLC. All Rights Reserved. +Authors: +Petr Krutov, +Stanislav Solovev, Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. @@ -16,13 +18,18 @@ limitations under the License. */ /* -This file is part of Terraform (by Hashicorp) provider for Digital Energy Cloud Orchestration -Technology platfom. +Terraform DECORT provider - manage resources provided by DECORT (Digital Energy Cloud +Orchestration Technology) with Terraform by Hashicorp. -Visit https://github.com/rudecs/terraform-provider-decort for full source code package and updates. +Source code: https://github.com/rudecs/terraform-provider-decort + +Please see README.md to learn where to place source code so that it +builds seamlessly. + +Documentation: https://github.com/rudecs/terraform-provider-decort/wiki */ -package decort +package kvmvm import ( "encoding/json" @@ -30,13 +37,13 @@ import ( "net/url" "strconv" + "github.com/rudecs/terraform-provider-decort/internal/controller" log "github.com/sirupsen/logrus" - "github.com/hashicorp/terraform-plugin-sdk/helper/schema" - // "github.com/hashicorp/terraform-plugin-sdk/helper/validation" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" ) -func (ctrl *ControllerCfg) utilityComputeExtraDisksConfigure(d *schema.ResourceData, do_delta bool) error { +func utilityComputeExtraDisksConfigure(d *schema.ResourceData, m interface{}, do_delta bool) error { // d is filled with data according to computeResource schema, so extra disks config is retrieved via "extra_disks" key // If do_delta is true, this function will identify changes between new and existing specs for extra disks and try to // update compute configuration accordingly @@ -45,6 +52,8 @@ func (ctrl *ControllerCfg) utilityComputeExtraDisksConfigure(d *schema.ResourceD // Note that this function will not abort on API errors, but will continue to configure (attach / detach) other individual // disks via atomic API calls. However, it will not retry failed manipulation on the same disk. + c := m.(*controller.ControllerCfg) + log.Debugf("utilityComputeExtraDisksConfigure: called for Compute ID %s with do_delta = %t", d.Id(), do_delta) // NB: as of rc-1.25 "extra_disks" are TypeSet with the elem of TypeInt @@ -62,7 +71,7 @@ func (ctrl *ControllerCfg) utilityComputeExtraDisksConfigure(d *schema.ResourceD urlValues := &url.Values{} urlValues.Add("computeId", d.Id()) urlValues.Add("diskId", fmt.Sprintf("%d", disk.(int))) - _, err := ctrl.decortAPICall("POST", ComputeDiskAttachAPI, urlValues) + _, err := c.DecortAPICall("POST", ComputeDiskAttachAPI, urlValues) if err != nil { // failed to attach extra disk - partial resource update apiErrCount++ @@ -85,7 +94,7 @@ func (ctrl *ControllerCfg) utilityComputeExtraDisksConfigure(d *schema.ResourceD urlValues := &url.Values{} urlValues.Add("computeId", d.Id()) urlValues.Add("diskId", fmt.Sprintf("%d", diskId.(int))) - _, err := ctrl.decortAPICall("POST", ComputeDiskDetachAPI, urlValues) + _, err := c.DecortAPICall("POST", ComputeDiskDetachAPI, urlValues) if err != nil { // failed to detach disk - there will be partial resource update log.Errorf("utilityComputeExtraDisksConfigure: failed to detach disk ID %d from Compute ID %s: %s", diskId.(int), d.Id(), err) @@ -100,7 +109,7 @@ func (ctrl *ControllerCfg) utilityComputeExtraDisksConfigure(d *schema.ResourceD urlValues := &url.Values{} urlValues.Add("computeId", d.Id()) urlValues.Add("diskId", fmt.Sprintf("%d", diskId.(int))) - _, err := ctrl.decortAPICall("POST", ComputeDiskAttachAPI, urlValues) + _, err := c.DecortAPICall("POST", ComputeDiskAttachAPI, urlValues) if err != nil { // failed to attach disk - there will be partial resource update log.Errorf("utilityComputeExtraDisksConfigure: failed to attach disk ID %d to Compute ID %s: %s", diskId.(int), d.Id(), err) @@ -118,13 +127,15 @@ func (ctrl *ControllerCfg) utilityComputeExtraDisksConfigure(d *schema.ResourceD return nil } -func (ctrl *ControllerCfg) utilityComputeNetworksConfigure(d *schema.ResourceData, do_delta bool) error { +func utilityComputeNetworksConfigure(d *schema.ResourceData, m interface{}, do_delta bool) error { // "d" is filled with data according to computeResource schema, so extra networks config is retrieved via "network" key // If do_delta is true, this function will identify changes between new and existing specs for network and try to // update compute configuration accordingly // Otherwise it will apply whatever is found in the new set of "network" right away. // Primary use of do_delta=false is when calling this function from compute Create handler. + c := m.(*controller.ControllerCfg) + old_set, new_set := d.GetChange("network") apiErrCount := 0 @@ -145,7 +156,7 @@ func (ctrl *ControllerCfg) utilityComputeNetworksConfigure(d *schema.ResourceDat if ipSet { urlValues.Add("ipAddr", ipaddr.(string)) } - _, err := ctrl.decortAPICall("POST", ComputeNetAttachAPI, urlValues) + _, err := c.DecortAPICall("POST", ComputeNetAttachAPI, urlValues) if err != nil { // failed to attach network - partial resource update apiErrCount++ @@ -169,7 +180,7 @@ func (ctrl *ControllerCfg) utilityComputeNetworksConfigure(d *schema.ResourceDat urlValues.Add("computeId", d.Id()) urlValues.Add("ipAddr", net_data["ip_address"].(string)) urlValues.Add("mac", net_data["mac"].(string)) - _, err := ctrl.decortAPICall("POST", ComputeNetDetachAPI, urlValues) + _, err := c.DecortAPICall("POST", ComputeNetDetachAPI, urlValues) if err != nil { // failed to detach this network - there will be partial resource update log.Errorf("utilityComputeNetworksConfigure: failed to detach net ID %d of type %s from Compute ID %s: %s", @@ -190,7 +201,7 @@ func (ctrl *ControllerCfg) utilityComputeNetworksConfigure(d *schema.ResourceDat if net_data["ip_address"].(string) != "" { urlValues.Add("ipAddr", net_data["ip_address"].(string)) } - _, err := ctrl.decortAPICall("POST", ComputeNetAttachAPI, urlValues) + _, err := c.DecortAPICall("POST", ComputeNetAttachAPI, urlValues) if err != nil { // failed to attach this network - there will be partial resource update log.Errorf("utilityComputeNetworksConfigure: failed to attach net ID %d of type %s to Compute ID %s: %s", @@ -223,7 +234,7 @@ func utilityComputeCheckPresence(d *schema.ResourceData, m interface{}) (string, // method for resource's Exists method. // - controller := m.(*ControllerCfg) + c := m.(*controller.ControllerCfg) urlValues := &url.Values{} // make it possible to use "read" & "check presence" functions with compute ID set so @@ -244,7 +255,7 @@ func utilityComputeCheckPresence(d *schema.ResourceData, m interface{}) (string, // compute ID is specified, try to get compute instance straight by this ID log.Debugf("utilityComputeCheckPresence: locating compute by its ID %d", theId) urlValues.Add("computeId", fmt.Sprintf("%d", theId)) - computeFacts, err := controller.decortAPICall("POST", ComputeGetAPI, urlValues) + computeFacts, err := c.DecortAPICall("POST", ComputeGetAPI, urlValues) if err != nil { return "", err } @@ -264,7 +275,7 @@ func utilityComputeCheckPresence(d *schema.ResourceData, m interface{}) (string, } urlValues.Add("rgId", fmt.Sprintf("%d", rgId)) - apiResp, err := controller.decortAPICall("POST", RgListComputesAPI, urlValues) + apiResp, err := c.DecortAPICall("POST", RgListComputesAPI, urlValues) if err != nil { return "", err } @@ -286,7 +297,7 @@ func utilityComputeCheckPresence(d *schema.ResourceData, m interface{}) (string, // we found the Compute we need - now get detailed information via compute/get API cgetValues := &url.Values{} cgetValues.Add("computeId", fmt.Sprintf("%d", item.ID)) - apiResp, err = controller.decortAPICall("POST", ComputeGetAPI, cgetValues) + apiResp, err = c.DecortAPICall("POST", ComputeGetAPI, cgetValues) if err != nil { return "", err } diff --git a/internal/service/cloudapi/pfw/api.go b/internal/service/cloudapi/pfw/api.go new file mode 100644 index 0000000..8a13c4f --- /dev/null +++ b/internal/service/cloudapi/pfw/api.go @@ -0,0 +1,36 @@ +/* +Copyright (c) 2019-2022 Digital Energy Cloud Solutions LLC. All Rights Reserved. +Authors: +Petr Krutov, +Stanislav Solovev, + +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. +*/ + +/* +Terraform DECORT provider - manage resources provided by DECORT (Digital Energy Cloud +Orchestration Technology) with Terraform by Hashicorp. + +Source code: https://github.com/rudecs/terraform-provider-decort + +Please see README.md to learn where to place source code so that it +builds seamlessly. + +Documentation: https://github.com/rudecs/terraform-provider-decort/wiki +*/ + +package pfw + +const ComputePfwListAPI = "/restmachine/cloudapi/compute/pfwList" +const ComputePfwAddAPI = "/restmachine/cloudapi/compute/pfwAdd" +const ComputePfwDelAPI = "/restmachine/cloudapi/compute/pfwDel" diff --git a/internal/service/cloudapi/pfw/models.go b/internal/service/cloudapi/pfw/models.go new file mode 100644 index 0000000..e74524b --- /dev/null +++ b/internal/service/cloudapi/pfw/models.go @@ -0,0 +1,45 @@ +/* +Copyright (c) 2019-2022 Digital Energy Cloud Solutions LLC. All Rights Reserved. +Authors: +Petr Krutov, +Stanislav Solovev, + +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. +*/ + +/* +Terraform DECORT provider - manage resources provided by DECORT (Digital Energy Cloud +Orchestration Technology) with Terraform by Hashicorp. + +Source code: https://github.com/rudecs/terraform-provider-decort + +Please see README.md to learn where to place source code so that it +builds seamlessly. + +Documentation: https://github.com/rudecs/terraform-provider-decort/wiki +*/ + +package pfw +type PfwRecord struct { + ID int `json:"id"` + LocalIP string `json:"localIp"` + LocalPort int `json:"localPort"` + Protocol string `json:"protocol"` + PublicPortEnd int `json:"publicPortEnd"` + PublicPortStart int `json:"publicPortStart"` + ComputeID int `json:"vmId"` +} + +type ComputePfwListResp []PfwRecord + + diff --git a/decort/resource_pfw.go b/internal/service/cloudapi/pfw/resource_pfw.go similarity index 68% rename from decort/resource_pfw.go rename to internal/service/cloudapi/pfw/resource_pfw.go index 314bc1a..381bcb2 100644 --- a/decort/resource_pfw.go +++ b/internal/service/cloudapi/pfw/resource_pfw.go @@ -1,6 +1,8 @@ /* -Copyright (c) 2019-2021 Digital Energy Cloud Solutions LLC. All Rights Reserved. -Author: Petr Krutov, +Copyright (c) 2019-2022 Digital Energy Cloud Solutions LLC. All Rights Reserved. +Authors: +Petr Krutov, +Stanislav Solovev, Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. @@ -16,28 +18,37 @@ limitations under the License. */ /* -This file is part of Terraform (by Hashicorp) provider for Digital Energy Cloud Orchestration -Technology platfom. +Terraform DECORT provider - manage resources provided by DECORT (Digital Energy Cloud +Orchestration Technology) with Terraform by Hashicorp. -Visit https://github.com/rudecs/terraform-provider-decort for full source code package and updates. +Source code: https://github.com/rudecs/terraform-provider-decort + +Please see README.md to learn where to place source code so that it +builds seamlessly. + +Documentation: https://github.com/rudecs/terraform-provider-decort/wiki */ -package decort +package pfw import ( + "context" "fmt" "net/url" "strconv" - "github.com/hashicorp/terraform-plugin-sdk/helper/schema" - "github.com/hashicorp/terraform-plugin-sdk/helper/validation" + "github.com/hashicorp/terraform-plugin-sdk/v2/diag" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/validation" + "github.com/rudecs/terraform-provider-decort/internal/constants" + "github.com/rudecs/terraform-provider-decort/internal/controller" log "github.com/sirupsen/logrus" ) -func resourcePfwCreate(d *schema.ResourceData, m interface{}) error { +func resourcePfwCreate(ctx context.Context, d *schema.ResourceData, m interface{}) diag.Diagnostics { log.Debugf("resourcePfwCreate: called for compute %d", d.Get("compute_id").(int)) - controller := m.(*ControllerCfg) + c := m.(*controller.ControllerCfg) urlValues := &url.Values{} urlValues.Add("computeId", strconv.Itoa(d.Get("compute_id").(int))) urlValues.Add("publicPortStart", strconv.Itoa(d.Get("public_port_start").(int))) @@ -48,16 +59,16 @@ func resourcePfwCreate(d *schema.ResourceData, m interface{}) error { urlValues.Add("publicPortEnd", strconv.Itoa(portEnd.(int))) } - pfwId, err := controller.decortAPICall("POST", ComputePfwAddAPI, urlValues) + pfwId, err := c.DecortAPICall("POST", ComputePfwAddAPI, urlValues) if err != nil { - return err + return diag.FromErr(err) } d.SetId(fmt.Sprintf("%d-%s", d.Get("compute_id").(int), pfwId)) pfw, err := utilityPfwCheckPresence(d, m) if err != nil { - return err + return diag.FromErr(err) } d.Set("local_ip", pfw.LocalIP) @@ -68,13 +79,13 @@ func resourcePfwCreate(d *schema.ResourceData, m interface{}) error { return nil } -func resourcePfwRead(d *schema.ResourceData, m interface{}) error { +func resourcePfwRead(ctx context.Context, d *schema.ResourceData, m interface{}) diag.Diagnostics { log.Debugf("resourcePfwRead: called for compute %d, rule %s", d.Get("compute_id").(int), d.Id()) pfw, err := utilityPfwCheckPresence(d, m) if pfw == nil { d.SetId("") - return err + return diag.FromErr(err) } d.Set("compute_id", pfw.ComputeID) @@ -87,25 +98,25 @@ func resourcePfwRead(d *schema.ResourceData, m interface{}) error { return nil } -func resourcePfwDelete(d *schema.ResourceData, m interface{}) error { +func resourcePfwDelete(ctx context.Context, d *schema.ResourceData, m interface{}) diag.Diagnostics { log.Debugf("resourcePfwDelete: called for compute %d, rule %s", d.Get("compute_id").(int), d.Id()) pfw, err := utilityPfwCheckPresence(d, m) if pfw == nil { if err != nil { - return err + return diag.FromErr(err) } return nil } - controller := m.(*ControllerCfg) + c := m.(*controller.ControllerCfg) urlValues := &url.Values{} urlValues.Add("computeId", strconv.Itoa(d.Get("compute_id").(int))) urlValues.Add("ruleId", strconv.Itoa(pfw.ID)) - _, err = controller.decortAPICall("POST", ComputePfwDelAPI, urlValues) + _, err = c.DecortAPICall("POST", ComputePfwDelAPI, urlValues) if err != nil { - return err + return diag.FromErr(err) } return nil @@ -175,25 +186,25 @@ func resourcePfwSchemaMake() map[string]*schema.Schema { } } -func resourcePfw() *schema.Resource { +func ResourcePfw() *schema.Resource { return &schema.Resource{ SchemaVersion: 1, - Create: resourcePfwCreate, - Read: resourcePfwRead, - Delete: resourcePfwDelete, - Exists: resourcePfwExists, + CreateContext: resourcePfwCreate, + ReadContext: resourcePfwRead, + DeleteContext: resourcePfwDelete, + Exists: resourcePfwExists, Importer: &schema.ResourceImporter{ State: schema.ImportStatePassthrough, }, Timeouts: &schema.ResourceTimeout{ - Create: &Timeout60s, - Read: &Timeout30s, - Update: &Timeout60s, - Delete: &Timeout60s, - Default: &Timeout60s, + Create: &constants.Timeout60s, + Read: &constants.Timeout30s, + Update: &constants.Timeout60s, + Delete: &constants.Timeout60s, + Default: &constants.Timeout60s, }, Schema: resourcePfwSchemaMake(), diff --git a/decort/utility_pfw.go b/internal/service/cloudapi/pfw/utility_pfw.go similarity index 63% rename from decort/utility_pfw.go rename to internal/service/cloudapi/pfw/utility_pfw.go index ea125fb..af7937f 100644 --- a/decort/utility_pfw.go +++ b/internal/service/cloudapi/pfw/utility_pfw.go @@ -1,6 +1,8 @@ /* Copyright (c) 2019-2022 Digital Energy Cloud Solutions LLC. All Rights Reserved. -Author: Petr Krutov, +Authors: +Petr Krutov, +Stanislav Solovev, Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. @@ -16,13 +18,18 @@ limitations under the License. */ /* -This file is part of Terraform (by Hashicorp) provider for Digital Energy Cloud Orchestration -Technology platfom. +Terraform DECORT provider - manage resources provided by DECORT (Digital Energy Cloud +Orchestration Technology) with Terraform by Hashicorp. -Visit https://github.com/rudecs/terraform-provider-decort for full source code package and updates. +Source code: https://github.com/rudecs/terraform-provider-decort + +Please see README.md to learn where to place source code so that it +builds seamlessly. + +Documentation: https://github.com/rudecs/terraform-provider-decort/wiki */ -package decort +package pfw import ( "encoding/json" @@ -30,15 +37,16 @@ import ( "strconv" "strings" - "github.com/hashicorp/terraform-plugin-sdk/helper/schema" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" + "github.com/rudecs/terraform-provider-decort/internal/controller" ) func utilityPfwCheckPresence(d *schema.ResourceData, m interface{}) (*PfwRecord, error) { - controller := m.(*ControllerCfg) + c := m.(*controller.ControllerCfg) urlValues := &url.Values{} urlValues.Add("computeId", strconv.Itoa(d.Get("compute_id").(int))) - resp, err := controller.decortAPICall("POST", ComputePfwListAPI, urlValues) + resp, err := c.DecortAPICall("POST", ComputePfwListAPI, urlValues) if err != nil { return nil, err } diff --git a/internal/service/cloudapi/rg/api.go b/internal/service/cloudapi/rg/api.go new file mode 100644 index 0000000..c9067f6 --- /dev/null +++ b/internal/service/cloudapi/rg/api.go @@ -0,0 +1,39 @@ +/* +Copyright (c) 2019-2022 Digital Energy Cloud Solutions LLC. All Rights Reserved. +Authors: +Petr Krutov, +Stanislav Solovev, + +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. +*/ + +/* +Terraform DECORT provider - manage resources provided by DECORT (Digital Energy Cloud +Orchestration Technology) with Terraform by Hashicorp. + +Source code: https://github.com/rudecs/terraform-provider-decort + +Please see README.md to learn where to place source code so that it +builds seamlessly. + +Documentation: https://github.com/rudecs/terraform-provider-decort/wiki +*/ + +package rg + +const ResgroupCreateAPI = "/restmachine/cloudapi/rg/create" +const ResgroupUpdateAPI = "/restmachine/cloudapi/rg/update" +const ResgroupListAPI = "/restmachine/cloudapi/rg/list" +const ResgroupGetAPI = "/restmachine/cloudapi/rg/get" +const ResgroupDeleteAPI = "/restmachine/cloudapi/rg/delete" +const RgListComputesAPI = "/restmachine/cloudapi/rg/listComputes" diff --git a/decort/data_source_rg.go b/internal/service/cloudapi/rg/data_source_rg.go similarity index 68% rename from decort/data_source_rg.go rename to internal/service/cloudapi/rg/data_source_rg.go index c1ae000..33f7f0e 100644 --- a/decort/data_source_rg.go +++ b/internal/service/cloudapi/rg/data_source_rg.go @@ -1,6 +1,8 @@ /* -Copyright (c) 2019-2021 Digital Energy Cloud Solutions LLC. All Rights Reserved. -Author: Sergey Shubin, , +Copyright (c) 2019-2022 Digital Energy Cloud Solutions LLC. All Rights Reserved. +Authors: +Petr Krutov, +Stanislav Solovev, Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. @@ -16,24 +18,31 @@ limitations under the License. */ /* -This file is part of Terraform (by Hashicorp) provider for Digital Energy Cloud Orchestration -Technology platfom. +Terraform DECORT provider - manage resources provided by DECORT (Digital Energy Cloud +Orchestration Technology) with Terraform by Hashicorp. -Visit https://github.com/rudecs/terraform-provider-decort for full source code package and updates. +Source code: https://github.com/rudecs/terraform-provider-decort + +Please see README.md to learn where to place source code so that it +builds seamlessly. + +Documentation: https://github.com/rudecs/terraform-provider-decort/wiki */ -package decort +package rg import ( + "context" "encoding/json" "fmt" + "github.com/rudecs/terraform-provider-decort/internal/constants" log "github.com/sirupsen/logrus" // "net/url" - "github.com/hashicorp/terraform-plugin-sdk/helper/schema" - // "github.com/hashicorp/terraform-plugin-sdk/helper/validation" + "github.com/hashicorp/terraform-plugin-sdk/v2/diag" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" ) func flattenResgroup(d *schema.ResourceData, rg_facts string) error { @@ -61,8 +70,8 @@ func flattenResgroup(d *schema.ResourceData, rg_facts string) error { d.Set("def_net_type", details.DefaultNetType) d.Set("def_net_id", details.DefaultNetID) /* - d.Set("vins", details.Vins) - d.Set("computes", details.Computes) + d.Set("vins", details.Vins) + d.Set("computes", details.Computes) */ log.Debugf("flattenResgroup: calling flattenQuota()") @@ -73,27 +82,27 @@ func flattenResgroup(d *schema.ResourceData, rg_facts string) error { return nil } -func dataSourceResgroupRead(d *schema.ResourceData, m interface{}) error { +func dataSourceResgroupRead(ctx context.Context, d *schema.ResourceData, m interface{}) diag.Diagnostics { rg_facts, err := utilityResgroupCheckPresence(d, m) if rg_facts == "" { // if empty string is returned from utilityResgroupCheckPresence then there is no // such resource group and err tells so - just return it to the calling party d.SetId("") // ensure ID is empty in this case - return err + return diag.FromErr(err) } - return flattenResgroup(d, rg_facts) + return diag.FromErr(flattenResgroup(d, rg_facts)) } -func dataSourceResgroup() *schema.Resource { +func DataSourceResgroup() *schema.Resource { return &schema.Resource{ SchemaVersion: 1, - Read: dataSourceResgroupRead, + ReadContext: dataSourceResgroupRead, Timeouts: &schema.ResourceTimeout{ - Read: &Timeout30s, - Default: &Timeout60s, + Read: &constants.Timeout30s, + Default: &constants.Timeout60s, }, Schema: map[string]*schema.Schema{ @@ -158,30 +167,30 @@ func dataSourceResgroup() *schema.Resource { }, /* - "status": { - Type: schema.TypeString, - Computed: true, - Description: "Current status of this resource group.", - }, + "status": { + Type: schema.TypeString, + Computed: true, + Description: "Current status of this resource group.", + }, - "vins": { - Type: schema.TypeList, // this is a list of ints - Computed: true, - MaxItems: LimitMaxVinsPerResgroup, - Elem: &schema.Schema{ - Type: schema.TypeInt, + "vins": { + Type: schema.TypeList, // this is a list of ints + Computed: true, + MaxItems: LimitMaxVinsPerResgroup, + Elem: &schema.Schema{ + Type: schema.TypeInt, + }, + Description: "List of VINs deployed in this resource group.", }, - Description: "List of VINs deployed in this resource group.", - }, - "computes": { - Type: schema.TypeList, //t his is a list of ints - Computed: true, - Elem: &schema.Schema{ - Type: schema.TypeInt, + "computes": { + Type: schema.TypeList, //t his is a list of ints + Computed: true, + Elem: &schema.Schema{ + Type: schema.TypeInt, + }, + Description: "List of computes deployed in this resource group.", }, - Description: "List of computes deployed in this resource group.", - }, */ }, } diff --git a/decort/data_source_rg_list.go b/internal/service/cloudapi/rg/data_source_rg_list.go similarity index 84% rename from decort/data_source_rg_list.go rename to internal/service/cloudapi/rg/data_source_rg_list.go index 73afce5..cfd71ba 100644 --- a/decort/data_source_rg_list.go +++ b/internal/service/cloudapi/rg/data_source_rg_list.go @@ -1,6 +1,8 @@ /* Copyright (c) 2019-2022 Digital Energy Cloud Solutions LLC. All Rights Reserved. -Author: Stanislav Solovev, +Authors: +Petr Krutov, +Stanislav Solovev, Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. @@ -16,17 +18,26 @@ limitations under the License. */ /* -This file is part of Terraform (by Hashicorp) provider for Digital Energy Cloud Orchestration -Technology platfom. +Terraform DECORT provider - manage resources provided by DECORT (Digital Energy Cloud +Orchestration Technology) with Terraform by Hashicorp. -Visit https://github.com/rudecs/terraform-provider-decort for full source code package and updates. +Source code: https://github.com/rudecs/terraform-provider-decort + +Please see README.md to learn where to place source code so that it +builds seamlessly. + +Documentation: https://github.com/rudecs/terraform-provider-decort/wiki */ -package decort +package rg import ( + "context" + "github.com/google/uuid" - "github.com/hashicorp/terraform-plugin-sdk/helper/schema" + "github.com/hashicorp/terraform-plugin-sdk/v2/diag" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" + "github.com/rudecs/terraform-provider-decort/internal/constants" ) func flattenRgList(rgl ResgroupListResp) []map[string]interface{} { @@ -96,10 +107,10 @@ func flattenRgResourceLimits(rl ResourceLimits) []map[string]interface{} { } -func dataSourceRgListRead(d *schema.ResourceData, m interface{}) error { +func dataSourceRgListRead(ctx context.Context, d *schema.ResourceData, m interface{}) diag.Diagnostics { rgList, err := utilityRgListCheckPresence(d, m) if err != nil { - return err + return diag.FromErr(err) } id := uuid.New() @@ -298,15 +309,15 @@ func dataSourceRgListSchemaMake() map[string]*schema.Schema { return res } -func dataSourceRgList() *schema.Resource { +func DataSourceRgList() *schema.Resource { return &schema.Resource{ SchemaVersion: 1, - Read: dataSourceRgListRead, + ReadContext: dataSourceRgListRead, Timeouts: &schema.ResourceTimeout{ - Read: &Timeout30s, - Default: &Timeout60s, + Read: &constants.Timeout30s, + Default: &constants.Timeout60s, }, Schema: dataSourceRgListSchemaMake(), diff --git a/internal/service/cloudapi/rg/models.go b/internal/service/cloudapi/rg/models.go new file mode 100644 index 0000000..f1f6e05 --- /dev/null +++ b/internal/service/cloudapi/rg/models.go @@ -0,0 +1,149 @@ +/* +Copyright (c) 2019-2022 Digital Energy Cloud Solutions LLC. All Rights Reserved. +Authors: +Petr Krutov, +Stanislav Solovev, + +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. +*/ + +/* +Terraform DECORT provider - manage resources provided by DECORT (Digital Energy Cloud +Orchestration Technology) with Terraform by Hashicorp. + +Source code: https://github.com/rudecs/terraform-provider-decort + +Please see README.md to learn where to place source code so that it +builds seamlessly. + +Documentation: https://github.com/rudecs/terraform-provider-decort/wiki +*/ + +package rg + +type ResourceLimits struct { + CUC float64 `json:"CU_C"` + CUD float64 `json:"CU_D"` + CUI float64 `json:"CU_I"` + CUM float64 `json:"CU_M"` + CUNP float64 `json:"CU_NP"` + GpuUnits float64 `json:"gpu_units"` +} + +type ResgroupRecord struct { + ACLs []AccountAclRecord `json:"acl"` + AccountID int `json:"accountId"` + AccountName string `json:"accountName"` + CreatedBy string `json:"createdBy"` + CreatedTime uint64 `json:"createdTime"` + DefaultNetID int `json:"def_net_id"` + DefaultNetType string `json:"def_net_type"` + DeletedBy string `json:"deletedBy"` + DeletedTime int `json:"deletedTime"` + Decsription string `json:"desc"` + GridID int `json:"gid"` + GUID int `json:"guid"` + ID uint `json:"id"` + LockStatus string `json:"lockStatus"` + Milestones int `json:"milestones"` + Name string `json:"name"` + RegisterComputes bool `json:"registerComputes"` + ResourceLimits ResourceLimits `json:"resourceLimits"` + Secret string `json:"secret"` + Status string `json:"status"` + UpdatedBy string `json:"updatedBy"` + UpdatedTime uint64 `json:"updatedTime"` + Vins []int `json:"vins"` + Computes []int `json:"vms"` +} + +type ResgroupListResp []ResgroupRecord + +type ResgroupUpdateParam struct { + RgId int `json:"rgId"` + Name string `json:"name"` + Desc string `json:"decs"` + Ram int `json:"maxMemoryCapacity"` + Disk int `json:"maxVDiskCapacity"` + Cpu int `json:"maxCPUCapacity"` + NetTraffic int `json:"maxNetworkPeerTransfer"` + Reason string `json:"reason"` +} + +type AccountAclRecord struct { + IsExplicit bool `json:"explicit"` + Guid string `json:"guid"` + Rights string `json:"right"` + Status string `json:"status"` + Type string `json:"type"` + UgroupID string `json:"userGroupId"` + CanBeDeleted bool `json:"canBeDeleted"` +} + +type ResgroupGetResp struct { + ACLs []UserAclRecord `json:"ACLs"` + Usage UsageRecord `json:"Resources"` + AccountID int `json:"accountId"` + AccountName string `json:"accountName"` + GridID int `json:"gid"` + CreatedBy string `json:"createdBy"` + CreatedTime uint64 `json:"createdTime"` + DefaultNetID int `json:"def_net_id"` + DefaultNetType string `json:"def_net_type"` + DeletedBy string `json:"deletedBy"` + DeletedTime uint64 `json:"deletedTime"` + Desc string `json:"desc"` + ID uint `json:"id"` + LockStatus string `json:"lockStatus"` + Name string `json:"name"` + Quota QuotaRecord `json:"resourceLimits"` + Status string `json:"status"` + UpdatedBy string `json:"updatedBy"` + UpdatedTime uint64 `json:"updatedTime"` + Vins []int `json:"vins"` + Computes []int `json:"vms"` + + Ignored map[string]interface{} `json:"-"` +} + +type UserAclRecord struct { + IsExplicit bool `json:"explicit"` + Rights string `json:"right"` + Status string `json:"status"` + Type string `json:"type"` + UgroupID string `json:"userGroupId"` + // CanBeDeleted bool `json:"canBeDeleted"` +} + +type QuotaRecord struct { // this is how quota is reported by /api/.../rg/get + Cpu int `json:"CU_C"` // CPU count in pcs + Ram float64 `json:"CU_M"` // RAM volume in MB, it is STILL reported as FLOAT + Disk int `json:"CU_D"` // Disk capacity in GB + ExtIPs int `json:"CU_I"` // Ext IPs count + ExtTraffic int `json:"CU_NP"` // Ext network traffic + GpuUnits int `json:"gpu_units"` // GPU count +} + +type ResourceRecord struct { // this is how actual usage is reported by /api/.../rg/get + Cpu int `json:"cpu"` + Disk int `json:"disksize"` + ExtIPs int `json:"extips"` + ExtTraffic int `json:"exttraffic"` + Gpu int `json:"gpu"` + Ram int `json:"ram"` +} + +type UsageRecord struct { + Current ResourceRecord `json:"Current"` + Reserved ResourceRecord `json:"Reserved"` +} diff --git a/decort/quota_subresource.go b/internal/service/cloudapi/rg/quota_subresource.go similarity index 84% rename from decort/quota_subresource.go rename to internal/service/cloudapi/rg/quota_subresource.go index f6e2fc1..6da4300 100644 --- a/decort/quota_subresource.go +++ b/internal/service/cloudapi/rg/quota_subresource.go @@ -1,6 +1,8 @@ /* -Copyright (c) 2019-2021 Digital Energy Cloud Solutions LLC. All Rights Reserved. -Author: Sergey Shubin, , +Copyright (c) 2019-2022 Digital Energy Cloud Solutions LLC. All Rights Reserved. +Authors: +Petr Krutov, +Stanislav Solovev, Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. @@ -15,17 +17,22 @@ See the License for the specific language governing permissions and limitations under the License. */ -package decort +/* +Terraform DECORT provider - manage resources provided by DECORT (Digital Energy Cloud +Orchestration Technology) with Terraform by Hashicorp. -import ( +Source code: https://github.com/rudecs/terraform-provider-decort + +Please see README.md to learn where to place source code so that it +builds seamlessly. - // "encoding/json" - // "fmt" - // "log" - // "net/url" +Documentation: https://github.com/rudecs/terraform-provider-decort/wiki +*/ + +package rg - "github.com/hashicorp/terraform-plugin-sdk/helper/schema" - // "github.com/hashicorp/terraform-plugin-sdk/helper/validation" +import ( + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" ) func makeQuotaRecord(arg_list []interface{}) QuotaRecord { diff --git a/decort/resource_rg.go b/internal/service/cloudapi/rg/resource_rg.go similarity index 79% rename from decort/resource_rg.go rename to internal/service/cloudapi/rg/resource_rg.go index cf5a9bc..815c427 100644 --- a/decort/resource_rg.go +++ b/internal/service/cloudapi/rg/resource_rg.go @@ -1,5 +1,8 @@ /* -Copyright (c) 2019-2021 Digital Energy Cloud Solutions. All Rights Reserved. +Copyright (c) 2019-2022 Digital Energy Cloud Solutions LLC. All Rights Reserved. +Authors: +Petr Krutov, +Stanislav Solovev, Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. @@ -7,7 +10,7 @@ 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 +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 @@ -15,26 +18,36 @@ limitations under the License. */ /* -This file is part of Terraform (by Hashicorp) provider for Digital Energy Cloud Orchestration -Technology platfom. +Terraform DECORT provider - manage resources provided by DECORT (Digital Energy Cloud +Orchestration Technology) with Terraform by Hashicorp. -Visit https://github.com/rudecs/terraform-provider-decort for full source code package and updates. +Source code: https://github.com/rudecs/terraform-provider-decort + +Please see README.md to learn where to place source code so that it +builds seamlessly. + +Documentation: https://github.com/rudecs/terraform-provider-decort/wiki */ -package decort +package rg import ( + "context" "encoding/json" "fmt" "net/url" + "github.com/rudecs/terraform-provider-decort/internal/constants" + "github.com/rudecs/terraform-provider-decort/internal/controller" + "github.com/rudecs/terraform-provider-decort/internal/location" log "github.com/sirupsen/logrus" - "github.com/hashicorp/terraform-plugin-sdk/helper/schema" - "github.com/hashicorp/terraform-plugin-sdk/helper/validation" + "github.com/hashicorp/terraform-plugin-sdk/v2/diag" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/validation" ) -func resourceResgroupCreate(d *schema.ResourceData, m interface{}) error { +func resourceResgroupCreate(ctx context.Context, d *schema.ResourceData, m interface{}) diag.Diagnostics { // First validate that we have all parameters required to create the new Resource Group // Valid account ID is required to create new resource group @@ -42,7 +55,7 @@ func resourceResgroupCreate(d *schema.ResourceData, m interface{}) error { rg_name, arg_set := d.GetOk("name") if !arg_set { - return fmt.Errorf("Cannot create new RG: missing name.") + return diag.FromErr(fmt.Errorf("Cannot create new RG: missing name.")) } /* Current version of provider works with default grid id (same is true for disk resources) @@ -70,16 +83,16 @@ func resourceResgroupCreate(d *schema.ResourceData, m interface{}) error { set_quota = true } - controller := m.(*ControllerCfg) + c := m.(*controller.ControllerCfg) log.Debugf("resourceResgroupCreate: called by user %q for RG name %s, account ID %d", - controller.getDecortUsername(), + c.GetDecortUsername(), rg_name.(string), d.Get("account_id").(int)) url_values := &url.Values{} url_values.Add("accountId", fmt.Sprintf("%d", d.Get("account_id").(int))) url_values.Add("name", rg_name.(string)) - url_values.Add("gid", fmt.Sprintf("%d", DefaultGridID)) // use default Grid ID, similar to disk resource mgmt convention - url_values.Add("owner", controller.getDecortUsername()) + url_values.Add("gid", fmt.Sprintf("%d", location.DefaultGridID)) // use default Grid ID, similar to disk resource mgmt convention + url_values.Add("owner", c.GetDecortUsername()) // pass quota values as set if set_quota { @@ -112,9 +125,9 @@ func resourceResgroupCreate(d *schema.ResourceData, m interface{}) error { url_values.Add("extIp", ext_ip.(string)) } - api_resp, err := controller.decortAPICall("POST", ResgroupCreateAPI, url_values) + api_resp, err := c.DecortAPICall("POST", ResgroupCreateAPI, url_values) if err != nil { - return err + return diag.FromErr(err) } d.SetId(api_resp) // rg/create API returns ID of the newly creted resource group on success @@ -122,22 +135,22 @@ func resourceResgroupCreate(d *schema.ResourceData, m interface{}) error { if !set_quota { resp, err := utilityResgroupCheckPresence(d, m) if err != nil { - return err + return diag.FromErr(err) } rg := ResgroupGetResp{} if err := json.Unmarshal([]byte(resp), &rg); err != nil { - return err + return diag.FromErr(err) } d.Set("quota", parseQuota(rg.Quota)) } // re-read newly created RG to make sure schema contains complete and up to date set of specifications - return resourceResgroupRead(d, m) + return resourceResgroupRead(ctx, d, m) } -func resourceResgroupRead(d *schema.ResourceData, m interface{}) error { +func resourceResgroupRead(ctx context.Context, d *schema.ResourceData, m interface{}) diag.Diagnostics { log.Debugf("resourceResgroupRead: called for RG name %s, account ID %d", d.Get("name").(string), d.Get("account_id").(int)) @@ -146,13 +159,13 @@ func resourceResgroupRead(d *schema.ResourceData, m interface{}) error { // if empty string is returned from utilityResgroupCheckPresence then there is no // such resource group and err tells so - just return it to the calling party d.SetId("") // ensure ID is empty - return err + return diag.FromErr(err) } - return flattenResgroup(d, rg_facts) + return diag.FromErr(flattenResgroup(d, rg_facts)) } -func resourceResgroupUpdate(d *schema.ResourceData, m interface{}) error { +func resourceResgroupUpdate(ctx context.Context, d *schema.ResourceData, m interface{}) diag.Diagnostics { log.Debugf("resourceResgroupUpdate: called for RG name %s, account ID %d", d.Get("name").(string), d.Get("account_id").(int)) @@ -167,18 +180,18 @@ func resourceResgroupUpdate(d *schema.ResourceData, m interface{}) error { for _, attr := range []string{"def_net_type", "ipcidr", "ext_ip"} { attr_new, attr_old := d.GetChange("def_net_type") if attr_new.(string) != attr_old.(string) { - return fmt.Errorf("resourceResgroupUpdate: RG ID %s: changing %s for existing RG is not allowed", d.Id(), attr) + return diag.FromErr(fmt.Errorf("resourceResgroupUpdate: RG ID %s: changing %s for existing RG is not allowed", d.Id(), attr)) } } attr_new, attr_old := d.GetChange("ext_net_id") if attr_new.(int) != attr_old.(int) { - return fmt.Errorf("resourceResgroupUpdate: RG ID %s: changing ext_net_id for existing RG is not allowed", d.Id()) + return diag.FromErr(fmt.Errorf("resourceResgroupUpdate: RG ID %s: changing ext_net_id for existing RG is not allowed", d.Id())) } do_general_update := false // will be true if general RG update is necessary (API rg/update) - controller := m.(*ControllerCfg) + c := m.(*controller.ControllerCfg) url_values := &url.Values{} url_values.Add("rgId", d.Id()) @@ -242,18 +255,18 @@ func resourceResgroupUpdate(d *schema.ResourceData, m interface{}) error { if do_general_update { log.Debugf("resourceResgroupUpdate: detected delta between new and old RG specs - updating the RG") - _, err := controller.decortAPICall("POST", ResgroupUpdateAPI, url_values) + _, err := c.DecortAPICall("POST", ResgroupUpdateAPI, url_values) if err != nil { - return err + return diag.FromErr(err) } } else { log.Debugf("resourceResgroupUpdate: no difference between old and new state - no update on the RG will be done") } - return resourceResgroupRead(d, m) + return resourceResgroupRead(ctx, d, m) } -func resourceResgroupDelete(d *schema.ResourceData, m interface{}) error { +func resourceResgroupDelete(ctx context.Context, d *schema.ResourceData, m interface{}) diag.Diagnostics { // NOTE: this method forcibly destroys target resource group with flag "permanently", so there is no way to // restore the destroyed resource group as well all Computes & VINSes that existed in it log.Debugf("resourceResgroupDelete: called for RG name %s, account ID %d", @@ -262,7 +275,7 @@ func resourceResgroupDelete(d *schema.ResourceData, m interface{}) error { rg_facts, err := utilityResgroupCheckPresence(d, m) if rg_facts == "" { if err != nil { - return err + return diag.FromErr(err) } // the target RG does not exist - in this case according to Terraform best practice // we exit from Destroy method without error @@ -275,10 +288,10 @@ func resourceResgroupDelete(d *schema.ResourceData, m interface{}) error { url_values.Add("permanently", "1") url_values.Add("reason", "Destroyed by DECORT Terraform provider") - controller := m.(*ControllerCfg) - _, err = controller.decortAPICall("POST", ResgroupDeleteAPI, url_values) + c := m.(*controller.ControllerCfg) + _, err = c.DecortAPICall("POST", ResgroupDeleteAPI, url_values) if err != nil { - return err + return diag.FromErr(err) } return nil @@ -296,26 +309,26 @@ func resourceResgroupExists(d *schema.ResourceData, m interface{}) (bool, error) return true, nil } -func resourceResgroup() *schema.Resource { +func ResourceResgroup() *schema.Resource { return &schema.Resource{ SchemaVersion: 1, - Create: resourceResgroupCreate, - Read: resourceResgroupRead, - Update: resourceResgroupUpdate, - Delete: resourceResgroupDelete, - Exists: resourceResgroupExists, + CreateContext: resourceResgroupCreate, + ReadContext: resourceResgroupRead, + UpdateContext: resourceResgroupUpdate, + DeleteContext: resourceResgroupDelete, + Exists: resourceResgroupExists, Importer: &schema.ResourceImporter{ State: schema.ImportStatePassthrough, }, Timeouts: &schema.ResourceTimeout{ - Create: &Timeout180s, - Read: &Timeout30s, - Update: &Timeout180s, - Delete: &Timeout60s, - Default: &Timeout60s, + Create: &constants.Timeout180s, + Read: &constants.Timeout30s, + Update: &constants.Timeout180s, + Delete: &constants.Timeout60s, + Default: &constants.Timeout60s, }, Schema: map[string]*schema.Schema{ diff --git a/decort/utility_rg.go b/internal/service/cloudapi/rg/utility_rg.go similarity index 80% rename from decort/utility_rg.go rename to internal/service/cloudapi/rg/utility_rg.go index 118c898..f2253e8 100644 --- a/decort/utility_rg.go +++ b/internal/service/cloudapi/rg/utility_rg.go @@ -1,6 +1,8 @@ /* -Copyright (c) 2019-2021 Digital Energy Cloud Solutions LLC. All Rights Reserved. -Author: Sergey Shubin, , +Copyright (c) 2019-2022 Digital Energy Cloud Solutions LLC. All Rights Reserved. +Authors: +Petr Krutov, +Stanislav Solovev, Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. @@ -16,13 +18,18 @@ limitations under the License. */ /* -This file is part of Terraform (by Hashicorp) provider for Digital Energy Cloud Orchestration -Technology platfom. +Terraform DECORT provider - manage resources provided by DECORT (Digital Energy Cloud +Orchestration Technology) with Terraform by Hashicorp. -Visit https://github.com/rudecs/terraform-provider-decort for full source code package and updates. +Source code: https://github.com/rudecs/terraform-provider-decort + +Please see README.md to learn where to place source code so that it +builds seamlessly. + +Documentation: https://github.com/rudecs/terraform-provider-decort/wiki */ -package decort +package rg import ( "encoding/json" @@ -30,10 +37,10 @@ import ( "net/url" "strconv" + "github.com/rudecs/terraform-provider-decort/internal/controller" log "github.com/sirupsen/logrus" - "github.com/hashicorp/terraform-plugin-sdk/helper/schema" - // "github.com/hashicorp/terraform-plugin-sdk/helper/validation" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" ) // On success this function returns a string, as returned by API rg/get, which could be unmarshalled @@ -56,7 +63,7 @@ func utilityResgroupCheckPresence(d *schema.ResourceData, m interface{}) (string // method for the Terraform resource Exists method. // - controller := m.(*ControllerCfg) + c := m.(*controller.ControllerCfg) urlValues := &url.Values{} // make it possible to use "read" & "check presence" functions with RG ID set so @@ -77,7 +84,7 @@ func utilityResgroupCheckPresence(d *schema.ResourceData, m interface{}) (string // go straight for the RG by its ID log.Debugf("utilityResgroupCheckPresence: locating RG by its ID %d", theId) urlValues.Add("rgId", fmt.Sprintf("%d", theId)) - rgFacts, err := controller.decortAPICall("POST", ResgroupGetAPI, urlValues) + rgFacts, err := c.DecortAPICall("POST", ResgroupGetAPI, urlValues) if err != nil { return "", err } @@ -94,7 +101,7 @@ func utilityResgroupCheckPresence(d *schema.ResourceData, m interface{}) (string // obtain Account ID by account name - it should not be zero on success urlValues.Add("includedeleted", "false") - apiResp, err := controller.decortAPICall("POST", ResgroupListAPI, urlValues) + apiResp, err := c.DecortAPICall("POST", ResgroupListAPI, urlValues) if err != nil { return "", err } @@ -118,7 +125,7 @@ func utilityResgroupCheckPresence(d *schema.ResourceData, m interface{}) (string // Namely, we need resource quota settings reqValues := &url.Values{} reqValues.Add("rgId", fmt.Sprintf("%d", item.ID)) - apiResp, err := controller.decortAPICall("POST", ResgroupGetAPI, reqValues) + apiResp, err := c.DecortAPICall("POST", ResgroupGetAPI, reqValues) if err != nil { return "", err } diff --git a/decort/utility_rg_list.go b/internal/service/cloudapi/rg/utility_rg_list.go similarity index 63% rename from decort/utility_rg_list.go rename to internal/service/cloudapi/rg/utility_rg_list.go index 78892f3..19a3b81 100644 --- a/decort/utility_rg_list.go +++ b/internal/service/cloudapi/rg/utility_rg_list.go @@ -1,6 +1,8 @@ /* Copyright (c) 2019-2022 Digital Energy Cloud Solutions LLC. All Rights Reserved. -Author: Stanislav Solovev, , +Authors: +Petr Krutov, +Stanislav Solovev, Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. @@ -16,26 +18,32 @@ limitations under the License. */ /* -This file is part of Terraform (by Hashicorp) provider for Digital Energy Cloud Orchestration -Technology platfom. +Terraform DECORT provider - manage resources provided by DECORT (Digital Energy Cloud +Orchestration Technology) with Terraform by Hashicorp. -Visit https://github.com/rudecs/terraform-provider-decort for full source code package and updates. +Source code: https://github.com/rudecs/terraform-provider-decort + +Please see README.md to learn where to place source code so that it +builds seamlessly. + +Documentation: https://github.com/rudecs/terraform-provider-decort/wiki */ -package decort +package rg import ( "encoding/json" "net/url" "strconv" + "github.com/rudecs/terraform-provider-decort/internal/controller" log "github.com/sirupsen/logrus" - "github.com/hashicorp/terraform-plugin-sdk/helper/schema" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" ) func utilityRgListCheckPresence(d *schema.ResourceData, m interface{}) (ResgroupListResp, error) { - controller := m.(*ControllerCfg) + c := m.(*controller.ControllerCfg) urlValues := &url.Values{} rgList := ResgroupListResp{} @@ -51,7 +59,7 @@ func utilityRgListCheckPresence(d *schema.ResourceData, m interface{}) (Resgroup } log.Debugf("utilityRgListCheckPresence: load rg list") - rgListRaw, err := controller.decortAPICall("POST", ResgroupListAPI, urlValues) + rgListRaw, err := c.DecortAPICall("POST", ResgroupListAPI, urlValues) if err != nil { return nil, err } diff --git a/internal/service/cloudapi/snapshot/api.go b/internal/service/cloudapi/snapshot/api.go new file mode 100644 index 0000000..9b8bdce --- /dev/null +++ b/internal/service/cloudapi/snapshot/api.go @@ -0,0 +1,37 @@ +/* +Copyright (c) 2019-2022 Digital Energy Cloud Solutions LLC. All Rights Reserved. +Authors: +Petr Krutov, +Stanislav Solovev, + +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. +*/ + +/* +Terraform DECORT provider - manage resources provided by DECORT (Digital Energy Cloud +Orchestration Technology) with Terraform by Hashicorp. + +Source code: https://github.com/rudecs/terraform-provider-decort + +Please see README.md to learn where to place source code so that it +builds seamlessly. + +Documentation: https://github.com/rudecs/terraform-provider-decort/wiki +*/ + +package snapshot + +const snapshotCreateAPI = "/restmachine/cloudapi/compute/snapshotCreate" +const snapshotDeleteAPI = "/restmachine/cloudapi/compute/snapshotDelete" +const snapshotRollbackAPI = "/restmachine/cloudapi/compute/snapshotRollback" +const snapshotListAPI = "/restmachine/cloudapi/compute/snapshotList" diff --git a/decort/data_source_snapshot_list.go b/internal/service/cloudapi/snapshot/data_source_snapshot_list.go similarity index 68% rename from decort/data_source_snapshot_list.go rename to internal/service/cloudapi/snapshot/data_source_snapshot_list.go index d6f2144..61a1cb5 100644 --- a/decort/data_source_snapshot_list.go +++ b/internal/service/cloudapi/snapshot/data_source_snapshot_list.go @@ -1,6 +1,8 @@ /* Copyright (c) 2019-2022 Digital Energy Cloud Solutions LLC. All Rights Reserved. -Author: Stanislav Solovev, , +Authors: +Petr Krutov, +Stanislav Solovev, Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. @@ -16,17 +18,26 @@ limitations under the License. */ /* -This file is part of Terraform (by Hashicorp) provider for Digital Energy Cloud Orchestration -Technology platfom. +Terraform DECORT provider - manage resources provided by DECORT (Digital Energy Cloud +Orchestration Technology) with Terraform by Hashicorp. -Visit https://github.com/rudecs/terraform-provider-decort for full source code package and updates. +Source code: https://github.com/rudecs/terraform-provider-decort + +Please see README.md to learn where to place source code so that it +builds seamlessly. + +Documentation: https://github.com/rudecs/terraform-provider-decort/wiki */ -package decort +package snapshot import ( + "context" + "github.com/google/uuid" - "github.com/hashicorp/terraform-plugin-sdk/helper/schema" + "github.com/hashicorp/terraform-plugin-sdk/v2/diag" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" + "github.com/rudecs/terraform-provider-decort/internal/constants" ) func flattenSnapshotList(gl SnapshotList) []map[string]interface{} { @@ -44,10 +55,10 @@ func flattenSnapshotList(gl SnapshotList) []map[string]interface{} { return res } -func dataSourceSnapshotListRead(d *schema.ResourceData, m interface{}) error { +func dataSourceSnapshotListRead(ctx context.Context, d *schema.ResourceData, m interface{}) diag.Diagnostics { snapshotList, err := utilitySnapshotListCheckPresence(d, m) if err != nil { - return err + return diag.FromErr(err) } id := uuid.New() d.SetId(id.String()) @@ -104,15 +115,15 @@ func dataSourceSnapshotSchemaMake() map[string]*schema.Schema { } } -func dataSourceSnapshotList() *schema.Resource { +func DataSourceSnapshotList() *schema.Resource { return &schema.Resource{ SchemaVersion: 1, - Read: dataSourceSnapshotListRead, + ReadContext: dataSourceSnapshotListRead, Timeouts: &schema.ResourceTimeout{ - Read: &Timeout30s, - Default: &Timeout60s, + Read: &constants.Timeout30s, + Default: &constants.Timeout60s, }, Schema: dataSourceSnapshotListSchemaMake(), diff --git a/internal/service/cloudapi/snapshot/models.go b/internal/service/cloudapi/snapshot/models.go new file mode 100644 index 0000000..0152191 --- /dev/null +++ b/internal/service/cloudapi/snapshot/models.go @@ -0,0 +1,41 @@ +/* +Copyright (c) 2019-2022 Digital Energy Cloud Solutions LLC. All Rights Reserved. +Authors: +Petr Krutov, +Stanislav Solovev, + +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. +*/ + +/* +Terraform DECORT provider - manage resources provided by DECORT (Digital Energy Cloud +Orchestration Technology) with Terraform by Hashicorp. + +Source code: https://github.com/rudecs/terraform-provider-decort + +Please see README.md to learn where to place source code so that it +builds seamlessly. + +Documentation: https://github.com/rudecs/terraform-provider-decort/wiki +*/ + +package snapshot + +type Snapshot struct { + Disks []int `json:"disks"` + Guid string `json:"guid"` + Label string `json:"label"` + Timestamp uint64 `json:"timestamp"` +} + +type SnapshotList []Snapshot diff --git a/decort/resource_snapshot.go b/internal/service/cloudapi/snapshot/resource_snapshot.go similarity index 56% rename from decort/resource_snapshot.go rename to internal/service/cloudapi/snapshot/resource_snapshot.go index 7a75867..b208092 100644 --- a/decort/resource_snapshot.go +++ b/internal/service/cloudapi/snapshot/resource_snapshot.go @@ -1,6 +1,8 @@ /* Copyright (c) 2019-2022 Digital Energy Cloud Solutions LLC. All Rights Reserved. -Author: Stanislav Solovev, +Authors: +Petr Krutov, +Stanislav Solovev, Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. @@ -16,35 +18,43 @@ limitations under the License. */ /* -This file is part of Terraform (by Hashicorp) provider for Digital Energy Cloud Orchestration -Technology platfom. +Terraform DECORT provider - manage resources provided by DECORT (Digital Energy Cloud +Orchestration Technology) with Terraform by Hashicorp. -Visit https://github.com/rudecs/terraform-provider-decort for full source code package and updates. +Source code: https://github.com/rudecs/terraform-provider-decort + +Please see README.md to learn where to place source code so that it +builds seamlessly. + +Documentation: https://github.com/rudecs/terraform-provider-decort/wiki */ -package decort +package snapshot import ( + "context" "net/url" "strconv" "strings" - "github.com/hashicorp/terraform-plugin-sdk/helper/customdiff" - "github.com/hashicorp/terraform-plugin-sdk/helper/schema" + "github.com/hashicorp/terraform-plugin-sdk/v2/diag" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" + "github.com/rudecs/terraform-provider-decort/internal/constants" + "github.com/rudecs/terraform-provider-decort/internal/controller" log "github.com/sirupsen/logrus" ) -func resourceSnapshotCreate(d *schema.ResourceData, m interface{}) error { +func resourceSnapshotCreate(ctx context.Context, d *schema.ResourceData, m interface{}) diag.Diagnostics { log.Debugf("resourceSnapshotCreate: called for snapshot %s", d.Get("label").(string)) - controller := m.(*ControllerCfg) + c := m.(*controller.ControllerCfg) urlValues := &url.Values{} urlValues.Add("label", d.Get("label").(string)) urlValues.Add("computeId", strconv.Itoa(d.Get("compute_id").(int))) - snapshotId, err := controller.decortAPICall("POST", snapshotCreateAPI, urlValues) + snapshotId, err := c.DecortAPICall("POST", snapshotCreateAPI, urlValues) if err != nil { - return err + return diag.FromErr(err) } snapshotId = strings.ReplaceAll(snapshotId, "\"", "") @@ -52,18 +62,18 @@ func resourceSnapshotCreate(d *schema.ResourceData, m interface{}) error { d.SetId(snapshotId) d.Set("guid", snapshotId) - err = resourceSnapshotRead(d, m) - if err != nil { - return err + diagnostics := resourceSnapshotRead(ctx, d, m) + if diagnostics != nil { + return diagnostics } return nil } -func resourceSnapshotRead(d *schema.ResourceData, m interface{}) error { +func resourceSnapshotRead(ctx context.Context, d *schema.ResourceData, m interface{}) diag.Diagnostics { snapshot, err := utilitySnapshotCheckPresence(d, m) if err != nil { - return err + return diag.FromErr(err) } d.Set("timestamp", snapshot.Timestamp) @@ -74,17 +84,17 @@ func resourceSnapshotRead(d *schema.ResourceData, m interface{}) error { return nil } -func resourceSnapshotDelete(d *schema.ResourceData, m interface{}) error { +func resourceSnapshotDelete(ctx context.Context, d *schema.ResourceData, m interface{}) diag.Diagnostics { log.Debugf("resourceSnapshotDelete: called for %s, id: %s", d.Get("label").(string), d.Id()) - controller := m.(*ControllerCfg) + c := m.(*controller.ControllerCfg) urlValues := &url.Values{} urlValues.Add("computeId", strconv.Itoa(d.Get("compute_id").(int))) urlValues.Add("label", d.Get("label").(string)) - _, err := controller.decortAPICall("POST", snapshotDeleteAPI, urlValues) + _, err := c.DecortAPICall("POST", snapshotDeleteAPI, urlValues) if err != nil { - return err + return diag.FromErr(err) } d.SetId("") @@ -103,23 +113,27 @@ func resourceSnapshotExists(d *schema.ResourceData, m interface{}) (bool, error) return true, nil } -func resourceSnapshotEdit(d *schema.ResourceData, m interface{}) error { - err := resourceSnapshotRead(d, m) - if err != nil { - return err +func resourceSnapshotEdit(ctx context.Context, d *schema.ResourceData, m interface{}) diag.Diagnostics { + if d.HasChange("rollback") { + if d.Get("rollback").(bool) { + err := resourceSnapshotRollback(d, m) + if err != nil { + return diag.FromErr(err) + } + } } return nil } -func resourceSnapshotRollback(d *schema.ResourceDiff, m interface{}) error { - c := m.(*ControllerCfg) +func resourceSnapshotRollback(d *schema.ResourceData, m interface{}) error { + c := m.(*controller.ControllerCfg) urlValues := &url.Values{} urlValues.Add("computeId", strconv.Itoa(d.Get("compute_id").(int))) urlValues.Add("label", d.Get("label").(string)) - _, err := c.decortAPICall("POST", snapshotRollbackAPI, urlValues) + _, err := c.DecortAPICall("POST", snapshotRollbackAPI, urlValues) if err != nil { return err } @@ -166,38 +180,28 @@ func resourceSnapshotSchemaMake() map[string]*schema.Schema { } } -func resourceSnapshot() *schema.Resource { +func ResourceSnapshot() *schema.Resource { return &schema.Resource{ SchemaVersion: 1, - Create: resourceSnapshotCreate, - Read: resourceSnapshotRead, - Update: resourceSnapshotEdit, - Delete: resourceSnapshotDelete, - Exists: resourceSnapshotExists, + CreateContext: resourceSnapshotCreate, + ReadContext: resourceSnapshotRead, + UpdateContext: resourceSnapshotEdit, + DeleteContext: resourceSnapshotDelete, + Exists: resourceSnapshotExists, Importer: &schema.ResourceImporter{ State: schema.ImportStatePassthrough, }, Timeouts: &schema.ResourceTimeout{ - Create: &Timeout60s, - Read: &Timeout30s, - Update: &Timeout60s, - Delete: &Timeout60s, - Default: &Timeout60s, + Create: &constants.Timeout60s, + Read: &constants.Timeout30s, + Update: &constants.Timeout60s, + Delete: &constants.Timeout60s, + Default: &constants.Timeout60s, }, - CustomizeDiff: customdiff.All( - customdiff.IfValueChange("rollback", func(old, new, meta interface{}) bool { - o := old.(bool) - if o != new.(bool) && !o { - return true - } - return false - }, resourceSnapshotRollback), - ), - Schema: resourceSnapshotSchemaMake(), } } diff --git a/decort/utility_snapshot.go b/internal/service/cloudapi/snapshot/utility_snapshot.go similarity index 63% rename from decort/utility_snapshot.go rename to internal/service/cloudapi/snapshot/utility_snapshot.go index 6e7abbc..e126a10 100644 --- a/decort/utility_snapshot.go +++ b/internal/service/cloudapi/snapshot/utility_snapshot.go @@ -1,6 +1,8 @@ /* Copyright (c) 2019-2022 Digital Energy Cloud Solutions LLC. All Rights Reserved. -Author: Stanislav Solovev, +Authors: +Petr Krutov, +Stanislav Solovev, Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. @@ -16,18 +18,23 @@ limitations under the License. */ /* -This file is part of Terraform (by Hashicorp) provider for Digital Energy Cloud Orchestration -Technology platfom. +Terraform DECORT provider - manage resources provided by DECORT (Digital Energy Cloud +Orchestration Technology) with Terraform by Hashicorp. -Visit https://github.com/rudecs/terraform-provider-decort for full source code package and updates. +Source code: https://github.com/rudecs/terraform-provider-decort + +Please see README.md to learn where to place source code so that it +builds seamlessly. + +Documentation: https://github.com/rudecs/terraform-provider-decort/wiki */ -package decort +package snapshot import ( "errors" - "github.com/hashicorp/terraform-plugin-sdk/helper/schema" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" ) func utilitySnapshotCheckPresence(d *schema.ResourceData, m interface{}) (*Snapshot, error) { diff --git a/decort/utility_snapshot_list.go b/internal/service/cloudapi/snapshot/utility_snapshot_list.go similarity index 58% rename from decort/utility_snapshot_list.go rename to internal/service/cloudapi/snapshot/utility_snapshot_list.go index 9171d23..4f80c90 100644 --- a/decort/utility_snapshot_list.go +++ b/internal/service/cloudapi/snapshot/utility_snapshot_list.go @@ -1,6 +1,8 @@ /* Copyright (c) 2019-2022 Digital Energy Cloud Solutions LLC. All Rights Reserved. -Author: Stanislav Solovev, +Authors: +Petr Krutov, +Stanislav Solovev, Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. @@ -16,28 +18,34 @@ limitations under the License. */ /* -This file is part of Terraform (by Hashicorp) provider for Digital Energy Cloud Orchestration -Technology platfom. +Terraform DECORT provider - manage resources provided by DECORT (Digital Energy Cloud +Orchestration Technology) with Terraform by Hashicorp. -Visit https://github.com/rudecs/terraform-provider-decort for full source code package and updates. +Source code: https://github.com/rudecs/terraform-provider-decort + +Please see README.md to learn where to place source code so that it +builds seamlessly. + +Documentation: https://github.com/rudecs/terraform-provider-decort/wiki */ -package decort +package snapshot import ( "encoding/json" "net/url" "strconv" - "github.com/hashicorp/terraform-plugin-sdk/helper/schema" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" + "github.com/rudecs/terraform-provider-decort/internal/controller" ) func utilitySnapshotListCheckPresence(d *schema.ResourceData, m interface{}) (SnapshotList, error) { - controller := m.(*ControllerCfg) + c := m.(*controller.ControllerCfg) urlValues := &url.Values{} urlValues.Add("computeId", strconv.Itoa(d.Get("compute_id").(int))) - resp, err := controller.decortAPICall("POST", snapshotListAPI, urlValues) + resp, err := c.DecortAPICall("POST", snapshotListAPI, urlValues) if err != nil { return nil, err } @@ -48,7 +56,7 @@ func utilitySnapshotListCheckPresence(d *schema.ResourceData, m interface{}) (Sn snapshotList := SnapshotList{} if err := json.Unmarshal([]byte(resp), &snapshotList); err != nil { - //return nil, errors.New(fmt.Sprint("Can not unmarshall data to snapshotList: ", resp, " ", snapshotList)) + return nil, err } diff --git a/internal/service/cloudapi/vgpu/api.go b/internal/service/cloudapi/vgpu/api.go new file mode 100644 index 0000000..ebd1104 --- /dev/null +++ b/internal/service/cloudapi/vgpu/api.go @@ -0,0 +1,34 @@ +/* +Copyright (c) 2019-2022 Digital Energy Cloud Solutions LLC. All Rights Reserved. +Authors: +Petr Krutov, +Stanislav Solovev, + +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. +*/ + +/* +Terraform DECORT provider - manage resources provided by DECORT (Digital Energy Cloud +Orchestration Technology) with Terraform by Hashicorp. + +Source code: https://github.com/rudecs/terraform-provider-decort + +Please see README.md to learn where to place source code so that it +builds seamlessly. + +Documentation: https://github.com/rudecs/terraform-provider-decort/wiki +*/ + +package vgpu + +const vgpuListAPI = "/restmachine/cloudbroker/vgpu/list" diff --git a/decort/data_source_vgpu.go b/internal/service/cloudapi/vgpu/data_source_vgpu.go similarity index 69% rename from decort/data_source_vgpu.go rename to internal/service/cloudapi/vgpu/data_source_vgpu.go index b1cf22b..0c66086 100644 --- a/decort/data_source_vgpu.go +++ b/internal/service/cloudapi/vgpu/data_source_vgpu.go @@ -1,6 +1,8 @@ /* Copyright (c) 2019-2022 Digital Energy Cloud Solutions LLC. All Rights Reserved. -Author: Petr Krutov, +Authors: +Petr Krutov, +Stanislav Solovev, Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. @@ -16,25 +18,32 @@ limitations under the License. */ /* -This file is part of Terraform (by Hashicorp) provider for Digital Energy Cloud Orchestration -Technology platfom. +Terraform DECORT provider - manage resources provided by DECORT (Digital Energy Cloud +Orchestration Technology) with Terraform by Hashicorp. -Visit https://github.com/rudecs/terraform-provider-decort for full source code package and updates. +Source code: https://github.com/rudecs/terraform-provider-decort + +Please see README.md to learn where to place source code so that it +builds seamlessly. + +Documentation: https://github.com/rudecs/terraform-provider-decort/wiki */ -package decort +package vgpu import ( + "context" "strconv" - "github.com/hashicorp/terraform-plugin-sdk/helper/schema" + "github.com/hashicorp/terraform-plugin-sdk/v2/diag" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" ) -func dataSourceVGPURead(d *schema.ResourceData, m interface{}) error { +func dataSourceVGPURead(ctx context.Context, d *schema.ResourceData, m interface{}) diag.Diagnostics { vgpu, err := utilityVGPUCheckPresence(d, m) if vgpu == nil { d.SetId("") - return err + return diag.FromErr(err) } d.SetId(strconv.Itoa(vgpu.ID)) @@ -100,11 +109,11 @@ func dataSourceVGPUSchemaMake() map[string]*schema.Schema { } } -func dataSourceVGPU() *schema.Resource { +func DataSourceVGPU() *schema.Resource { return &schema.Resource{ SchemaVersion: 1, - Read: dataSourceVGPURead, + ReadContext: dataSourceVGPURead, Schema: dataSourceVGPUSchemaMake(), } diff --git a/internal/service/cloudapi/vgpu/models.go b/internal/service/cloudapi/vgpu/models.go new file mode 100644 index 0000000..9f96f47 --- /dev/null +++ b/internal/service/cloudapi/vgpu/models.go @@ -0,0 +1,44 @@ +/* +Copyright (c) 2019-2022 Digital Energy Cloud Solutions LLC. All Rights Reserved. +Authors: +Petr Krutov, +Stanislav Solovev, + +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. +*/ + +/* +Terraform DECORT provider - manage resources provided by DECORT (Digital Energy Cloud +Orchestration Technology) with Terraform by Hashicorp. + +Source code: https://github.com/rudecs/terraform-provider-decort + +Please see README.md to learn where to place source code so that it +builds seamlessly. + +Documentation: https://github.com/rudecs/terraform-provider-decort/wiki +*/ + +package vgpu + +type VGPU struct { + AccountID int `json:"accountId"` + ID int `json:"id"` + Mode string `json:"mode"` + PgpuID int `json:"pgpuid"` + ProfileID int `json:"profileId"` + RAM int `json:"ram"` + Status string `json:"status"` + Type string `json:"type"` + VmID int `json:"vmid"` +} diff --git a/decort/utility_vgpu.go b/internal/service/cloudapi/vgpu/utility_vgpu.go similarity index 65% rename from decort/utility_vgpu.go rename to internal/service/cloudapi/vgpu/utility_vgpu.go index a35ca71..fd00ee4 100644 --- a/decort/utility_vgpu.go +++ b/internal/service/cloudapi/vgpu/utility_vgpu.go @@ -1,6 +1,8 @@ /* Copyright (c) 2019-2022 Digital Energy Cloud Solutions LLC. All Rights Reserved. -Author: Petr Krutov, +Authors: +Petr Krutov, +Stanislav Solovev, Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. @@ -16,24 +18,30 @@ limitations under the License. */ /* -This file is part of Terraform (by Hashicorp) provider for Digital Energy Cloud Orchestration -Technology platfom. +Terraform DECORT provider - manage resources provided by DECORT (Digital Energy Cloud +Orchestration Technology) with Terraform by Hashicorp. -Visit https://github.com/rudecs/terraform-provider-decort for full source code package and updates. +Source code: https://github.com/rudecs/terraform-provider-decort + +Please see README.md to learn where to place source code so that it +builds seamlessly. + +Documentation: https://github.com/rudecs/terraform-provider-decort/wiki */ -package decort +package vgpu import ( "encoding/json" "net/url" "strconv" - "github.com/hashicorp/terraform-plugin-sdk/helper/schema" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" + "github.com/rudecs/terraform-provider-decort/internal/controller" ) func utilityVGPUCheckPresence(d *schema.ResourceData, m interface{}) (*VGPU, error) { - controller := m.(*ControllerCfg) + c := m.(*controller.ControllerCfg) urlValues := &url.Values{} urlValues.Add("size", "50") @@ -51,7 +59,7 @@ func utilityVGPUCheckPresence(d *schema.ResourceData, m interface{}) (*VGPU, err for page := 1; ; page++ { urlValues.Set("page", strconv.Itoa(page)) - resp, err := controller.decortAPICall("POST", vgpuListAPI, urlValues) + resp, err := c.DecortAPICall("POST", vgpuListAPI, urlValues) if err != nil { return nil, err } diff --git a/internal/service/cloudapi/vins/api.go b/internal/service/cloudapi/vins/api.go new file mode 100644 index 0000000..4a21e3e --- /dev/null +++ b/internal/service/cloudapi/vins/api.go @@ -0,0 +1,44 @@ +/* +Copyright (c) 2019-2022 Digital Energy Cloud Solutions LLC. All Rights Reserved. +Authors: +Petr Krutov, +Stanislav Solovev, + +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. +*/ + +/* +Terraform DECORT provider - manage resources provided by DECORT (Digital Energy Cloud +Orchestration Technology) with Terraform by Hashicorp. + +Source code: https://github.com/rudecs/terraform-provider-decort + +Please see README.md to learn where to place source code so that it +builds seamlessly. + +Documentation: https://github.com/rudecs/terraform-provider-decort/wiki +*/ + +package vins + +const VinsListAPI = "/restmachine/cloudapi/vins/list" +const VinsGetAPI = "/restmachine/cloudapi/vins/get" +const VinsSearchAPI = "/restmachine/cloudapi/vins/search" + +const VinsCreateInAccountAPI = "/restmachine/cloudapi/vins/createInAccount" +const VinsCreateInRgAPI = "/restmachine/cloudapi/vins/createInRG" + +const VinsExtNetConnectAPI = "/restmachine/cloudapi/vins/extNetConnect" +const VinsExtNetDisconnectAPI = "/restmachine/cloudapi/vins/extNetDisconnect" + +const VinsDeleteAPI = "/restmachine/cloudapi/vins/delete" diff --git a/decort/data_source_vins.go b/internal/service/cloudapi/vins/data_source_vins.go similarity index 78% rename from decort/data_source_vins.go rename to internal/service/cloudapi/vins/data_source_vins.go index 61fd3c5..b6419b7 100644 --- a/decort/data_source_vins.go +++ b/internal/service/cloudapi/vins/data_source_vins.go @@ -1,6 +1,8 @@ /* -Copyright (c) 2020-2021 Digital Energy Cloud Solutions LLC. All Rights Reserved. -Author: Sergey Shubin, , +Copyright (c) 2019-2022 Digital Energy Cloud Solutions LLC. All Rights Reserved. +Authors: +Petr Krutov, +Stanislav Solovev, Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. @@ -16,35 +18,43 @@ limitations under the License. */ /* -This file is part of Terraform (by Hashicorp) provider for Digital Energy Cloud Orchestration -Technology platfom. +Terraform DECORT provider - manage resources provided by DECORT (Digital Energy Cloud +Orchestration Technology) with Terraform by Hashicorp. -Visit https://github.com/rudecs/terraform-provider-decort for full source code package and updates. +Source code: https://github.com/rudecs/terraform-provider-decort + +Please see README.md to learn where to place source code so that it +builds seamlessly. + +Documentation: https://github.com/rudecs/terraform-provider-decort/wiki */ -package decort +package vins import ( + "context" "encoding/json" "fmt" + "github.com/rudecs/terraform-provider-decort/internal/constants" log "github.com/sirupsen/logrus" // "net/url" - "github.com/hashicorp/terraform-plugin-sdk/helper/schema" + "github.com/hashicorp/terraform-plugin-sdk/v2/diag" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" // "github.com/hashicorp/terraform-plugin-sdk/helper/validation" ) // vins_facts is a response string from API vins/get -func flattenVins(d *schema.ResourceData, vins_facts string) error { +func flattenVins(d *schema.ResourceData, vins_facts string) diag.Diagnostics { // NOTE: this function modifies ResourceData argument - as such it should never be called // from resourceVinsExists(...) method // log.Debugf("flattenVins: ready to decode response body from API %s", vins_facts) vinsRecord := VinsRecord{} err := json.Unmarshal([]byte(vins_facts), &vinsRecord) if err != nil { - return err + return diag.FromErr(err) } log.Debugf("flattenVins: decoded ViNS name:ID %s:%d, account ID %d, RG ID %d", @@ -69,7 +79,7 @@ func flattenVins(d *schema.ResourceData, vins_facts string) error { d.Set("ext_ip_addr", extNetIP.(string)) d.Set("ext_net_id", int(extNetID.(float64))) } else { - return fmt.Errorf("Failed to unmarshal VNF GW Config - structure is invalid.") + return diag.Errorf("Failed to unmarshal VNF GW Config - structure is invalid.") } noExtNetConnection = false break @@ -86,27 +96,27 @@ func flattenVins(d *schema.ResourceData, vins_facts string) error { return nil } -func dataSourceVinsRead(d *schema.ResourceData, m interface{}) error { +func dataSourceVinsRead(ctx context.Context, d *schema.ResourceData, m interface{}) diag.Diagnostics { vinsFacts, err := utilityVinsCheckPresence(d, m) if vinsFacts == "" { // if empty string is returned from utilityVinsCheckPresence then there is no // such ViNS and err tells so - just return it to the calling party d.SetId("") // ensure ID is empty in this case - return err + return diag.FromErr(err) } return flattenVins(d, vinsFacts) } -func dataSourceVins() *schema.Resource { +func DataSourceVins() *schema.Resource { return &schema.Resource{ SchemaVersion: 1, - Read: dataSourceVinsRead, + ReadContext: dataSourceVinsRead, Timeouts: &schema.ResourceTimeout{ - Read: &Timeout30s, - Default: &Timeout60s, + Read: &constants.Timeout30s, + Default: &constants.Timeout60s, }, Schema: map[string]*schema.Schema{ diff --git a/decort/data_source_vins_list.go b/internal/service/cloudapi/vins/data_source_vins_list.go similarity index 75% rename from decort/data_source_vins_list.go rename to internal/service/cloudapi/vins/data_source_vins_list.go index 84a2c0b..76365db 100644 --- a/decort/data_source_vins_list.go +++ b/internal/service/cloudapi/vins/data_source_vins_list.go @@ -1,6 +1,8 @@ /* Copyright (c) 2019-2022 Digital Energy Cloud Solutions LLC. All Rights Reserved. -Author: Stanislav Solovev, +Authors: +Petr Krutov, +Stanislav Solovev, Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. @@ -16,17 +18,26 @@ limitations under the License. */ /* -This file is part of Terraform (by Hashicorp) provider for Digital Energy Cloud Orchestration -Technology platfom. +Terraform DECORT provider - manage resources provided by DECORT (Digital Energy Cloud +Orchestration Technology) with Terraform by Hashicorp. -Visit https://github.com/rudecs/terraform-provider-decort for full source code package and updates. +Source code: https://github.com/rudecs/terraform-provider-decort + +Please see README.md to learn where to place source code so that it +builds seamlessly. + +Documentation: https://github.com/rudecs/terraform-provider-decort/wiki */ -package decort +package vins import ( + "context" + "github.com/google/uuid" - "github.com/hashicorp/terraform-plugin-sdk/helper/schema" + "github.com/hashicorp/terraform-plugin-sdk/v2/diag" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" + "github.com/rudecs/terraform-provider-decort/internal/constants" ) func flattenVinsList(vl VinsList) []map[string]interface{} { @@ -55,10 +66,10 @@ func flattenVinsList(vl VinsList) []map[string]interface{} { return res } -func dataSourceVinsListRead(d *schema.ResourceData, m interface{}) error { +func dataSourceVinsListRead(ctx context.Context, d *schema.ResourceData, m interface{}) diag.Diagnostics { vinsList, err := utilityVinsListCheckPresence(d, m) if err != nil { - return err + return diag.FromErr(err) } id := uuid.New() @@ -162,15 +173,15 @@ func dataSourceVinsListSchemaMake() map[string]*schema.Schema { return res } -func dataSourceVinsList() *schema.Resource { +func DataSourceVinsList() *schema.Resource { return &schema.Resource{ SchemaVersion: 1, - Read: dataSourceVinsListRead, + ReadContext: dataSourceVinsListRead, Timeouts: &schema.ResourceTimeout{ - Read: &Timeout30s, - Default: &Timeout60s, + Read: &constants.Timeout30s, + Default: &constants.Timeout60s, }, Schema: dataSourceVinsListSchemaMake(), diff --git a/internal/service/cloudapi/vins/models.go b/internal/service/cloudapi/vins/models.go new file mode 100644 index 0000000..e8b95d1 --- /dev/null +++ b/internal/service/cloudapi/vins/models.go @@ -0,0 +1,94 @@ +/* +Copyright (c) 2019-2022 Digital Energy Cloud Solutions LLC. All Rights Reserved. +Authors: +Petr Krutov, +Stanislav Solovev, + +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. +*/ + +/* +Terraform DECORT provider - manage resources provided by DECORT (Digital Energy Cloud +Orchestration Technology) with Terraform by Hashicorp. + +Source code: https://github.com/rudecs/terraform-provider-decort + +Please see README.md to learn where to place source code so that it +builds seamlessly. + +Documentation: https://github.com/rudecs/terraform-provider-decort/wiki +*/ + +package vins + +type Vins struct { + AccountId int `json:"accountId"` + AccountName string `json:"accountName"` + CreatedBy string `json:"createdBy"` + CreatedTime int `json:"createdTime"` + DeletedBy string `json:"deletedBy"` + DeletedTime int `json:"deletedTime"` + ExternalIP string `json:"externalIP"` + ID int `json:"id"` + Name string `json:"name"` + Network string `json:"network"` + RGID int `json:"rgId"` + RGName string `json:"rgName"` + Status string `json:"status"` + UpdatedBy string `json:"updatedBy"` + UpdatedTime int `json:"updatedTime"` + VXLanID int `json:"vxlanId"` +} + +type VinsList []Vins + +type VinsSearchResp []VinsSearchRecord + +type VnfRecord struct { + ID int `json:"id"` + AccountID int `json:"accountId"` + Type string `json:"type"` // "DHCP", "NAT", "GW" etc + Config map[string]interface{} `json:"config"` // NOTE: VNF specs vary by VNF type +} + +type VnfGwConfigRecord struct { // describes GW VNF config structure inside ViNS, as returned by API vins/get + ExtNetID int `json:"ext_net_id"` + ExtNetIP string `json:"ext_net_ip"` + ExtNetMask int `json:"ext_net_mask"` + DefaultGW string `json:"default_gw"` +} +type VinsRecord struct { // represents part of the response from API vins/get + ID int `json:"id"` + Name string `json:"name"` + IPCidr string `json:"network"` + VxLanID int `json:"vxlanId"` + ExternalIP string `json:"externalIP"` + AccountID int `json:"accountId"` + AccountName string `json:"accountName"` + RgID int `json:"rgid"` + RgName string `json:"rgName"` + VNFs map[string]VnfRecord `json:"vnfs"` + Desc string `json:"desc"` +} + +type VinsSearchRecord struct { + ID int `json:"id"` + Name string `json:"name"` + IPCidr string `json:"network"` + VxLanID int `json:"vxlanId"` + ExternalIP string `json:"externalIP"` + AccountID int `json:"accountId"` + AccountName string `json:"accountName"` + RgID int `json:"rgId"` + RgName string `json:"rgName"` +} diff --git a/decort/resource_vins.go b/internal/service/cloudapi/vins/resource_vins.go similarity index 78% rename from decort/resource_vins.go rename to internal/service/cloudapi/vins/resource_vins.go index cdfb5f6..fc0170d 100644 --- a/decort/resource_vins.go +++ b/internal/service/cloudapi/vins/resource_vins.go @@ -1,6 +1,8 @@ /* -Copyright (c) 2019-2021 Digital Energy Cloud Solutions LLC. All Rights Reserved. -Author: Sergey Shubin, , +Copyright (c) 2019-2022 Digital Energy Cloud Solutions LLC. All Rights Reserved. +Authors: +Petr Krutov, +Stanislav Solovev, Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. @@ -16,25 +18,32 @@ limitations under the License. */ /* -This file is part of Terraform (by Hashicorp) provider for Digital Energy Cloud Orchestration -Technology platfom. +Terraform DECORT provider - manage resources provided by DECORT (Digital Energy Cloud +Orchestration Technology) with Terraform by Hashicorp. -Visit https://github.com/rudecs/terraform-provider-decort for full source code package and updates. +Source code: https://github.com/rudecs/terraform-provider-decort + +Please see README.md to learn where to place source code so that it +builds seamlessly. + +Documentation: https://github.com/rudecs/terraform-provider-decort/wiki */ -package decort +package vins import ( - // "encoding/json" + "context" "fmt" "net/url" "strconv" + "github.com/rudecs/terraform-provider-decort/internal/constants" + "github.com/rudecs/terraform-provider-decort/internal/controller" log "github.com/sirupsen/logrus" - "github.com/hashicorp/terraform-plugin-sdk/helper/schema" - "github.com/hashicorp/terraform-plugin-sdk/helper/validation" - // "github.com/hashicorp/terraform-plugin-sdk/helper/validation" + "github.com/hashicorp/terraform-plugin-sdk/v2/diag" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/validation" ) func ipcidrDiffSupperss(key, oldVal, newVal string, d *schema.ResourceData) bool { @@ -49,13 +58,13 @@ func ipcidrDiffSupperss(key, oldVal, newVal string, d *schema.ResourceData) bool return true // suppress difference } -func resourceVinsCreate(d *schema.ResourceData, m interface{}) error { +func resourceVinsCreate(ctx context.Context, d *schema.ResourceData, m interface{}) diag.Diagnostics { log.Debugf("resourceVinsCreate: called for ViNS name %s, Account ID %d, RG ID %d", d.Get("name").(string), d.Get("account_id").(int), d.Get("rg_id").(int)) apiToCall := VinsCreateInAccountAPI - controller := m.(*ControllerCfg) + c := m.(*controller.ControllerCfg) urlValues := &url.Values{} urlValues.Add("name", d.Get("name").(string)) @@ -69,7 +78,7 @@ func resourceVinsCreate(d *schema.ResourceData, m interface{}) error { argVal, argSet = d.GetOk("account_id") if !argSet || argVal.(int) <= 0 { // No valid Account ID (and no RG ID either) - cannot create ViNS - return fmt.Errorf("resourceVinsCreate: ViNS name %s - no valid account and/or resource group ID specified", d.Id()) + return diag.Errorf("resourceVinsCreate: ViNS name %s - no valid account and/or resource group ID specified", d.Id()) } urlValues.Add("accountId", fmt.Sprintf("%d", argVal.(int))) } @@ -106,9 +115,9 @@ func resourceVinsCreate(d *schema.ResourceData, m interface{}) error { urlValues.Add("desc", argVal.(string)) } - apiResp, err := controller.decortAPICall("POST", apiToCall, urlValues) + apiResp, err := c.DecortAPICall("POST", apiToCall, urlValues) if err != nil { - return err + return diag.FromErr(err) } d.SetId(apiResp) // update ID of the resource to tell Terraform that the ViNS resource exists @@ -120,29 +129,27 @@ func resourceVinsCreate(d *schema.ResourceData, m interface{}) error { // between ViNS resource and ViNS data source schemas // ViNS resource read function will also update resource ID on success, so that Terraform // will know the resource exists (however, we already did it a few lines before) - return dataSourceVinsRead(d, m) + return dataSourceVinsRead(ctx, d, m) } -func resourceVinsRead(d *schema.ResourceData, m interface{}) error { +func resourceVinsRead(ctx context.Context, d *schema.ResourceData, m interface{}) diag.Diagnostics { vinsFacts, err := utilityVinsCheckPresence(d, m) if vinsFacts == "" { // if empty string is returned from utilityVinsCheckPresence then there is no // such ViNS and err tells so - just return it to the calling party d.SetId("") // ensure ID is empty - return err + return diag.FromErr(err) } return flattenVins(d, vinsFacts) } -func resourceVinsUpdate(d *schema.ResourceData, m interface{}) error { +func resourceVinsUpdate(ctx context.Context, d *schema.ResourceData, m interface{}) diag.Diagnostics { log.Debugf("resourceVinsUpdate: called for ViNS ID / name %s / %s, Account ID %d, RG ID %d", d.Id(), d.Get("name").(string), d.Get("account_id").(int), d.Get("rg_id").(int)) - controller := m.(*ControllerCfg) - - d.Partial(true) + c := m.(*controller.ControllerCfg) // 1. Handle external network connection change oldExtNetId, newExtNedId := d.GetChange("ext_net_id") @@ -154,39 +161,35 @@ func resourceVinsUpdate(d *schema.ResourceData, m interface{}) error { if oldExtNetId.(int) > 0 { // there was preexisting external net connection - disconnect ViNS - _, err := controller.decortAPICall("POST", VinsExtNetDisconnectAPI, extnetParams) + _, err := c.DecortAPICall("POST", VinsExtNetDisconnectAPI, extnetParams) if err != nil { - return err + return diag.FromErr(err) } } if newExtNedId.(int) > 0 { // new external network connection requested - connect ViNS extnetParams.Add("netId", fmt.Sprintf("%d", newExtNedId.(int))) - _, err := controller.decortAPICall("POST", VinsExtNetConnectAPI, extnetParams) + _, err := c.DecortAPICall("POST", VinsExtNetConnectAPI, extnetParams) if err != nil { - return err + return diag.FromErr(err) } } - - d.SetPartial("ext_net_id") } - d.Partial(false) - // we may reuse dataSourceVinsRead here as we maintain similarity // between Compute resource and Compute data source schemas - return dataSourceVinsRead(d, m) + return dataSourceVinsRead(ctx, d, m) } -func resourceVinsDelete(d *schema.ResourceData, m interface{}) error { +func resourceVinsDelete(ctx context.Context, d *schema.ResourceData, m interface{}) diag.Diagnostics { log.Debugf("resourceVinsDelete: called for ViNS ID / name %s / %s, Account ID %d, RG ID %d", d.Id(), d.Get("name").(string), d.Get("account_id").(int), d.Get("rg_id").(int)) vinsFacts, err := utilityVinsCheckPresence(d, m) if vinsFacts == "" { if err != nil { - return err + return diag.FromErr(err) } // the specified ViNS does not exist - in this case according to Terraform best practice // we exit from Destroy method without error @@ -198,10 +201,10 @@ func resourceVinsDelete(d *schema.ResourceData, m interface{}) error { params.Add("force", "1") // disconnect all computes before deleting ViNS params.Add("permanently", "1") // delete ViNS immediately bypassing recycle bin - controller := m.(*ControllerCfg) - _, err = controller.decortAPICall("POST", VinsDeleteAPI, params) + c := m.(*controller.ControllerCfg) + _, err = c.DecortAPICall("POST", VinsDeleteAPI, params) if err != nil { - return err + return diag.FromErr(err) } return nil @@ -294,26 +297,26 @@ func resourceVinsSchemaMake() map[string]*schema.Schema { return rets } -func resourceVins() *schema.Resource { +func ResourceVins() *schema.Resource { return &schema.Resource{ SchemaVersion: 1, - Create: resourceVinsCreate, - Read: resourceVinsRead, - Update: resourceVinsUpdate, - Delete: resourceVinsDelete, - Exists: resourceVinsExists, + CreateContext: resourceVinsCreate, + ReadContext: resourceVinsRead, + UpdateContext: resourceVinsUpdate, + DeleteContext: resourceVinsDelete, + Exists: resourceVinsExists, Importer: &schema.ResourceImporter{ State: schema.ImportStatePassthrough, }, Timeouts: &schema.ResourceTimeout{ - Create: &Timeout180s, - Read: &Timeout30s, - Update: &Timeout180s, - Delete: &Timeout60s, - Default: &Timeout60s, + Create: &constants.Timeout180s, + Read: &constants.Timeout30s, + Update: &constants.Timeout180s, + Delete: &constants.Timeout60s, + Default: &constants.Timeout60s, }, Schema: resourceVinsSchemaMake(), diff --git a/decort/utility_vins.go b/internal/service/cloudapi/vins/utility_vins.go similarity index 82% rename from decort/utility_vins.go rename to internal/service/cloudapi/vins/utility_vins.go index 03a410c..c8e363b 100644 --- a/decort/utility_vins.go +++ b/internal/service/cloudapi/vins/utility_vins.go @@ -1,6 +1,8 @@ /* -Copyright (c) 2020-2021 Digital Energy Cloud Solutions LLC. All Rights Reserved. -Author: Sergey Shubin, , +Copyright (c) 2019-2022 Digital Energy Cloud Solutions LLC. All Rights Reserved. +Authors: +Petr Krutov, +Stanislav Solovev, Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. @@ -16,13 +18,18 @@ limitations under the License. */ /* -This file is part of Terraform (by Hashicorp) provider for Digital Energy Cloud Orchestration -Technology platfom. +Terraform DECORT provider - manage resources provided by DECORT (Digital Energy Cloud +Orchestration Technology) with Terraform by Hashicorp. -Visit https://github.com/rudecs/terraform-provider-decort for full source code package and updates. +Source code: https://github.com/rudecs/terraform-provider-decort + +Please see README.md to learn where to place source code so that it +builds seamlessly. + +Documentation: https://github.com/rudecs/terraform-provider-decort/wiki */ -package decort +package vins import ( "encoding/json" @@ -30,9 +37,10 @@ import ( "net/url" "strconv" + "github.com/rudecs/terraform-provider-decort/internal/controller" log "github.com/sirupsen/logrus" - "github.com/hashicorp/terraform-plugin-sdk/helper/schema" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" ) // On success this function returns a string, as returned by API vins/get, which could be unmarshalled @@ -51,7 +59,7 @@ func utilityVinsCheckPresence(d *schema.ResourceData, m interface{}) (string, er // method for the Terraform resource Exists method. // - controller := m.(*ControllerCfg) + c := m.(*controller.ControllerCfg) urlValues := &url.Values{} // make it possible to use "read" & "check presence" functions with ViNS ID set so @@ -72,7 +80,7 @@ func utilityVinsCheckPresence(d *schema.ResourceData, m interface{}) (string, er // ViNS ID is specified, try to get compute instance straight by this ID log.Debugf("utilityVinsCheckPresence: locating ViNS by its ID %d", theId) urlValues.Add("vinsId", fmt.Sprintf("%d", theId)) - vinsFacts, err := controller.decortAPICall("POST", VinsGetAPI, urlValues) + vinsFacts, err := c.DecortAPICall("POST", VinsGetAPI, urlValues) if err != nil { return "", err } @@ -103,7 +111,7 @@ func utilityVinsCheckPresence(d *schema.ResourceData, m interface{}) (string, er urlValues.Add("accountId", fmt.Sprintf("%d", accountId.(int))) } - apiResp, err := controller.decortAPICall("POST", VinsSearchAPI, urlValues) + apiResp, err := c.DecortAPICall("POST", VinsSearchAPI, urlValues) if err != nil { return "", err } @@ -132,7 +140,7 @@ func utilityVinsCheckPresence(d *schema.ResourceData, m interface{}) (string, er // manage ViNS, so we have to get detailed info by calling API vins/get rqValues := &url.Values{} rqValues.Add("vinsId", fmt.Sprintf("%d", item.ID)) - vinsGetResp, err := controller.decortAPICall("POST", VinsGetAPI, rqValues) + vinsGetResp, err := c.DecortAPICall("POST", VinsGetAPI, rqValues) if err != nil { return "", err } diff --git a/decort/utility_vins_list.go b/internal/service/cloudapi/vins/utility_vins_list.go similarity index 63% rename from decort/utility_vins_list.go rename to internal/service/cloudapi/vins/utility_vins_list.go index 7bdf083..c886c68 100644 --- a/decort/utility_vins_list.go +++ b/internal/service/cloudapi/vins/utility_vins_list.go @@ -1,6 +1,8 @@ /* Copyright (c) 2019-2022 Digital Energy Cloud Solutions LLC. All Rights Reserved. -Author: Stanislav Solovev, , +Authors: +Petr Krutov, +Stanislav Solovev, Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. @@ -16,27 +18,33 @@ limitations under the License. */ /* -This file is part of Terraform (by Hashicorp) provider for Digital Energy Cloud Orchestration -Technology platfom. +Terraform DECORT provider - manage resources provided by DECORT (Digital Energy Cloud +Orchestration Technology) with Terraform by Hashicorp. -Visit https://github.com/rudecs/terraform-provider-decort for full source code package and updates. +Source code: https://github.com/rudecs/terraform-provider-decort + +Please see README.md to learn where to place source code so that it +builds seamlessly. + +Documentation: https://github.com/rudecs/terraform-provider-decort/wiki */ -package decort +package vins import ( "encoding/json" "net/url" "strconv" + "github.com/rudecs/terraform-provider-decort/internal/controller" log "github.com/sirupsen/logrus" - "github.com/hashicorp/terraform-plugin-sdk/helper/schema" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" ) func utilityVinsListCheckPresence(d *schema.ResourceData, m interface{}) (VinsList, error) { vinsList := VinsList{} - controller := m.(*ControllerCfg) + c := m.(*controller.ControllerCfg) urlValues := &url.Values{} if includeDeleted, ok := d.GetOk("include_deleted"); ok { @@ -50,7 +58,7 @@ func utilityVinsListCheckPresence(d *schema.ResourceData, m interface{}) (VinsLi } log.Debugf("utilityVinsListCheckPresence") - vinsListRaw, err := controller.decortAPICall("POST", vinsListAPI, urlValues) + vinsListRaw, err := c.DecortAPICall("POST", VinsListAPI, urlValues) if err != nil { return nil, err } diff --git a/internal/service/cloudbroker/grid/api.go b/internal/service/cloudbroker/grid/api.go new file mode 100644 index 0000000..9efebd9 --- /dev/null +++ b/internal/service/cloudbroker/grid/api.go @@ -0,0 +1,35 @@ +/* +Copyright (c) 2019-2022 Digital Energy Cloud Solutions LLC. All Rights Reserved. +Authors: +Petr Krutov, +Stanislav Solovev, + +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. +*/ + +/* +Terraform DECORT provider - manage resources provided by DECORT (Digital Energy Cloud +Orchestration Technology) with Terraform by Hashicorp. + +Source code: https://github.com/rudecs/terraform-provider-decort + +Please see README.md to learn where to place source code so that it +builds seamlessly. + +Documentation: https://github.com/rudecs/terraform-provider-decort/wiki +*/ + +package grid + +const GridListGetAPI = "/restmachine/cloudbroker/grid/list" +const GridGetAPI = "/restmachine/cloudbroker/grid/get" diff --git a/decort/data_source_grid.go b/internal/service/cloudbroker/grid/data_source_grid.go similarity index 61% rename from decort/data_source_grid.go rename to internal/service/cloudbroker/grid/data_source_grid.go index 2529e3f..7ba9abe 100644 --- a/decort/data_source_grid.go +++ b/internal/service/cloudbroker/grid/data_source_grid.go @@ -1,6 +1,8 @@ /* Copyright (c) 2019-2022 Digital Energy Cloud Solutions LLC. All Rights Reserved. -Author: Stanislav Solovev, , +Authors: +Petr Krutov, +Stanislav Solovev, Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. @@ -16,18 +18,26 @@ limitations under the License. */ /* -This file is part of Terraform (by Hashicorp) provider for Digital Energy Cloud Orchestration -Technology platfom. +Terraform DECORT provider - manage resources provided by DECORT (Digital Energy Cloud +Orchestration Technology) with Terraform by Hashicorp. -Visit https://github.com/rudecs/terraform-provider-decort for full source code package and updates. +Source code: https://github.com/rudecs/terraform-provider-decort + +Please see README.md to learn where to place source code so that it +builds seamlessly. + +Documentation: https://github.com/rudecs/terraform-provider-decort/wiki */ -package decort +package grid import ( + "context" "strconv" - "github.com/hashicorp/terraform-plugin-sdk/helper/schema" + "github.com/hashicorp/terraform-plugin-sdk/v2/diag" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" + "github.com/rudecs/terraform-provider-decort/internal/constants" ) func flattenGrid(d *schema.ResourceData, grid *Grid) { @@ -39,10 +49,10 @@ func flattenGrid(d *schema.ResourceData, grid *Grid) { d.Set("id", grid.Id) } -func dataSourceGridRead(d *schema.ResourceData, m interface{}) error { +func dataSourceGridRead(ctx context.Context, d *schema.ResourceData, m interface{}) diag.Diagnostics { grid, err := utilityGridCheckPresence(d, m) if err != nil { - return err + return diag.FromErr(err) } d.SetId(strconv.Itoa(grid.Id)) flattenGrid(d, grid) @@ -83,15 +93,15 @@ func dataSourceGetGridSchemaMake() map[string]*schema.Schema { } } -func dataSourceGrid() *schema.Resource { +func DataSourceGrid() *schema.Resource { return &schema.Resource{ SchemaVersion: 1, - Read: dataSourceGridRead, + ReadContext: dataSourceGridRead, Timeouts: &schema.ResourceTimeout{ - Read: &Timeout30s, - Default: &Timeout60s, + Read: &constants.Timeout30s, + Default: &constants.Timeout60s, }, Schema: dataSourceGetGridSchemaMake(), diff --git a/decort/data_source_grid_list.go b/internal/service/cloudbroker/grid/data_source_grid_list.go similarity index 68% rename from decort/data_source_grid_list.go rename to internal/service/cloudbroker/grid/data_source_grid_list.go index 3a420da..4521c90 100644 --- a/decort/data_source_grid_list.go +++ b/internal/service/cloudbroker/grid/data_source_grid_list.go @@ -1,6 +1,8 @@ /* Copyright (c) 2019-2022 Digital Energy Cloud Solutions LLC. All Rights Reserved. -Author: Stanislav Solovev, , +Authors: +Petr Krutov, +Stanislav Solovev, Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. @@ -16,17 +18,26 @@ limitations under the License. */ /* -This file is part of Terraform (by Hashicorp) provider for Digital Energy Cloud Orchestration -Technology platfom. +Terraform DECORT provider - manage resources provided by DECORT (Digital Energy Cloud +Orchestration Technology) with Terraform by Hashicorp. -Visit https://github.com/rudecs/terraform-provider-decort for full source code package and updates. +Source code: https://github.com/rudecs/terraform-provider-decort + +Please see README.md to learn where to place source code so that it +builds seamlessly. + +Documentation: https://github.com/rudecs/terraform-provider-decort/wiki */ -package decort +package grid import ( + "context" + "github.com/google/uuid" - "github.com/hashicorp/terraform-plugin-sdk/helper/schema" + "github.com/hashicorp/terraform-plugin-sdk/v2/diag" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" + "github.com/rudecs/terraform-provider-decort/internal/constants" ) func flattenGridList(gl GridList) []map[string]interface{} { @@ -46,10 +57,10 @@ func flattenGridList(gl GridList) []map[string]interface{} { return res } -func dataSourceGridListRead(d *schema.ResourceData, m interface{}) error { +func dataSourceGridListRead(ctx context.Context, d *schema.ResourceData, m interface{}) diag.Diagnostics { gridList, err := utilityGridListCheckPresence(d, m) if err != nil { - return err + return diag.FromErr(err) } id := uuid.New() d.SetId(id.String()) @@ -112,15 +123,15 @@ func dataSourceGridSchemaMake() map[string]*schema.Schema { } } -func dataSourceGridList() *schema.Resource { +func DataSourceGridList() *schema.Resource { return &schema.Resource{ SchemaVersion: 1, - Read: dataSourceGridListRead, + ReadContext: dataSourceGridListRead, Timeouts: &schema.ResourceTimeout{ - Read: &Timeout30s, - Default: &Timeout60s, + Read: &constants.Timeout30s, + Default: &constants.Timeout60s, }, Schema: dataSourceGridListSchemaMake(), diff --git a/internal/service/cloudbroker/grid/models.go b/internal/service/cloudbroker/grid/models.go new file mode 100644 index 0000000..72e35cf --- /dev/null +++ b/internal/service/cloudbroker/grid/models.go @@ -0,0 +1,43 @@ +/* +Copyright (c) 2019-2022 Digital Energy Cloud Solutions LLC. All Rights Reserved. +Authors: +Petr Krutov, +Stanislav Solovev, + +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. +*/ + +/* +Terraform DECORT provider - manage resources provided by DECORT (Digital Energy Cloud +Orchestration Technology) with Terraform by Hashicorp. + +Source code: https://github.com/rudecs/terraform-provider-decort + +Please see README.md to learn where to place source code so that it +builds seamlessly. + +Documentation: https://github.com/rudecs/terraform-provider-decort/wiki +*/ + +package grid + +type Grid struct { + Flag string `json:"flag"` + Gid int `json:"gid"` + Guid int `json:"guid"` + Id int `json:"id"` + LocationCode string `json:"locationCode"` + Name string `json:"name"` +} + +type GridList []Grid diff --git a/decort/utility_grid.go b/internal/service/cloudbroker/grid/utility_grid.go similarity index 60% rename from decort/utility_grid.go rename to internal/service/cloudbroker/grid/utility_grid.go index 8500a5f..ef30e99 100644 --- a/decort/utility_grid.go +++ b/internal/service/cloudbroker/grid/utility_grid.go @@ -1,6 +1,8 @@ /* Copyright (c) 2019-2022 Digital Energy Cloud Solutions LLC. All Rights Reserved. -Author: Stanislav Solovev, , +Authors: +Petr Krutov, +Stanislav Solovev, Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. @@ -16,13 +18,18 @@ limitations under the License. */ /* -This file is part of Terraform (by Hashicorp) provider for Digital Energy Cloud Orchestration -Technology platfom. +Terraform DECORT provider - manage resources provided by DECORT (Digital Energy Cloud +Orchestration Technology) with Terraform by Hashicorp. -Visit https://github.com/rudecs/terraform-provider-decort for full source code package and updates. +Source code: https://github.com/rudecs/terraform-provider-decort + +Please see README.md to learn where to place source code so that it +builds seamlessly. + +Documentation: https://github.com/rudecs/terraform-provider-decort/wiki */ -package decort +package grid import ( "encoding/json" @@ -30,14 +37,15 @@ import ( "net/url" "strconv" + "github.com/rudecs/terraform-provider-decort/internal/controller" log "github.com/sirupsen/logrus" - "github.com/hashicorp/terraform-plugin-sdk/helper/schema" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" ) func utilityGridCheckPresence(d *schema.ResourceData, m interface{}) (*Grid, error) { grid := &Grid{} - controller := m.(*ControllerCfg) + c := m.(*controller.ControllerCfg) urlValues := &url.Values{} if gridId, ok := d.GetOk("grid_id"); ok { @@ -47,7 +55,7 @@ func utilityGridCheckPresence(d *schema.ResourceData, m interface{}) (*Grid, err } log.Debugf("utilityGridCheckPresence: load grid") - gridRaw, err := controller.decortAPICall("POST", GridGetAPI, urlValues) + gridRaw, err := c.DecortAPICall("POST", GridGetAPI, urlValues) if err != nil { return nil, err } diff --git a/decort/utility_grid_list.go b/internal/service/cloudbroker/grid/utility_grid_list.go similarity index 61% rename from decort/utility_grid_list.go rename to internal/service/cloudbroker/grid/utility_grid_list.go index 202f6ad..c679411 100644 --- a/decort/utility_grid_list.go +++ b/internal/service/cloudbroker/grid/utility_grid_list.go @@ -1,6 +1,8 @@ /* Copyright (c) 2019-2022 Digital Energy Cloud Solutions LLC. All Rights Reserved. -Author: Stanislav Solovev, , +Authors: +Petr Krutov, +Stanislav Solovev, Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. @@ -16,27 +18,33 @@ limitations under the License. */ /* -This file is part of Terraform (by Hashicorp) provider for Digital Energy Cloud Orchestration -Technology platfom. +Terraform DECORT provider - manage resources provided by DECORT (Digital Energy Cloud +Orchestration Technology) with Terraform by Hashicorp. -Visit https://github.com/rudecs/terraform-provider-decort for full source code package and updates. +Source code: https://github.com/rudecs/terraform-provider-decort + +Please see README.md to learn where to place source code so that it +builds seamlessly. + +Documentation: https://github.com/rudecs/terraform-provider-decort/wiki */ -package decort +package grid import ( "encoding/json" "net/url" "strconv" + "github.com/rudecs/terraform-provider-decort/internal/controller" log "github.com/sirupsen/logrus" - "github.com/hashicorp/terraform-plugin-sdk/helper/schema" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" ) func utilityGridListCheckPresence(d *schema.ResourceData, m interface{}) (GridList, error) { gridList := GridList{} - controller := m.(*ControllerCfg) + c := m.(*controller.ControllerCfg) urlValues := &url.Values{} if page, ok := d.GetOk("page"); ok { @@ -47,7 +55,7 @@ func utilityGridListCheckPresence(d *schema.ResourceData, m interface{}) (GridLi } log.Debugf("utilityGridListCheckPresence: load grid list") - gridListRaw, err := controller.decortAPICall("POST", GridListGetAPI, urlValues) + gridListRaw, err := c.DecortAPICall("POST", GridListGetAPI, urlValues) if err != nil { return nil, err } diff --git a/internal/service/cloudbroker/image/api.go b/internal/service/cloudbroker/image/api.go new file mode 100644 index 0000000..a7610ff --- /dev/null +++ b/internal/service/cloudbroker/image/api.go @@ -0,0 +1,52 @@ +/* +Copyright (c) 2019-2022 Digital Energy Cloud Solutions LLC. All Rights Reserved. +Authors: +Petr Krutov, +Stanislav Solovev, + +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. +*/ + +/* +Terraform DECORT provider - manage resources provided by DECORT (Digital Energy Cloud +Orchestration Technology) with Terraform by Hashicorp. + +Source code: https://github.com/rudecs/terraform-provider-decort + +Please see README.md to learn where to place source code so that it +builds seamlessly. + +Documentation: https://github.com/rudecs/terraform-provider-decort/wiki +*/ + +package image + +const imageCreateAPI = "/restmachine/cloudbroker/image/createImage" +const imageSyncCreateAPI = "/restmachine/cloudbroker/image/syncCreateImage" +const imageCreateVirtualAPI = "/restmachine/cloudbroker/image/createVirtual" +const imageCreateCDROMAPI = "/restmachine/cloudbroker/image/createCDROMImage" +const imageListStacksApi = "/restmachine/cloudbroker/image/listStacks" +const imageGetAPI = "/restmachine/cloudbroker/image/get" +const imageListGetAPI = "/restmachine/cloudbroker/image/list" +const imageEditAPI = "/restmachine/cloudbroker/image/edit" +const imageDeleteAPI = "/restmachine/cloudbroker/image/delete" +const imageDeleteCDROMAPI = "/restmachine/cloudbroker/image/deleteCDROMImage" +const imageEnableAPI = "/restmachine/cloudbroker/image/enable" +const imageDisableAPI = "/restmachine/cloudbroker/image/disable" +const imageEditNameAPI = "/restmachine/cloudbroker/image/rename" +const imageLinkAPI = "/restmachine/cloudbroker/image/link" +const imageShareAPI = "/restmachine/cloudbroker/image/share" +const imageComputeciSetAPI = "/restmachine/cloudbroker/image/computeciSet" +const imageComputeciUnsetAPI = "/restmachine/cloudbroker/image/computeciUnset" +const imageUpdateNodesAPI = "/restmachine/cloudbroker/image/updateNodes" +const imageDeleteImagesAPI = "/restmachine/cloudbroker/image/deleteImages" diff --git a/decort/data_source_image.go b/internal/service/cloudbroker/image/data_source_image.go similarity index 86% rename from decort/data_source_image.go rename to internal/service/cloudbroker/image/data_source_image.go index 9a218e9..fe0ee4b 100644 --- a/decort/data_source_image.go +++ b/internal/service/cloudbroker/image/data_source_image.go @@ -1,6 +1,8 @@ /* Copyright (c) 2019-2022 Digital Energy Cloud Solutions LLC. All Rights Reserved. -Author: Stanislav Solovev, , +Authors: +Petr Krutov, +Stanislav Solovev, Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. @@ -16,18 +18,27 @@ limitations under the License. */ /* -This file is part of Terraform (by Hashicorp) provider for Digital Energy Cloud Orchestration -Technology platfom. +Terraform DECORT provider - manage resources provided by DECORT (Digital Energy Cloud +Orchestration Technology) with Terraform by Hashicorp. -Visit https://github.com/rudecs/terraform-provider-decort for full source code package and updates. +Source code: https://github.com/rudecs/terraform-provider-decort + +Please see README.md to learn where to place source code so that it +builds seamlessly. + +Documentation: https://github.com/rudecs/terraform-provider-decort/wiki */ -package decort +package image import ( + "context" "strconv" - "github.com/hashicorp/terraform-plugin-sdk/helper/schema" + "github.com/hashicorp/terraform-plugin-sdk/v2/diag" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" + "github.com/rudecs/terraform-provider-decort/internal/constants" + "github.com/rudecs/terraform-provider-decort/internal/flattens" ) func flattenImage(d *schema.ResourceData, image *Image) { @@ -66,16 +77,16 @@ func flattenImage(d *schema.ResourceData, image *Image) { d.Set("hot_resize", image.Hotresize) d.Set("history", flattenHistory(image.History)) d.Set("last_modified", image.LastModified) - d.Set("meta", flattenMeta(image.Meta)) + d.Set("meta", flattens.FlattenMeta(image.Meta)) d.Set("desc", image.Desc) d.Set("shared_with", image.SharedWith) } -func dataSourceImageRead(d *schema.ResourceData, m interface{}) error { +func dataSourceImageRead(ctx context.Context, d *schema.ResourceData, m interface{}) diag.Diagnostics { image, err := utilityImageCheckPresence(d, m) if err != nil { - return err + return diag.FromErr(err) } d.SetId(strconv.Itoa(image.Guid)) flattenImage(d, image) @@ -295,15 +306,15 @@ func dataSourceImageSchemaMake() map[string]*schema.Schema { } } -func dataSourceImage() *schema.Resource { +func DataSourceImage() *schema.Resource { return &schema.Resource{ SchemaVersion: 1, - Read: dataSourceImageRead, + ReadContext: dataSourceImageRead, Timeouts: &schema.ResourceTimeout{ - Read: &Timeout30s, - Default: &Timeout60s, + Read: &constants.Timeout30s, + Default: &constants.Timeout60s, }, Schema: dataSourceImageSchemaMake(), diff --git a/decort/data_source_image_list.go b/internal/service/cloudbroker/image/data_source_image_list.go similarity index 74% rename from decort/data_source_image_list.go rename to internal/service/cloudbroker/image/data_source_image_list.go index ad6f6d9..1108d23 100644 --- a/decort/data_source_image_list.go +++ b/internal/service/cloudbroker/image/data_source_image_list.go @@ -1,6 +1,8 @@ /* Copyright (c) 2019-2022 Digital Energy Cloud Solutions LLC. All Rights Reserved. -Author: Stanislav Solovev, , +Authors: +Petr Krutov, +Stanislav Solovev, Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. @@ -16,17 +18,26 @@ limitations under the License. */ /* -This file is part of Terraform (by Hashicorp) provider for Digital Energy Cloud Orchestration -Technology platfom. +Terraform DECORT provider - manage resources provided by DECORT (Digital Energy Cloud +Orchestration Technology) with Terraform by Hashicorp. -Visit https://github.com/rudecs/terraform-provider-decort for full source code package and updates. +Source code: https://github.com/rudecs/terraform-provider-decort + +Please see README.md to learn where to place source code so that it +builds seamlessly. + +Documentation: https://github.com/rudecs/terraform-provider-decort/wiki */ -package decort +package image import ( + "context" + "github.com/google/uuid" - "github.com/hashicorp/terraform-plugin-sdk/helper/schema" + "github.com/hashicorp/terraform-plugin-sdk/v2/diag" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" + "github.com/rudecs/terraform-provider-decort/internal/constants" ) func flattenImageList(il ImageList) []map[string]interface{} { @@ -77,10 +88,10 @@ func flattenImageList(il ImageList) []map[string]interface{} { return res } -func dataSourceImageListRead(d *schema.ResourceData, m interface{}) error { +func dataSourceImageListRead(ctx context.Context, d *schema.ResourceData, m interface{}) diag.Diagnostics { imageList, err := utilityImageListCheckPresence(d, m) if err != nil { - return err + return diag.FromErr(err) } id := uuid.New() d.SetId(id.String()) @@ -124,15 +135,15 @@ func dataSourceImageListSchemaMake() map[string]*schema.Schema { return rets } -func dataSourceImageList() *schema.Resource { +func DataSourceImageList() *schema.Resource { return &schema.Resource{ SchemaVersion: 1, - Read: dataSourceImageListRead, + ReadContext: dataSourceImageListRead, Timeouts: &schema.ResourceTimeout{ - Read: &Timeout30s, - Default: &Timeout60s, + Read: &constants.Timeout30s, + Default: &constants.Timeout60s, }, Schema: dataSourceImageListSchemaMake(), diff --git a/decort/data_source_image_list_stacks.go b/internal/service/cloudbroker/image/data_source_image_list_stacks.go similarity index 75% rename from decort/data_source_image_list_stacks.go rename to internal/service/cloudbroker/image/data_source_image_list_stacks.go index 7b37371..2a47dd5 100644 --- a/decort/data_source_image_list_stacks.go +++ b/internal/service/cloudbroker/image/data_source_image_list_stacks.go @@ -1,6 +1,8 @@ /* Copyright (c) 2019-2022 Digital Energy Cloud Solutions LLC. All Rights Reserved. -Author: Stanislav Solovev, , +Authors: +Petr Krutov, +Stanislav Solovev, Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. @@ -16,17 +18,26 @@ limitations under the License. */ /* -This file is part of Terraform (by Hashicorp) provider for Digital Energy Cloud Orchestration -Technology platfom. +Terraform DECORT provider - manage resources provided by DECORT (Digital Energy Cloud +Orchestration Technology) with Terraform by Hashicorp. -Visit https://github.com/rudecs/terraform-provider-decort for full source code package and updates. +Source code: https://github.com/rudecs/terraform-provider-decort + +Please see README.md to learn where to place source code so that it +builds seamlessly. + +Documentation: https://github.com/rudecs/terraform-provider-decort/wiki */ -package decort +package image import ( + "context" + "github.com/google/uuid" - "github.com/hashicorp/terraform-plugin-sdk/helper/schema" + "github.com/hashicorp/terraform-plugin-sdk/v2/diag" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" + "github.com/rudecs/terraform-provider-decort/internal/constants" ) func flattenImageListStacks(_ *schema.ResourceData, stack ImageListStacks) []map[string]interface{} { @@ -55,10 +66,10 @@ func flattenImageListStacks(_ *schema.ResourceData, stack ImageListStacks) []map return temp } -func dataSourceImageListStacksRead(d *schema.ResourceData, m interface{}) error { +func dataSourceImageListStacksRead(ctx context.Context, d *schema.ResourceData, m interface{}) diag.Diagnostics { imageListStacks, err := utilityImageListStacksCheckPresence(d, m) if err != nil { - return err + return diag.FromErr(err) } id := uuid.New() d.SetId(id.String()) @@ -166,15 +177,15 @@ func dataSourceImageListStacksSchemaMake() map[string]*schema.Schema { } } -func dataSourceImageListStacks() *schema.Resource { +func DataSourceImageListStacks() *schema.Resource { return &schema.Resource{ SchemaVersion: 1, - Read: dataSourceImageListStacksRead, + ReadContext: dataSourceImageListStacksRead, Timeouts: &schema.ResourceTimeout{ - Read: &Timeout30s, - Default: &Timeout60s, + Read: &constants.Timeout30s, + Default: &constants.Timeout60s, }, Schema: dataSourceImageListStacksSchemaMake(), diff --git a/internal/service/cloudbroker/image/models.go b/internal/service/cloudbroker/image/models.go new file mode 100644 index 0000000..7c0f34b --- /dev/null +++ b/internal/service/cloudbroker/image/models.go @@ -0,0 +1,101 @@ +/* +Copyright (c) 2019-2022 Digital Energy Cloud Solutions LLC. All Rights Reserved. +Authors: +Petr Krutov, +Stanislav Solovev, + +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. +*/ + +/* +Terraform DECORT provider - manage resources provided by DECORT (Digital Energy Cloud +Orchestration Technology) with Terraform by Hashicorp. + +Source code: https://github.com/rudecs/terraform-provider-decort + +Please see README.md to learn where to place source code so that it +builds seamlessly. + +Documentation: https://github.com/rudecs/terraform-provider-decort/wiki +*/ + +package image + +type History struct { + Guid string `json:"guid"` + Id int `json:"id"` + Timestamp int64 `json:"timestamp"` +} + +type Image struct { + ImageId int `json:"id"` + Name string `json:"name"` + Url string `json:"url"` + Gid int `json:"gid"` + Guid int `json:"guid"` + Boottype string `json:"bootType"` + Imagetype string `json:"type"` + Drivers []string `json:"drivers"` + Hotresize bool `json:"hotResize"` + Bootable bool `json:"bootable"` + Username string `json:"username"` + Password string `json:"password"` + AccountId int `json:"accountId"` + UsernameDL string `json:"usernameDL"` + PasswordDL string `json:"passwordDL"` + SepId int `json:"sepId"` + PoolName string `json:"pool"` + Architecture string `json:"architecture"` + UNCPath string `json:"UNCPath"` + LinkTo int `json:"linkTo"` + Status string `json:"status"` + TechStatus string `json:"techStatus"` + Size int `json:"size"` + Version string `json:"version"` + Enabled bool `json:"enabled"` + ComputeciId int `json:"computeciId"` + Milestones int `json:"milestones"` + ProviderName string `json:"provider_name"` + PurgeAttempts int `json:"purgeAttempts"` + ReferenceId string `json:"referenceId"` + ResId string `json:"resId"` + ResName string `json:"resName"` + Rescuecd bool `json:"rescuecd"` + Meta []interface{} `json:"_meta"` + History []History `json:"history"` + LastModified int64 `json:"lastModified"` + Desc string `json:"desc"` + SharedWith []int `json:"sharedWith"` +} + +type ImageList []Image + +type ImageStack struct { + ApiURL string `json:"apiUrl"` + ApiKey string `json:"apikey"` + AppId string `json:"appId"` + Desc string `json:"desc"` + Drivers []string `json:"drivers"` + Error int `json:"error"` + Guid int `json:"guid"` + Id int `json:"id"` + Images []int `json:"images"` + Login string `json:"login"` + Name string `json:"name"` + Passwd string `json:"passwd"` + ReferenceId string `json:"referenceId"` + Status string `json:"status"` + Type string `json:"type"` +} + +type ImageListStacks []ImageStack diff --git a/decort/resource_cdrom_image.go b/internal/service/cloudbroker/image/resource_cdrom_image.go similarity index 73% rename from decort/resource_cdrom_image.go rename to internal/service/cloudbroker/image/resource_cdrom_image.go index df93a21..af794eb 100644 --- a/decort/resource_cdrom_image.go +++ b/internal/service/cloudbroker/image/resource_cdrom_image.go @@ -1,6 +1,8 @@ /* Copyright (c) 2019-2022 Digital Energy Cloud Solutions LLC. All Rights Reserved. -Author: Stanislav Solovev, +Authors: +Petr Krutov, +Stanislav Solovev, Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. @@ -16,27 +18,35 @@ limitations under the License. */ /* -This file is part of Terraform (by Hashicorp) provider for Digital Energy Cloud Orchestration -Technology platfom. +Terraform DECORT provider - manage resources provided by DECORT (Digital Energy Cloud +Orchestration Technology) with Terraform by Hashicorp. -Visit https://github.com/rudecs/terraform-provider-decort for full source code package and updates. +Source code: https://github.com/rudecs/terraform-provider-decort + +Please see README.md to learn where to place source code so that it +builds seamlessly. + +Documentation: https://github.com/rudecs/terraform-provider-decort/wiki */ -package decort +package image import ( + "context" "net/url" "strconv" - "github.com/hashicorp/terraform-plugin-sdk/helper/customdiff" - "github.com/hashicorp/terraform-plugin-sdk/helper/schema" + "github.com/hashicorp/terraform-plugin-sdk/v2/diag" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" + "github.com/rudecs/terraform-provider-decort/internal/constants" + "github.com/rudecs/terraform-provider-decort/internal/controller" log "github.com/sirupsen/logrus" ) -func resourceCDROMImageCreate(d *schema.ResourceData, m interface{}) error { +func resourceCDROMImageCreate(ctx context.Context, d *schema.ResourceData, m interface{}) diag.Diagnostics { log.Debugf("resourceCDROMImageCreate: called for image %s", d.Get("name").(string)) - controller := m.(*ControllerCfg) + c := m.(*controller.ControllerCfg) urlValues := &url.Values{} urlValues.Add("name", d.Get("name").(string)) urlValues.Add("url", d.Get("url").(string)) @@ -80,9 +90,9 @@ func resourceCDROMImageCreate(d *schema.ResourceData, m interface{}) error { urlValues.Add("architecture", architecture.(string)) } - imageId, err := controller.decortAPICall("POST", imageCreateCDROMAPI, urlValues) + imageId, err := c.DecortAPICall("POST", imageCreateCDROMAPI, urlValues) if err != nil { - return err + return diag.FromErr(err) } d.SetId(imageId) @@ -90,33 +100,33 @@ func resourceCDROMImageCreate(d *schema.ResourceData, m interface{}) error { image, err := utilityImageCheckPresence(d, m) if err != nil { - return err + return diag.FromErr(err) } d.SetId(strconv.Itoa(image.ImageId)) d.Set("bootable", image.Bootable) //d.Set("image_id", image.ImageId) - err = resourceImageRead(d, m) - if err != nil { - return err + diagnostics := resourceImageRead(ctx, d, m) + if diagnostics != nil { + return diagnostics } return nil } -func resourceCDROMImageDelete(d *schema.ResourceData, m interface{}) error { +func resourceCDROMImageDelete(ctx context.Context, d *schema.ResourceData, m interface{}) diag.Diagnostics { log.Debugf("resourceCDROMImageDelete: called for %s, id: %s", d.Get("name").(string), d.Id()) image, err := utilityImageCheckPresence(d, m) if image == nil { if err != nil { - return err + return diag.FromErr(err) } return nil } - controller := m.(*ControllerCfg) + c := m.(*controller.ControllerCfg) urlValues := &url.Values{} urlValues.Add("imageId", strconv.Itoa(d.Get("image_id").(int))) @@ -124,9 +134,9 @@ func resourceCDROMImageDelete(d *schema.ResourceData, m interface{}) error { urlValues.Add("permanently", strconv.FormatBool(permanently.(bool))) } - _, err = controller.decortAPICall("POST", imageDeleteCDROMAPI, urlValues) + _, err = c.DecortAPICall("POST", imageDeleteCDROMAPI, urlValues) if err != nil { - return err + return diag.FromErr(err) } d.SetId("") @@ -361,73 +371,27 @@ func resourceCDROMImageSchemaMake() map[string]*schema.Schema { } } -func resourceCDROMImage() *schema.Resource { +func ResourceCDROMImage() *schema.Resource { return &schema.Resource{ SchemaVersion: 1, - Create: resourceCDROMImageCreate, - Read: resourceImageRead, - Update: resourceImageEdit, - Delete: resourceCDROMImageDelete, - Exists: resourceImageExists, + CreateContext: resourceCDROMImageCreate, + ReadContext: resourceImageRead, + UpdateContext: resourceImageEdit, + DeleteContext: resourceCDROMImageDelete, + Exists: resourceImageExists, Importer: &schema.ResourceImporter{ State: schema.ImportStatePassthrough, }, Timeouts: &schema.ResourceTimeout{ - Create: &Timeout60s, - Read: &Timeout30s, - Update: &Timeout60s, - Delete: &Timeout60s, - Default: &Timeout60s, - }, - - CustomizeDiff: customdiff.All( - customdiff.IfValueChange("enabled", func(old, new, meta interface{}) bool { - return old.(bool) != new.(bool) - }, resourceImageChangeEnabled), - customdiff.IfValueChange("name", func(old, new, meta interface{}) bool { - return old.(string) != new.(string) && old.(string) != "" - }, resourceImageEditName), - customdiff.IfValueChange("shared_with", func(old, new, meta interface{}) bool { - o := old.([]interface{}) - n := new.([]interface{}) - - if len(o) != len(n) { - return true - } else if len(o) == 0 { - return false - } - count := 0 - for i, v := range n { - if v.(int) == o[i].(int) { - count++ - } - } - return count == 0 - }, resourceImageShare), - customdiff.IfValueChange("computeci_id", func(old, new, meta interface{}) bool { - return old.(int) != new.(int) - }, resourceImageChangeComputeci), - customdiff.IfValueChange("enabled_stacks", func(old, new, meta interface{}) bool { - o := old.([]interface{}) - n := new.([]interface{}) - - if len(o) != len(n) { - return true - } else if len(o) == 0 { - return false - } - count := 0 - for i, v := range n { - if v.(string) == o[i].(string) { - count++ - } - } - return count == 0 - }, resourceImageUpdateNodes), - ), + Create: &constants.Timeout60s, + Read: &constants.Timeout30s, + Update: &constants.Timeout60s, + Delete: &constants.Timeout60s, + Default: &constants.Timeout60s, + }, Schema: resourceCDROMImageSchemaMake(), } diff --git a/decort/resource_delete_images.go b/internal/service/cloudbroker/image/resource_delete_images.go similarity index 56% rename from decort/resource_delete_images.go rename to internal/service/cloudbroker/image/resource_delete_images.go index 5c5cc19..5548285 100644 --- a/decort/resource_delete_images.go +++ b/internal/service/cloudbroker/image/resource_delete_images.go @@ -1,6 +1,8 @@ /* Copyright (c) 2019-2022 Digital Energy Cloud Solutions LLC. All Rights Reserved. -Author: Stanislav Solovev, +Authors: +Petr Krutov, +Stanislav Solovev, Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. @@ -16,33 +18,42 @@ limitations under the License. */ /* -This file is part of Terraform (by Hashicorp) provider for Digital Energy Cloud Orchestration -Technology platfom. +Terraform DECORT provider - manage resources provided by DECORT (Digital Energy Cloud +Orchestration Technology) with Terraform by Hashicorp. -Visit https://github.com/rudecs/terraform-provider-decort for full source code package and updates. +Source code: https://github.com/rudecs/terraform-provider-decort + +Please see README.md to learn where to place source code so that it +builds seamlessly. + +Documentation: https://github.com/rudecs/terraform-provider-decort/wiki */ -package decort +package image import ( + "context" "net/url" "strconv" "github.com/google/uuid" - "github.com/hashicorp/terraform-plugin-sdk/helper/schema" + "github.com/hashicorp/terraform-plugin-sdk/v2/diag" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" + "github.com/rudecs/terraform-provider-decort/internal/constants" + "github.com/rudecs/terraform-provider-decort/internal/controller" log "github.com/sirupsen/logrus" ) -func resourceCreateListImages(d *schema.ResourceData, m interface{}) error { +func resourceCreateListImages(ctx context.Context, d *schema.ResourceData, m interface{}) diag.Diagnostics { id := uuid.New() d.SetId(id.String()) return nil } -func resourceDeleteListImages(d *schema.ResourceData, m interface{}) error { +func resourceDeleteListImages(ctx context.Context, d *schema.ResourceData, m interface{}) diag.Diagnostics { log.Debugf("resourceDeleteListImages: start deleting...") - c := m.(*ControllerCfg) + c := m.(*controller.ControllerCfg) urlValues := &url.Values{} imageIds := d.Get("image_ids").([]interface{}) @@ -63,9 +74,9 @@ func resourceDeleteListImages(d *schema.ResourceData, m interface{}) error { urlValues.Add("permanently", strconv.FormatBool(d.Get("permanently").(bool))) urlValues.Add("imageIds", temp) - _, err := c.decortAPICall("POST", imageDeleteImagesAPI, urlValues) + _, err := c.DecortAPICall("POST", imageDeleteImagesAPI, urlValues) if err != nil { - return err + return diag.FromErr(err) } d.SetId("") @@ -73,7 +84,7 @@ func resourceDeleteListImages(d *schema.ResourceData, m interface{}) error { return nil } -func resourceReadListImages(d *schema.ResourceData, m interface{}) error { +func resourceReadListImages(ctx context.Context, d *schema.ResourceData, m interface{}) diag.Diagnostics { return nil } @@ -106,24 +117,24 @@ func resourceDeleteImagesSchemaMake() map[string]*schema.Schema { } -func resourceDeleteImages() *schema.Resource { +func ResourceDeleteImages() *schema.Resource { return &schema.Resource{ SchemaVersion: 1, - Create: resourceCreateListImages, - Read: resourceReadListImages, - Delete: resourceDeleteListImages, + CreateContext: resourceCreateListImages, + ReadContext: resourceReadListImages, + DeleteContext: resourceDeleteListImages, Importer: &schema.ResourceImporter{ State: schema.ImportStatePassthrough, }, Timeouts: &schema.ResourceTimeout{ - Create: &Timeout60s, - Read: &Timeout30s, - Update: &Timeout60s, - Delete: &Timeout60s, - Default: &Timeout60s, + Create: &constants.Timeout60s, + Read: &constants.Timeout30s, + Update: &constants.Timeout60s, + Delete: &constants.Timeout60s, + Default: &constants.Timeout60s, }, Schema: resourceDeleteImagesSchemaMake(), diff --git a/decort/resource_image.go b/internal/service/cloudbroker/image/resource_image.go similarity index 72% rename from decort/resource_image.go rename to internal/service/cloudbroker/image/resource_image.go index cd4b970..464e687 100644 --- a/decort/resource_image.go +++ b/internal/service/cloudbroker/image/resource_image.go @@ -1,6 +1,8 @@ /* Copyright (c) 2019-2022 Digital Energy Cloud Solutions LLC. All Rights Reserved. -Author: Stanislav Solovev, +Authors: +Petr Krutov, +Stanislav Solovev, Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. @@ -16,28 +18,37 @@ limitations under the License. */ /* -This file is part of Terraform (by Hashicorp) provider for Digital Energy Cloud Orchestration -Technology platfom. +Terraform DECORT provider - manage resources provided by DECORT (Digital Energy Cloud +Orchestration Technology) with Terraform by Hashicorp. -Visit https://github.com/rudecs/terraform-provider-decort for full source code package and updates. +Source code: https://github.com/rudecs/terraform-provider-decort + +Please see README.md to learn where to place source code so that it +builds seamlessly. + +Documentation: https://github.com/rudecs/terraform-provider-decort/wiki */ -package decort +package image import ( + "context" "errors" "net/url" "strconv" - "github.com/hashicorp/terraform-plugin-sdk/helper/customdiff" - "github.com/hashicorp/terraform-plugin-sdk/helper/schema" + "github.com/hashicorp/terraform-plugin-sdk/v2/diag" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" + "github.com/rudecs/terraform-provider-decort/internal/constants" + "github.com/rudecs/terraform-provider-decort/internal/controller" + "github.com/rudecs/terraform-provider-decort/internal/flattens" log "github.com/sirupsen/logrus" ) -func resourceImageCreate(d *schema.ResourceData, m interface{}) error { +func resourceImageCreate(ctx context.Context, d *schema.ResourceData, m interface{}) diag.Diagnostics { log.Debugf("resourceImageCreate: called for image %s", d.Get("name").(string)) - controller := m.(*ControllerCfg) + c := m.(*controller.ControllerCfg) urlValues := &url.Values{} urlValues.Add("name", d.Get("name").(string)) urlValues.Add("url", d.Get("url").(string)) @@ -92,9 +103,9 @@ func resourceImageCreate(d *schema.ResourceData, m interface{}) error { } else { api = imageSyncCreateAPI } - imageId, err := controller.decortAPICall("POST", api, urlValues) + imageId, err := c.DecortAPICall("POST", api, urlValues) if err != nil { - return err + return diag.FromErr(err) } d.SetId(imageId) @@ -102,28 +113,28 @@ func resourceImageCreate(d *schema.ResourceData, m interface{}) error { image, err := utilityImageCheckPresence(d, m) if err != nil { - return err + return diag.FromErr(err) } d.SetId(strconv.Itoa(image.ImageId)) d.Set("bootable", image.Bootable) //d.Set("image_id", image.ImageId) - err = resourceImageRead(d, m) - if err != nil { - return err + diagnostics := resourceImageRead(ctx, d, m) + if diagnostics != nil { + return diagnostics } return nil } -func resourceImageRead(d *schema.ResourceData, m interface{}) error { +func resourceImageRead(ctx context.Context, d *schema.ResourceData, m interface{}) diag.Diagnostics { log.Debugf("resourceImageRead: called for %s id: %s", d.Get("name").(string), d.Id()) image, err := utilityImageCheckPresence(d, m) if image == nil { d.SetId("") - return err + return diag.FromErr(err) } d.Set("name", image.Name) @@ -158,7 +169,7 @@ func resourceImageRead(d *schema.ResourceData, m interface{}) error { d.Set("res_name", image.ResName) d.Set("rescuecd", image.Rescuecd) d.Set("architecture", image.Architecture) - d.Set("meta", flattenMeta(image.Meta)) + d.Set("meta", flattens.FlattenMeta(image.Meta)) d.Set("hot_resize", image.Hotresize) d.Set("history", flattenHistory(image.History)) d.Set("last_modified", image.LastModified) @@ -168,18 +179,18 @@ func resourceImageRead(d *schema.ResourceData, m interface{}) error { return nil } -func resourceImageDelete(d *schema.ResourceData, m interface{}) error { +func resourceImageDelete(ctx context.Context, d *schema.ResourceData, m interface{}) diag.Diagnostics { log.Debugf("resourceImageDelete: called for %s, id: %s", d.Get("name").(string), d.Id()) image, err := utilityImageCheckPresence(d, m) if image == nil { if err != nil { - return err + return diag.FromErr(err) } return nil } - controller := m.(*ControllerCfg) + c := m.(*controller.ControllerCfg) urlValues := &url.Values{} urlValues.Add("imageId", strconv.Itoa(d.Get("image_id").(int))) if reason, ok := d.GetOk("reason"); ok { @@ -191,9 +202,9 @@ func resourceImageDelete(d *schema.ResourceData, m interface{}) error { urlValues.Add("permanently", strconv.FormatBool(permanently.(bool))) } - _, err = controller.decortAPICall("POST", imageDeleteAPI, urlValues) + _, err = c.DecortAPICall("POST", imageDeleteAPI, urlValues) if err != nil { - return err + return diag.FromErr(err) } d.SetId("") @@ -214,13 +225,13 @@ func resourceImageExists(d *schema.ResourceData, m interface{}) (bool, error) { return true, nil } -func resourceImageEditName(d *schema.ResourceDiff, m interface{}) error { +func resourceImageEditName(d *schema.ResourceData, m interface{}) error { log.Debugf("resourceImageEditName: called for %s, id: %s", d.Get("name").(string), d.Id()) - c := m.(*ControllerCfg) + c := m.(*controller.ControllerCfg) urlValues := &url.Values{} urlValues.Add("imageId", strconv.Itoa(d.Get("image_id").(int))) urlValues.Add("name", d.Get("name").(string)) - _, err := c.decortAPICall("POST", imageEditNameAPI, urlValues) + _, err := c.DecortAPICall("POST", imageEditNameAPI, urlValues) if err != nil { return err } @@ -228,40 +239,82 @@ func resourceImageEditName(d *schema.ResourceDiff, m interface{}) error { return nil } -func resourceImageEdit(d *schema.ResourceData, m interface{}) error { +func resourceImageEdit(ctx context.Context, d *schema.ResourceData, m interface{}) diag.Diagnostics { log.Debugf("resourceImageEdit: called for %s, id: %s", d.Get("name").(string), d.Id()) - c := m.(*ControllerCfg) + c := m.(*controller.ControllerCfg) urlValues := &url.Values{} - urlValues.Add("imageId", strconv.Itoa(d.Get("image_id").(int))) - urlValues.Add("name", d.Get("name").(string)) - urlValues.Add("username", d.Get("username").(string)) - urlValues.Add("password", d.Get("password").(string)) - urlValues.Add("accountId", strconv.Itoa(d.Get("account_id").(int))) - urlValues.Add("bootable", strconv.FormatBool(d.Get("bootable").(bool))) - urlValues.Add("hotresize", strconv.FormatBool(d.Get("hot_resize").(bool))) + if d.HasChange("enabled") { + err := resourceImageChangeEnabled(d, m) + if err != nil { + return diag.FromErr(err) + } + urlValues = &url.Values{} + } - //_, err := c.decortAPICall("POST", imageEditAPI, urlValues) - _, err := c.decortAPICall("POST", imageEditAPI, urlValues) - if err != nil { - err = resourceImageRead(d, m) + if d.HasChange("name") { + err := resourceImageEditName(d, m) if err != nil { - return err + return diag.FromErr(err) } - return nil + urlValues = &url.Values{} } - err = resourceImageRead(d, m) - if err != nil { - return err + + if d.HasChange("shared_with") { + err := resourceImageShare(d, m) + if err != nil { + return diag.FromErr(err) + } + urlValues = &url.Values{} + } + if d.HasChange("computeci_id") { + err := resourceImageChangeComputeci(d, m) + if err != nil { + return diag.FromErr(err) + } + urlValues = &url.Values{} + } + + if d.HasChange("enabled_stacks") { + err := resourceImageUpdateNodes(d, m) + if err != nil { + return diag.FromErr(err) + } + urlValues = &url.Values{} + } + + if d.HasChange("link_to") { + err := resourceImageLink(d, m) + if err != nil { + return diag.FromErr(err) + } + urlValues = &url.Values{} + } + + if d.HasChanges("name", "username", "password", "account_id", "bootable", "hot_resize") { + + urlValues.Add("imageId", strconv.Itoa(d.Get("image_id").(int))) + urlValues.Add("name", d.Get("name").(string)) + + urlValues.Add("username", d.Get("username").(string)) + urlValues.Add("password", d.Get("password").(string)) + urlValues.Add("accountId", strconv.Itoa(d.Get("account_id").(int))) + urlValues.Add("bootable", strconv.FormatBool(d.Get("bootable").(bool))) + urlValues.Add("hotresize", strconv.FormatBool(d.Get("hot_resize").(bool))) + + _, err := c.DecortAPICall("POST", imageEditAPI, urlValues) + if err != nil { + return diag.FromErr(err) + } } return nil } -func resourceImageChangeEnabled(d *schema.ResourceDiff, m interface{}) error { +func resourceImageChangeEnabled(d *schema.ResourceData, m interface{}) error { var api string - c := m.(*ControllerCfg) + c := m.(*controller.ControllerCfg) urlValues := &url.Values{} urlValues.Add("imageId", strconv.Itoa(d.Get("image_id").(int))) if d.Get("enabled").(bool) { @@ -269,7 +322,7 @@ func resourceImageChangeEnabled(d *schema.ResourceDiff, m interface{}) error { } else { api = imageDisableAPI } - resp, err := c.decortAPICall("POST", api, urlValues) + resp, err := c.DecortAPICall("POST", api, urlValues) if err != nil { return err } @@ -283,13 +336,13 @@ func resourceImageChangeEnabled(d *schema.ResourceDiff, m interface{}) error { return nil } -func resourceImageLink(d *schema.ResourceDiff, m interface{}) error { +func resourceImageLink(d *schema.ResourceData, m interface{}) error { log.Debugf("resourceVirtualImageLink: called for %s, id: %s", d.Get("name").(string), d.Id()) - c := m.(*ControllerCfg) + c := m.(*controller.ControllerCfg) urlValues := &url.Values{} urlValues.Add("imageId", strconv.Itoa(d.Get("image_id").(int))) urlValues.Add("targetId", strconv.Itoa(d.Get("link_to").(int))) - _, err := c.decortAPICall("POST", imageLinkAPI, urlValues) + _, err := c.DecortAPICall("POST", imageLinkAPI, urlValues) if err != nil { return err } @@ -297,9 +350,9 @@ func resourceImageLink(d *schema.ResourceDiff, m interface{}) error { return nil } -func resourceImageShare(d *schema.ResourceDiff, m interface{}) error { +func resourceImageShare(d *schema.ResourceData, m interface{}) error { log.Debugf("resourceImageShare: called for %s, id: %s", d.Get("name").(string), d.Id()) - c := m.(*ControllerCfg) + c := m.(*controller.ControllerCfg) urlValues := &url.Values{} urlValues.Add("imageId", strconv.Itoa(d.Get("image_id").(int))) accIds := d.Get("shared_with").([]interface{}) @@ -316,7 +369,7 @@ func resourceImageShare(d *schema.ResourceDiff, m interface{}) error { } temp = "[" + temp + "]" urlValues.Add("accounts", temp) - _, err := c.decortAPICall("POST", imageShareAPI, urlValues) + _, err := c.DecortAPICall("POST", imageShareAPI, urlValues) if err != nil { return err } @@ -324,8 +377,8 @@ func resourceImageShare(d *schema.ResourceDiff, m interface{}) error { return nil } -func resourceImageChangeComputeci(d *schema.ResourceDiff, m interface{}) error { - c := m.(*ControllerCfg) +func resourceImageChangeComputeci(d *schema.ResourceData, m interface{}) error { + c := m.(*controller.ControllerCfg) urlValues := &url.Values{} urlValues.Add("imageId", strconv.Itoa(d.Get("image_id").(int))) @@ -340,7 +393,7 @@ func resourceImageChangeComputeci(d *schema.ResourceDiff, m interface{}) error { api = imageComputeciSetAPI } - _, err := c.decortAPICall("POST", api, urlValues) + _, err := c.DecortAPICall("POST", api, urlValues) if err != nil { return err } @@ -348,9 +401,9 @@ func resourceImageChangeComputeci(d *schema.ResourceDiff, m interface{}) error { return nil } -func resourceImageUpdateNodes(d *schema.ResourceDiff, m interface{}) error { +func resourceImageUpdateNodes(d *schema.ResourceData, m interface{}) error { log.Debugf("resourceImageUpdateNodes: called for %s, id: %s", d.Get("name").(string), d.Id()) - c := m.(*ControllerCfg) + c := m.(*controller.ControllerCfg) urlValues := &url.Values{} urlValues.Add("imageId", strconv.Itoa(d.Get("image_id").(int))) enabledStacks := d.Get("enabled_stacks").([]interface{}) @@ -365,7 +418,7 @@ func resourceImageUpdateNodes(d *schema.ResourceDiff, m interface{}) error { } temp = "[" + temp + "]" urlValues.Add("enabledStacks", temp) - _, err := c.decortAPICall("POST", imageUpdateNodesAPI, urlValues) + _, err := c.DecortAPICall("POST", imageUpdateNodesAPI, urlValues) if err != nil { return err } @@ -616,73 +669,27 @@ func resourceImageSchemaMake() map[string]*schema.Schema { } } -func resourceImage() *schema.Resource { +func ResourceImage() *schema.Resource { return &schema.Resource{ SchemaVersion: 1, - Create: resourceImageCreate, - Read: resourceImageRead, - Update: resourceImageEdit, - Delete: resourceImageDelete, - Exists: resourceImageExists, + CreateContext: resourceImageCreate, + ReadContext: resourceImageRead, + UpdateContext: resourceImageEdit, + DeleteContext: resourceImageDelete, + Exists: resourceImageExists, Importer: &schema.ResourceImporter{ State: schema.ImportStatePassthrough, }, Timeouts: &schema.ResourceTimeout{ - Create: &Timeout60s, - Read: &Timeout30s, - Update: &Timeout60s, - Delete: &Timeout60s, - Default: &Timeout60s, - }, - CustomizeDiff: customdiff.All( - customdiff.IfValueChange("enabled", func(old, new, meta interface{}) bool { - return old.(bool) != new.(bool) - }, resourceImageChangeEnabled), - customdiff.IfValueChange("name", func(old, new, meta interface{}) bool { - return old.(string) != new.(string) && old.(string) != "" - }, resourceImageEditName), - customdiff.IfValueChange("shared_with", func(old, new, meta interface{}) bool { - o := old.([]interface{}) - n := new.([]interface{}) - - if len(o) != len(n) { - return true - } else if len(o) == 0 { - return false - } - - count := 0 - for i, v := range n { - if v.(int) == o[i].(int) { - count++ - } - } - return count == 0 - }, resourceImageShare), - customdiff.IfValueChange("computeci_id", func(old, new, meta interface{}) bool { - return old.(int) != new.(int) - }, resourceImageChangeComputeci), - customdiff.IfValueChange("enabled_stacks", func(old, new, meta interface{}) bool { - o := old.([]interface{}) - n := new.([]interface{}) - - if len(o) != len(n) { - return true - } else if len(o) == 0 { - return false - } - count := 0 - for i, v := range n { - if v.(string) == o[i].(string) { - count++ - } - } - return count == 0 - }, resourceImageUpdateNodes), - ), + Create: &constants.Timeout60s, + Read: &constants.Timeout30s, + Update: &constants.Timeout60s, + Delete: &constants.Timeout60s, + Default: &constants.Timeout60s, + }, Schema: resourceImageSchemaMake(), } diff --git a/decort/resource_virtual_image.go b/internal/service/cloudbroker/image/resource_virtual_image.go similarity index 70% rename from decort/resource_virtual_image.go rename to internal/service/cloudbroker/image/resource_virtual_image.go index 5097db1..f778367 100644 --- a/decort/resource_virtual_image.go +++ b/internal/service/cloudbroker/image/resource_virtual_image.go @@ -1,6 +1,8 @@ /* Copyright (c) 2019-2022 Digital Energy Cloud Solutions LLC. All Rights Reserved. -Author: Stanislav Solovev, +Authors: +Petr Krutov, +Stanislav Solovev, Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. @@ -16,34 +18,42 @@ limitations under the License. */ /* -This file is part of Terraform (by Hashicorp) provider for Digital Energy Cloud Orchestration -Technology platfom. +Terraform DECORT provider - manage resources provided by DECORT (Digital Energy Cloud +Orchestration Technology) with Terraform by Hashicorp. -Visit https://github.com/rudecs/terraform-provider-decort for full source code package and updates. +Source code: https://github.com/rudecs/terraform-provider-decort + +Please see README.md to learn where to place source code so that it +builds seamlessly. + +Documentation: https://github.com/rudecs/terraform-provider-decort/wiki */ -package decort +package image import ( + "context" "net/url" "strconv" - "github.com/hashicorp/terraform-plugin-sdk/helper/customdiff" - "github.com/hashicorp/terraform-plugin-sdk/helper/schema" + "github.com/hashicorp/terraform-plugin-sdk/v2/diag" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" + "github.com/rudecs/terraform-provider-decort/internal/constants" + "github.com/rudecs/terraform-provider-decort/internal/controller" log "github.com/sirupsen/logrus" ) -func resourceVirtualImageCreate(d *schema.ResourceData, m interface{}) error { +func resourceVirtualImageCreate(ctx context.Context, d *schema.ResourceData, m interface{}) diag.Diagnostics { log.Debugf("resourceImageCreate: called for image %s", d.Get("name").(string)) - controller := m.(*ControllerCfg) + c := m.(*controller.ControllerCfg) urlValues := &url.Values{} urlValues.Add("name", d.Get("name").(string)) urlValues.Add("targetId", strconv.Itoa(d.Get("target_id").(int))) - imageId, err := controller.decortAPICall("POST", imageCreateVirtualAPI, urlValues) + imageId, err := c.DecortAPICall("POST", imageCreateVirtualAPI, urlValues) if err != nil { - return err + return diag.FromErr(err) } d.SetId(imageId) @@ -51,16 +61,16 @@ func resourceVirtualImageCreate(d *schema.ResourceData, m interface{}) error { image, err := utilityImageCheckPresence(d, m) if err != nil { - return err + return diag.FromErr(err) } d.SetId(strconv.Itoa(image.ImageId)) d.Set("bootable", image.Bootable) //d.Set("image_id", image.ImageId) - err = resourceImageRead(d, m) - if err != nil { - return err + diagnostics := resourceImageRead(ctx, d, m) + if diagnostics != nil { + return diagnostics } return nil @@ -308,77 +318,28 @@ func resourceVirtualImageSchemaMake() map[string]*schema.Schema { } } -func resourceVirtualImage() *schema.Resource { +func ResourceVirtualImage() *schema.Resource { return &schema.Resource{ SchemaVersion: 1, - Create: resourceVirtualImageCreate, - Read: resourceImageRead, - Update: resourceImageEdit, - Delete: resourceImageDelete, - Exists: resourceImageExists, + CreateContext: resourceVirtualImageCreate, + ReadContext: resourceImageRead, + UpdateContext: resourceImageEdit, + DeleteContext: resourceImageDelete, + Exists: resourceImageExists, Importer: &schema.ResourceImporter{ State: schema.ImportStatePassthrough, }, Timeouts: &schema.ResourceTimeout{ - Create: &Timeout60s, - Read: &Timeout30s, - Update: &Timeout60s, - Delete: &Timeout60s, - Default: &Timeout60s, + Create: &constants.Timeout60s, + Read: &constants.Timeout30s, + Update: &constants.Timeout60s, + Delete: &constants.Timeout60s, + Default: &constants.Timeout60s, }, - CustomizeDiff: customdiff.All( - customdiff.IfValueChange("enabled", func(old, new, meta interface{}) bool { - return old.(bool) != new.(bool) - }, resourceImageChangeEnabled), - customdiff.IfValueChange("link_to", func(old, new, meta interface{}) bool { - return old.(int) != new.(int) - }, resourceImageLink), - customdiff.IfValueChange("name", func(old, new, meta interface{}) bool { - return old.(string) != new.(string) && old.(string) != "" - }, resourceImageEditName), - customdiff.IfValueChange("shared_with", func(old, new, meta interface{}) bool { - o := old.([]interface{}) - n := new.([]interface{}) - - if len(o) != len(n) { - return true - } else if len(o) == 0 { - return false - } - count := 0 - for i, v := range n { - if v.(int) == o[i].(int) { - count++ - } - } - return count == 0 - }, resourceImageShare), - customdiff.IfValueChange("computeci_id", func(old, new, meta interface{}) bool { - return old.(int) != new.(int) - }, resourceImageChangeComputeci), - customdiff.IfValueChange("enabled_stacks", func(old, new, meta interface{}) bool { - o := old.([]interface{}) - n := new.([]interface{}) - - if len(o) != len(n) { - return true - } else if len(o) == 0 { - return false - } - count := 0 - for i, v := range n { - if v.(string) == o[i].(string) { - count++ - } - } - return count == 0 - }, resourceImageUpdateNodes), - ), - Schema: resourceVirtualImageSchemaMake(), } } diff --git a/decort/utility_image.go b/internal/service/cloudbroker/image/utility_image.go similarity index 61% rename from decort/utility_image.go rename to internal/service/cloudbroker/image/utility_image.go index 3b20243..10c30ed 100644 --- a/decort/utility_image.go +++ b/internal/service/cloudbroker/image/utility_image.go @@ -1,6 +1,8 @@ /* Copyright (c) 2019-2022 Digital Energy Cloud Solutions LLC. All Rights Reserved. -Author: Stanislav Solovev, +Authors: +Petr Krutov, +Stanislav Solovev, Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. @@ -16,13 +18,18 @@ limitations under the License. */ /* -This file is part of Terraform (by Hashicorp) provider for Digital Energy Cloud Orchestration -Technology platfom. +Terraform DECORT provider - manage resources provided by DECORT (Digital Energy Cloud +Orchestration Technology) with Terraform by Hashicorp. -Visit https://github.com/rudecs/terraform-provider-decort for full source code package and updates. +Source code: https://github.com/rudecs/terraform-provider-decort + +Please see README.md to learn where to place source code so that it +builds seamlessly. + +Documentation: https://github.com/rudecs/terraform-provider-decort/wiki */ -package decort +package image import ( "encoding/json" @@ -31,11 +38,12 @@ import ( "net/url" "strconv" - "github.com/hashicorp/terraform-plugin-sdk/helper/schema" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" + "github.com/rudecs/terraform-provider-decort/internal/controller" ) func utilityImageCheckPresence(d *schema.ResourceData, m interface{}) (*Image, error) { - controller := m.(*ControllerCfg) + c := m.(*controller.ControllerCfg) urlValues := &url.Values{} if (strconv.Itoa(d.Get("image_id").(int))) != "0" { @@ -44,7 +52,7 @@ func utilityImageCheckPresence(d *schema.ResourceData, m interface{}) (*Image, e urlValues.Add("imageId", d.Id()) } - resp, err := controller.decortAPICall("POST", imageGetAPI, urlValues) + resp, err := c.DecortAPICall("POST", imageGetAPI, urlValues) if err != nil { return nil, err } diff --git a/decort/utility_image_list.go b/internal/service/cloudbroker/image/utility_image_list.go similarity index 64% rename from decort/utility_image_list.go rename to internal/service/cloudbroker/image/utility_image_list.go index bc80677..dffabdf 100644 --- a/decort/utility_image_list.go +++ b/internal/service/cloudbroker/image/utility_image_list.go @@ -1,6 +1,8 @@ /* Copyright (c) 2019-2022 Digital Energy Cloud Solutions LLC. All Rights Reserved. -Author: Stanislav Solovev, , +Authors: +Petr Krutov, +Stanislav Solovev, Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. @@ -16,27 +18,33 @@ limitations under the License. */ /* -This file is part of Terraform (by Hashicorp) provider for Digital Energy Cloud Orchestration -Technology platfom. +Terraform DECORT provider - manage resources provided by DECORT (Digital Energy Cloud +Orchestration Technology) with Terraform by Hashicorp. -Visit https://github.com/rudecs/terraform-provider-decort for full source code package and updates. +Source code: https://github.com/rudecs/terraform-provider-decort + +Please see README.md to learn where to place source code so that it +builds seamlessly. + +Documentation: https://github.com/rudecs/terraform-provider-decort/wiki */ -package decort +package image import ( "encoding/json" "net/url" "strconv" + "github.com/rudecs/terraform-provider-decort/internal/controller" log "github.com/sirupsen/logrus" - "github.com/hashicorp/terraform-plugin-sdk/helper/schema" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" ) func utilityImageListCheckPresence(d *schema.ResourceData, m interface{}) (ImageList, error) { imageList := ImageList{} - controller := m.(*ControllerCfg) + c := m.(*controller.ControllerCfg) urlValues := &url.Values{} if sepId, ok := d.GetOk("sep_id"); ok { @@ -54,7 +62,7 @@ func utilityImageListCheckPresence(d *schema.ResourceData, m interface{}) (Image } log.Debugf("utilityImageListCheckPresence: load image list") - imageListRaw, err := controller.decortAPICall("POST", imageListGetAPI, urlValues) + imageListRaw, err := c.DecortAPICall("POST", imageListGetAPI, urlValues) if err != nil { return nil, err } diff --git a/decort/utility_image_list_stacks.go b/internal/service/cloudbroker/image/utility_image_list_stacks.go similarity index 59% rename from decort/utility_image_list_stacks.go rename to internal/service/cloudbroker/image/utility_image_list_stacks.go index c2ebd10..8062078 100644 --- a/decort/utility_image_list_stacks.go +++ b/internal/service/cloudbroker/image/utility_image_list_stacks.go @@ -1,6 +1,8 @@ /* Copyright (c) 2019-2022 Digital Energy Cloud Solutions LLC. All Rights Reserved. -Author: Stanislav Solovev, , +Authors: +Petr Krutov, +Stanislav Solovev, Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. @@ -16,33 +18,39 @@ limitations under the License. */ /* -This file is part of Terraform (by Hashicorp) provider for Digital Energy Cloud Orchestration -Technology platfom. +Terraform DECORT provider - manage resources provided by DECORT (Digital Energy Cloud +Orchestration Technology) with Terraform by Hashicorp. -Visit https://github.com/rudecs/terraform-provider-decort for full source code package and updates. +Source code: https://github.com/rudecs/terraform-provider-decort + +Please see README.md to learn where to place source code so that it +builds seamlessly. + +Documentation: https://github.com/rudecs/terraform-provider-decort/wiki */ -package decort +package image import ( "encoding/json" "net/url" "strconv" + "github.com/rudecs/terraform-provider-decort/internal/controller" log "github.com/sirupsen/logrus" - "github.com/hashicorp/terraform-plugin-sdk/helper/schema" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" ) func utilityImageListStacksCheckPresence(d *schema.ResourceData, m interface{}) (ImageListStacks, error) { imageListStacks := ImageListStacks{} - controller := m.(*ControllerCfg) + c := m.(*controller.ControllerCfg) urlValues := &url.Values{} urlValues.Add("imageId", strconv.Itoa(d.Get("image_id").(int))) log.Debugf("utilityImageListStacksCheckPresence: load image list") - imageListRaw, err := controller.decortAPICall("POST", imageListStacksApi, urlValues) + imageListRaw, err := c.DecortAPICall("POST", imageListStacksApi, urlValues) if err != nil { return nil, err } diff --git a/internal/service/cloudbroker/pcidevice/api.go b/internal/service/cloudbroker/pcidevice/api.go new file mode 100644 index 0000000..02a466a --- /dev/null +++ b/internal/service/cloudbroker/pcidevice/api.go @@ -0,0 +1,38 @@ +/* +Copyright (c) 2019-2022 Digital Energy Cloud Solutions LLC. All Rights Reserved. +Authors: +Petr Krutov, +Stanislav Solovev, + +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. +*/ + +/* +Terraform DECORT provider - manage resources provided by DECORT (Digital Energy Cloud +Orchestration Technology) with Terraform by Hashicorp. + +Source code: https://github.com/rudecs/terraform-provider-decort + +Please see README.md to learn where to place source code so that it +builds seamlessly. + +Documentation: https://github.com/rudecs/terraform-provider-decort/wiki +*/ + +package pcidevice + +const pcideviceListAPI = "/restmachine/cloudbroker/pcidevice/list" +const pcideviceDisableAPI = "/restmachine/cloudbroker/pcidevice/disable" +const pcideviceEnableAPI = "/restmachine/cloudbroker/pcidevice/enable" +const pcideviceCreateAPI = "/restmachine/cloudbroker/pcidevice/create" +const pcideviceDeleteAPI = "/restmachine/cloudbroker/pcidevice/delete" diff --git a/decort/data_source_pcidevice.go b/internal/service/cloudbroker/pcidevice/data_source_pcidevice.go similarity index 65% rename from decort/data_source_pcidevice.go rename to internal/service/cloudbroker/pcidevice/data_source_pcidevice.go index e3fa314..880ff91 100644 --- a/decort/data_source_pcidevice.go +++ b/internal/service/cloudbroker/pcidevice/data_source_pcidevice.go @@ -1,6 +1,8 @@ /* Copyright (c) 2019-2022 Digital Energy Cloud Solutions LLC. All Rights Reserved. -Author: Stanislav Solovev, , +Authors: +Petr Krutov, +Stanislav Solovev, Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. @@ -16,28 +18,37 @@ limitations under the License. */ /* -This file is part of Terraform (by Hashicorp) provider for Digital Energy Cloud Orchestration -Technology platfom. +Terraform DECORT provider - manage resources provided by DECORT (Digital Energy Cloud +Orchestration Technology) with Terraform by Hashicorp. -Visit https://github.com/rudecs/terraform-provider-decort for full source code package and updates. +Source code: https://github.com/rudecs/terraform-provider-decort + +Please see README.md to learn where to place source code so that it +builds seamlessly. + +Documentation: https://github.com/rudecs/terraform-provider-decort/wiki */ -package decort +package pcidevice import ( + "context" "strconv" - "github.com/hashicorp/terraform-plugin-sdk/helper/schema" + "github.com/hashicorp/terraform-plugin-sdk/v2/diag" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" + "github.com/rudecs/terraform-provider-decort/internal/constants" + "github.com/rudecs/terraform-provider-decort/internal/flattens" ) -func dataSourcePcideviceRead(d *schema.ResourceData, m interface{}) error { +func dataSourcePcideviceRead(ctx context.Context, d *schema.ResourceData, m interface{}) diag.Diagnostics { pcidevice, err := utilityPcideviceCheckPresence(d, m) if err != nil { - return err + return diag.FromErr(err) } d.Set("ckey", pcidevice.CKey) - d.Set("meta", flattenMeta(pcidevice.Meta)) + d.Set("meta", flattens.FlattenMeta(pcidevice.Meta)) d.Set("compute_id", pcidevice.Computeid) d.Set("description", pcidevice.Description) d.Set("guid", pcidevice.Guid) @@ -112,15 +123,15 @@ func dataSourcePcideviceSchemaMake() map[string]*schema.Schema { return rets } -func dataSourcePcidevice() *schema.Resource { +func DataSourcePcidevice() *schema.Resource { return &schema.Resource{ SchemaVersion: 1, - Read: dataSourcePcideviceRead, + ReadContext: dataSourcePcideviceRead, Timeouts: &schema.ResourceTimeout{ - Read: &Timeout30s, - Default: &Timeout60s, + Read: &constants.Timeout30s, + Default: &constants.Timeout60s, }, Schema: dataSourcePcideviceSchemaMake(), diff --git a/decort/data_source_pcidevice_list.go b/internal/service/cloudbroker/pcidevice/data_source_pcidevice_list.go similarity index 69% rename from decort/data_source_pcidevice_list.go rename to internal/service/cloudbroker/pcidevice/data_source_pcidevice_list.go index 2ee469d..b570cbf 100644 --- a/decort/data_source_pcidevice_list.go +++ b/internal/service/cloudbroker/pcidevice/data_source_pcidevice_list.go @@ -1,6 +1,8 @@ /* Copyright (c) 2019-2022 Digital Energy Cloud Solutions LLC. All Rights Reserved. -Author: Stanislav Solovev, , +Authors: +Petr Krutov, +Stanislav Solovev, Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. @@ -16,17 +18,27 @@ limitations under the License. */ /* -This file is part of Terraform (by Hashicorp) provider for Digital Energy Cloud Orchestration -Technology platfom. +Terraform DECORT provider - manage resources provided by DECORT (Digital Energy Cloud +Orchestration Technology) with Terraform by Hashicorp. -Visit https://github.com/rudecs/terraform-provider-decort for full source code package and updates. +Source code: https://github.com/rudecs/terraform-provider-decort + +Please see README.md to learn where to place source code so that it +builds seamlessly. + +Documentation: https://github.com/rudecs/terraform-provider-decort/wiki */ -package decort +package pcidevice import ( + "context" + "github.com/google/uuid" - "github.com/hashicorp/terraform-plugin-sdk/helper/schema" + "github.com/hashicorp/terraform-plugin-sdk/v2/diag" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" + "github.com/rudecs/terraform-provider-decort/internal/constants" + "github.com/rudecs/terraform-provider-decort/internal/flattens" ) func flattenPcideviceList(pl PcideviceList) []map[string]interface{} { @@ -34,7 +46,7 @@ func flattenPcideviceList(pl PcideviceList) []map[string]interface{} { for _, item := range pl { temp := map[string]interface{}{ "ckey": item.CKey, - "meta": flattenMeta(item.Meta), + "meta": flattens.FlattenMeta(item.Meta), "compute_id": item.Computeid, "description": item.Description, "guid": item.Guid, @@ -51,10 +63,10 @@ func flattenPcideviceList(pl PcideviceList) []map[string]interface{} { return res } -func dataSourcePcideviceListRead(d *schema.ResourceData, m interface{}) error { +func dataSourcePcideviceListRead(ctx context.Context, d *schema.ResourceData, m interface{}) diag.Diagnostics { pcideviceList, err := utilityPcideviceListCheckPresence(d, m) if err != nil { - return err + return diag.FromErr(err) } d.Set("items", flattenPcideviceList(pcideviceList)) @@ -136,15 +148,15 @@ func dataSourcePcideviceListSchemaMake() map[string]*schema.Schema { return rets } -func dataSourcePcideviceList() *schema.Resource { +func DataSourcePcideviceList() *schema.Resource { return &schema.Resource{ SchemaVersion: 1, - Read: dataSourcePcideviceListRead, + ReadContext: dataSourcePcideviceListRead, Timeouts: &schema.ResourceTimeout{ - Read: &Timeout30s, - Default: &Timeout60s, + Read: &constants.Timeout30s, + Default: &constants.Timeout60s, }, Schema: dataSourcePcideviceListSchemaMake(), diff --git a/internal/service/cloudbroker/pcidevice/models.go b/internal/service/cloudbroker/pcidevice/models.go new file mode 100644 index 0000000..f6dc1f8 --- /dev/null +++ b/internal/service/cloudbroker/pcidevice/models.go @@ -0,0 +1,49 @@ +/* +Copyright (c) 2019-2022 Digital Energy Cloud Solutions LLC. All Rights Reserved. +Authors: +Petr Krutov, +Stanislav Solovev, + +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. +*/ + +/* +Terraform DECORT provider - manage resources provided by DECORT (Digital Energy Cloud +Orchestration Technology) with Terraform by Hashicorp. + +Source code: https://github.com/rudecs/terraform-provider-decort + +Please see README.md to learn where to place source code so that it +builds seamlessly. + +Documentation: https://github.com/rudecs/terraform-provider-decort/wiki +*/ + +package pcidevice + +type Pcidevice struct { + CKey string `json:"_ckey"` + Meta []interface{} `json:"_meta"` + Computeid int `json:"computeId"` + Description string `json:"description"` + Guid int `json:"guid"` + HwPath string `json:"hwPath"` + ID int `json:"id"` + Name string `json:"name"` + RgID int `json:"rgId"` + StackID int `json:"stackId"` + Status string `json:"status"` + SystemName string `json:"systemName"` +} + +type PcideviceList []Pcidevice diff --git a/decort/resource_pcidevice.go b/internal/service/cloudbroker/pcidevice/resource_pcidevice.go similarity index 61% rename from decort/resource_pcidevice.go rename to internal/service/cloudbroker/pcidevice/resource_pcidevice.go index 470ddb1..63408a2 100644 --- a/decort/resource_pcidevice.go +++ b/internal/service/cloudbroker/pcidevice/resource_pcidevice.go @@ -1,6 +1,8 @@ /* Copyright (c) 2019-2022 Digital Energy Cloud Solutions LLC. All Rights Reserved. -Author: Stanislav Solovev, +Authors: +Petr Krutov, +Stanislav Solovev, Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. @@ -16,43 +18,52 @@ limitations under the License. */ /* -This file is part of Terraform (by Hashicorp) provider for Digital Energy Cloud Orchestration -Technology platfom. +Terraform DECORT provider - manage resources provided by DECORT (Digital Energy Cloud +Orchestration Technology) with Terraform by Hashicorp. -Visit https://github.com/rudecs/terraform-provider-decort for full source code package and updates. +Source code: https://github.com/rudecs/terraform-provider-decort + +Please see README.md to learn where to place source code so that it +builds seamlessly. + +Documentation: https://github.com/rudecs/terraform-provider-decort/wiki */ -package decort +package pcidevice import ( - "errors" + "context" "net/url" "strconv" - "github.com/hashicorp/terraform-plugin-sdk/helper/schema" + "github.com/hashicorp/terraform-plugin-sdk/v2/diag" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" + "github.com/rudecs/terraform-provider-decort/internal/constants" + "github.com/rudecs/terraform-provider-decort/internal/controller" + "github.com/rudecs/terraform-provider-decort/internal/flattens" log "github.com/sirupsen/logrus" ) -func resourcePcideviceCreate(d *schema.ResourceData, m interface{}) error { +func resourcePcideviceCreate(ctx context.Context, d *schema.ResourceData, m interface{}) diag.Diagnostics { log.Debugf("resourcePcideviceCreate: called for pcidevice %s", d.Get("name").(string)) if deviceId, ok := d.GetOk("device_id"); ok { if exists, err := resourcePcideviceExists(d, m); exists { if err != nil { - return err + return diag.FromErr(err) } d.SetId(strconv.Itoa(deviceId.(int))) - err = resourcePcideviceRead(d, m) - if err != nil { - return err + diagnostics := resourcePcideviceRead(ctx, d, m) + if diagnostics != nil { + return diagnostics } return nil } - return errors.New("provided device id does not exist") + return diag.Errorf("provided device id does not exist") } - controller := m.(*ControllerCfg) + c := m.(*controller.ControllerCfg) urlValues := &url.Values{} urlValues.Add("name", d.Get("name").(string)) urlValues.Add("hwPath", d.Get("hw_path").(string)) @@ -63,31 +74,31 @@ func resourcePcideviceCreate(d *schema.ResourceData, m interface{}) error { urlValues.Add("description", description.(string)) } - pcideviceId, err := controller.decortAPICall("POST", pcideviceCreateAPI, urlValues) + pcideviceId, err := c.DecortAPICall("POST", pcideviceCreateAPI, urlValues) if err != nil { - return err + return diag.FromErr(err) } d.SetId(pcideviceId) d.Set("device_id", pcideviceId) - err = resourcePcideviceRead(d, m) - if err != nil { - return err + diagnostics := resourcePcideviceRead(ctx, d, m) + if diagnostics != nil { + return diagnostics } return nil } -func resourcePcideviceRead(d *schema.ResourceData, m interface{}) error { +func resourcePcideviceRead(ctx context.Context, d *schema.ResourceData, m interface{}) diag.Diagnostics { pcidevice, err := utilityPcideviceCheckPresence(d, m) if err != nil { - return err + return diag.FromErr(err) } d.SetId(strconv.Itoa(pcidevice.ID)) d.Set("ckey", pcidevice.CKey) - d.Set("meta", flattenMeta(pcidevice.Meta)) + d.Set("meta", flattens.FlattenMeta(pcidevice.Meta)) d.Set("compute_id", pcidevice.Computeid) d.Set("description", pcidevice.Description) d.Set("guid", pcidevice.Guid) @@ -102,17 +113,17 @@ func resourcePcideviceRead(d *schema.ResourceData, m interface{}) error { return nil } -func resourcePcideviceDelete(d *schema.ResourceData, m interface{}) error { +func resourcePcideviceDelete(ctx context.Context, d *schema.ResourceData, m interface{}) diag.Diagnostics { log.Debugf("resourcePcideviceDelete: called for %s, id: %s", d.Get("name").(string), d.Id()) - controller := m.(*ControllerCfg) + c := m.(*controller.ControllerCfg) urlValues := &url.Values{} urlValues.Add("deviceId", d.Id()) urlValues.Add("force", strconv.FormatBool(d.Get("force").(bool))) - _, err := controller.decortAPICall("POST", pcideviceDeleteAPI, urlValues) + _, err := c.DecortAPICall("POST", pcideviceDeleteAPI, urlValues) if err != nil { - return err + return diag.FromErr(err) } d.SetId("") @@ -132,10 +143,10 @@ func resourcePcideviceExists(d *schema.ResourceData, m interface{}) (bool, error return true, nil } -func resourcePcideviceEdit(d *schema.ResourceData, m interface{}) error { +func resourcePcideviceEdit(ctx context.Context, d *schema.ResourceData, m interface{}) diag.Diagnostics { if d.HasChange("enable") { state := d.Get("enable").(bool) - c := m.(*ControllerCfg) + c := m.(*controller.ControllerCfg) urlValues := &url.Values{} api := "" @@ -147,15 +158,15 @@ func resourcePcideviceEdit(d *schema.ResourceData, m interface{}) error { api = pcideviceDisableAPI } - _, err := c.decortAPICall("POST", api, urlValues) + _, err := c.DecortAPICall("POST", api, urlValues) if err != nil { - return err + return diag.FromErr(err) } } - err := resourcePcideviceRead(d, m) - if err != nil { - return err + diagnostics := resourcePcideviceRead(ctx, d, m) + if diagnostics != nil { + return diagnostics } return nil @@ -236,26 +247,26 @@ func resourcePcideviceSchemaMake() map[string]*schema.Schema { } } -func resourcePcidevice() *schema.Resource { +func ResourcePcidevice() *schema.Resource { return &schema.Resource{ SchemaVersion: 1, - Create: resourcePcideviceCreate, - Read: resourcePcideviceRead, - Update: resourcePcideviceEdit, - Delete: resourcePcideviceDelete, - Exists: resourcePcideviceExists, + CreateContext: resourcePcideviceCreate, + ReadContext: resourcePcideviceRead, + UpdateContext: resourcePcideviceEdit, + DeleteContext: resourcePcideviceDelete, + Exists: resourcePcideviceExists, Importer: &schema.ResourceImporter{ State: schema.ImportStatePassthrough, }, Timeouts: &schema.ResourceTimeout{ - Create: &Timeout60s, - Read: &Timeout30s, - Update: &Timeout60s, - Delete: &Timeout60s, - Default: &Timeout60s, + Create: &constants.Timeout60s, + Read: &constants.Timeout30s, + Update: &constants.Timeout60s, + Delete: &constants.Timeout60s, + Default: &constants.Timeout60s, }, Schema: resourcePcideviceSchemaMake(), diff --git a/decort/utility_pcidevice.go b/internal/service/cloudbroker/pcidevice/utility_pcidevice.go similarity index 64% rename from decort/utility_pcidevice.go rename to internal/service/cloudbroker/pcidevice/utility_pcidevice.go index 5709ea0..fb4ffcd 100644 --- a/decort/utility_pcidevice.go +++ b/internal/service/cloudbroker/pcidevice/utility_pcidevice.go @@ -1,6 +1,8 @@ /* Copyright (c) 2019-2022 Digital Energy Cloud Solutions LLC. All Rights Reserved. -Author: Stanislav Solovev, , +Authors: +Petr Krutov, +Stanislav Solovev, Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. @@ -16,18 +18,23 @@ limitations under the License. */ /* -This file is part of Terraform (by Hashicorp) provider for Digital Energy Cloud Orchestration -Technology platfom. +Terraform DECORT provider - manage resources provided by DECORT (Digital Energy Cloud +Orchestration Technology) with Terraform by Hashicorp. -Visit https://github.com/rudecs/terraform-provider-decort for full source code package and updates. +Source code: https://github.com/rudecs/terraform-provider-decort + +Please see README.md to learn where to place source code so that it +builds seamlessly. + +Documentation: https://github.com/rudecs/terraform-provider-decort/wiki */ -package decort +package pcidevice import ( "strconv" - "github.com/hashicorp/terraform-plugin-sdk/helper/schema" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" ) func utilityPcideviceCheckPresence(d *schema.ResourceData, m interface{}) (*Pcidevice, error) { diff --git a/decort/utility_pcidevice_list.go b/internal/service/cloudbroker/pcidevice/utility_pcidevice_list.go similarity index 55% rename from decort/utility_pcidevice_list.go rename to internal/service/cloudbroker/pcidevice/utility_pcidevice_list.go index e4f7580..1dd503d 100644 --- a/decort/utility_pcidevice_list.go +++ b/internal/service/cloudbroker/pcidevice/utility_pcidevice_list.go @@ -1,6 +1,8 @@ /* Copyright (c) 2019-2022 Digital Energy Cloud Solutions LLC. All Rights Reserved. -Author: Stanislav Solovev, , +Authors: +Petr Krutov, +Stanislav Solovev, Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. @@ -16,27 +18,33 @@ limitations under the License. */ /* -This file is part of Terraform (by Hashicorp) provider for Digital Energy Cloud Orchestration -Technology platfom. +Terraform DECORT provider - manage resources provided by DECORT (Digital Energy Cloud +Orchestration Technology) with Terraform by Hashicorp. -Visit https://github.com/rudecs/terraform-provider-decort for full source code package and updates. +Source code: https://github.com/rudecs/terraform-provider-decort + +Please see README.md to learn where to place source code so that it +builds seamlessly. + +Documentation: https://github.com/rudecs/terraform-provider-decort/wiki */ -package decort +package pcidevice import ( "encoding/json" "net/url" - "github.com/hashicorp/terraform-plugin-sdk/helper/schema" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" + "github.com/rudecs/terraform-provider-decort/internal/controller" ) func utilityPcideviceListCheckPresence(_ *schema.ResourceData, m interface{}) (PcideviceList, error) { pcideviceList := PcideviceList{} - controller := m.(*ControllerCfg) + c := m.(*controller.ControllerCfg) urlValues := &url.Values{} - pcideviceListRaw, err := controller.decortAPICall("POST", pcideviceListAPI, urlValues) + pcideviceListRaw, err := c.DecortAPICall("POST", pcideviceListAPI, urlValues) if err != nil { return nil, err } diff --git a/internal/service/cloudbroker/sep/api.go b/internal/service/cloudbroker/sep/api.go new file mode 100644 index 0000000..5febab6 --- /dev/null +++ b/internal/service/cloudbroker/sep/api.go @@ -0,0 +1,59 @@ +/* +Copyright (c) 2019-2022 Digital Energy Cloud Solutions LLC. All Rights Reserved. +Authors: +Petr Krutov, +Stanislav Solovev, + +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. +*/ + +/* +Terraform DECORT provider - manage resources provided by DECORT (Digital Energy Cloud +Orchestration Technology) with Terraform by Hashicorp. + +Source code: https://github.com/rudecs/terraform-provider-decort + +Please see README.md to learn where to place source code so that it +builds seamlessly. + +Documentation: https://github.com/rudecs/terraform-provider-decort/wiki +*/ + +package sep + +const sepAddConsumerNodesAPI = "/restmachine/cloudbroker/sep/addConsumerNodes" +const sepDelConsumerNodesAPI = "/restmachine/cloudbroker/sep/delConsumerNodes" +const sepAddProviderNodesAPI = "/restmachine/cloudbroker/sep/addProviderNodes" + +const sepConfigFieldEditAPI = "/restmachine/cloudbroker/sep/configFieldEdit" +const sepConfigInsertAPI = "/restmachine/cloudbroker/sep/configInsert" +const sepConfigValidateAPI = "/restmachine/cloudbroker/sep/configValidate" + +const sepConsumptionAPI = "/restmachine/cloudbroker/sep/consumption" + +const sepDecommissionAPI = "/restmachine/cloudbroker/sep/decommission" + +const sepEnableAPI = "/restmachine/cloudbroker/sep/enable" +const sepDisableAPI = "/restmachine/cloudbroker/sep/disable" + +const sepDiskListAPI = "/restmachine/cloudbroker/sep/diskList" + +const sepGetAPI = "/restmachine/cloudbroker/sep/get" +const sepGetConfigAPI = "/restmachine/cloudbroker/sep/getConfig" +const sepGetPoolAPI = "/restmachine/cloudbroker/sep/getPool" + +const sepCreateAPI = "/restmachine/cloudbroker/sep/create" +const sepDeleteAPI = "/restmachine/cloudbroker/sep/delete" +const sepListAPI = "/restmachine/cloudbroker/sep/list" + +const sepUpdateCapacityLimitAPI = "/restmachine/cloudbroker/sep/updateCapacityLimit" diff --git a/decort/data_source_sep.go b/internal/service/cloudbroker/sep/data_source_sep.go similarity index 68% rename from decort/data_source_sep.go rename to internal/service/cloudbroker/sep/data_source_sep.go index 4dab665..76d3ea8 100644 --- a/decort/data_source_sep.go +++ b/internal/service/cloudbroker/sep/data_source_sep.go @@ -1,6 +1,8 @@ /* Copyright (c) 2019-2022 Digital Energy Cloud Solutions LLC. All Rights Reserved. -Author: Stanislav Solovev, , +Authors: +Petr Krutov, +Stanislav Solovev, Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. @@ -16,31 +18,40 @@ limitations under the License. */ /* -This file is part of Terraform (by Hashicorp) provider for Digital Energy Cloud Orchestration -Technology platfom. +Terraform DECORT provider - manage resources provided by DECORT (Digital Energy Cloud +Orchestration Technology) with Terraform by Hashicorp. -Visit https://github.com/rudecs/terraform-provider-decort for full source code package and updates. +Source code: https://github.com/rudecs/terraform-provider-decort + +Please see README.md to learn where to place source code so that it +builds seamlessly. + +Documentation: https://github.com/rudecs/terraform-provider-decort/wiki */ -package decort +package sep import ( + "context" "encoding/json" "github.com/google/uuid" - "github.com/hashicorp/terraform-plugin-sdk/helper/schema" + "github.com/hashicorp/terraform-plugin-sdk/v2/diag" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" + "github.com/rudecs/terraform-provider-decort/internal/constants" + "github.com/rudecs/terraform-provider-decort/internal/flattens" ) -func dataSourceSepRead(d *schema.ResourceData, m interface{}) error { +func dataSourceSepRead(ctx context.Context, d *schema.ResourceData, m interface{}) diag.Diagnostics { desSep, err := utilitySepCheckPresence(d, m) if err != nil { - return err + return diag.FromErr(err) } id := uuid.New() d.SetId(id.String()) d.Set("ckey", desSep.Ckey) - d.Set("meta", flattenMeta(desSep.Meta)) + d.Set("meta", flattens.FlattenMeta(desSep.Meta)) d.Set("consumed_by", desSep.ConsumedBy) d.Set("desc", desSep.Desc) d.Set("gid", desSep.Gid) @@ -129,15 +140,15 @@ func dataSourceSepCSchemaMake() map[string]*schema.Schema { } } -func dataSourceSep() *schema.Resource { +func DataSourceSep() *schema.Resource { return &schema.Resource{ SchemaVersion: 1, - Read: dataSourceSepRead, + ReadContext: dataSourceSepRead, Timeouts: &schema.ResourceTimeout{ - Read: &Timeout30s, - Default: &Timeout60s, + Read: &constants.Timeout30s, + Default: &constants.Timeout60s, }, Schema: dataSourceSepCSchemaMake(), diff --git a/decort/data_source_sep_config.go b/internal/service/cloudbroker/sep/data_source_sep_config.go similarity index 56% rename from decort/data_source_sep_config.go rename to internal/service/cloudbroker/sep/data_source_sep_config.go index dcf1ec0..2d8d4ed 100644 --- a/decort/data_source_sep_config.go +++ b/internal/service/cloudbroker/sep/data_source_sep_config.go @@ -1,6 +1,8 @@ /* Copyright (c) 2019-2022 Digital Energy Cloud Solutions LLC. All Rights Reserved. -Author: Stanislav Solovev, , +Authors: +Petr Krutov, +Stanislav Solovev, Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. @@ -16,25 +18,33 @@ limitations under the License. */ /* -This file is part of Terraform (by Hashicorp) provider for Digital Energy Cloud Orchestration -Technology platfom. +Terraform DECORT provider - manage resources provided by DECORT (Digital Energy Cloud +Orchestration Technology) with Terraform by Hashicorp. -Visit https://github.com/rudecs/terraform-provider-decort for full source code package and updates. +Source code: https://github.com/rudecs/terraform-provider-decort + +Please see README.md to learn where to place source code so that it +builds seamlessly. + +Documentation: https://github.com/rudecs/terraform-provider-decort/wiki */ -package decort +package sep import ( + "context" "encoding/json" "github.com/google/uuid" - "github.com/hashicorp/terraform-plugin-sdk/helper/schema" + "github.com/hashicorp/terraform-plugin-sdk/v2/diag" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" + "github.com/rudecs/terraform-provider-decort/internal/constants" ) -func dataSourceSepConfigRead(d *schema.ResourceData, m interface{}) error { +func dataSourceSepConfigRead(ctx context.Context, d *schema.ResourceData, m interface{}) diag.Diagnostics { sepConfig, err := utilitySepConfigCheckPresence(d, m) if err != nil { - return err + return diag.FromErr(err) } id := uuid.New() @@ -61,15 +71,15 @@ func dataSourceSepConfigSchemaMake() map[string]*schema.Schema { } } -func dataSourceSepConfig() *schema.Resource { +func DataSourceSepConfig() *schema.Resource { return &schema.Resource{ SchemaVersion: 1, - Read: dataSourceSepConfigRead, + ReadContext: dataSourceSepConfigRead, Timeouts: &schema.ResourceTimeout{ - Read: &Timeout30s, - Default: &Timeout60s, + Read: &constants.Timeout30s, + Default: &constants.Timeout60s, }, Schema: dataSourceSepConfigSchemaMake(), diff --git a/decort/data_source_sep_consumption.go b/internal/service/cloudbroker/sep/data_source_sep_consumption.go similarity index 78% rename from decort/data_source_sep_consumption.go rename to internal/service/cloudbroker/sep/data_source_sep_consumption.go index bd2c898..c4aa957 100644 --- a/decort/data_source_sep_consumption.go +++ b/internal/service/cloudbroker/sep/data_source_sep_consumption.go @@ -1,6 +1,8 @@ /* Copyright (c) 2019-2022 Digital Energy Cloud Solutions LLC. All Rights Reserved. -Author: Stanislav Solovev, , +Authors: +Petr Krutov, +Stanislav Solovev, Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. @@ -16,23 +18,32 @@ limitations under the License. */ /* -This file is part of Terraform (by Hashicorp) provider for Digital Energy Cloud Orchestration -Technology platfom. +Terraform DECORT provider - manage resources provided by DECORT (Digital Energy Cloud +Orchestration Technology) with Terraform by Hashicorp. -Visit https://github.com/rudecs/terraform-provider-decort for full source code package and updates. +Source code: https://github.com/rudecs/terraform-provider-decort + +Please see README.md to learn where to place source code so that it +builds seamlessly. + +Documentation: https://github.com/rudecs/terraform-provider-decort/wiki */ -package decort +package sep import ( + "context" + "github.com/google/uuid" - "github.com/hashicorp/terraform-plugin-sdk/helper/schema" + "github.com/hashicorp/terraform-plugin-sdk/v2/diag" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" + "github.com/rudecs/terraform-provider-decort/internal/constants" ) -func dataSourceSepConsumptionRead(d *schema.ResourceData, m interface{}) error { +func dataSourceSepConsumptionRead(ctx context.Context, d *schema.ResourceData, m interface{}) diag.Diagnostics { sepCons, err := utilitySepConsumptionCheckPresence(d, m) if err != nil { - return err + return diag.FromErr(err) } id := uuid.New() d.SetId(id.String()) @@ -179,15 +190,15 @@ func dataSourceSepConsumptionSchemaMake() map[string]*schema.Schema { } } -func dataSourceSepConsumption() *schema.Resource { +func DataSourceSepConsumption() *schema.Resource { return &schema.Resource{ SchemaVersion: 1, - Read: dataSourceSepConsumptionRead, + ReadContext: dataSourceSepConsumptionRead, Timeouts: &schema.ResourceTimeout{ - Read: &Timeout30s, - Default: &Timeout60s, + Read: &constants.Timeout30s, + Default: &constants.Timeout60s, }, Schema: dataSourceSepConsumptionSchemaMake(), diff --git a/decort/data_source_sep_disk_list.go b/internal/service/cloudbroker/sep/data_source_sep_disk_list.go similarity index 58% rename from decort/data_source_sep_disk_list.go rename to internal/service/cloudbroker/sep/data_source_sep_disk_list.go index 128aa22..8e0fe92 100644 --- a/decort/data_source_sep_disk_list.go +++ b/internal/service/cloudbroker/sep/data_source_sep_disk_list.go @@ -1,6 +1,8 @@ /* Copyright (c) 2019-2022 Digital Energy Cloud Solutions LLC. All Rights Reserved. -Author: Stanislav Solovev, , +Authors: +Petr Krutov, +Stanislav Solovev, Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. @@ -16,23 +18,32 @@ limitations under the License. */ /* -This file is part of Terraform (by Hashicorp) provider for Digital Energy Cloud Orchestration -Technology platfom. +Terraform DECORT provider - manage resources provided by DECORT (Digital Energy Cloud +Orchestration Technology) with Terraform by Hashicorp. -Visit https://github.com/rudecs/terraform-provider-decort for full source code package and updates. +Source code: https://github.com/rudecs/terraform-provider-decort + +Please see README.md to learn where to place source code so that it +builds seamlessly. + +Documentation: https://github.com/rudecs/terraform-provider-decort/wiki */ -package decort +package sep import ( + "context" + "github.com/google/uuid" - "github.com/hashicorp/terraform-plugin-sdk/helper/schema" + "github.com/hashicorp/terraform-plugin-sdk/v2/diag" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" + "github.com/rudecs/terraform-provider-decort/internal/constants" ) -func dataSourceSepDiskListRead(d *schema.ResourceData, m interface{}) error { +func dataSourceSepDiskListRead(ctx context.Context, d *schema.ResourceData, m interface{}) diag.Diagnostics { sepDiskList, err := utilitySepDiskListCheckPresence(d, m) if err != nil { - return err + return diag.FromErr(err) } id := uuid.New() d.SetId(id.String()) @@ -66,15 +77,15 @@ func dataSourceSepDiskListSchemaMake() map[string]*schema.Schema { return rets } -func dataSourceSepDiskList() *schema.Resource { +func DataSourceSepDiskList() *schema.Resource { return &schema.Resource{ SchemaVersion: 1, - Read: dataSourceSepDiskListRead, + ReadContext: dataSourceSepDiskListRead, Timeouts: &schema.ResourceTimeout{ - Read: &Timeout30s, - Default: &Timeout60s, + Read: &constants.Timeout30s, + Default: &constants.Timeout60s, }, Schema: dataSourceSepDiskListSchemaMake(), diff --git a/decort/data_source_sep_list.go b/internal/service/cloudbroker/sep/data_source_sep_list.go similarity index 72% rename from decort/data_source_sep_list.go rename to internal/service/cloudbroker/sep/data_source_sep_list.go index 89f0340..fe9bd5d 100644 --- a/decort/data_source_sep_list.go +++ b/internal/service/cloudbroker/sep/data_source_sep_list.go @@ -1,6 +1,8 @@ /* Copyright (c) 2019-2022 Digital Energy Cloud Solutions LLC. All Rights Reserved. -Author: Stanislav Solovev, , +Authors: +Petr Krutov, +Stanislav Solovev, Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. @@ -16,19 +18,28 @@ limitations under the License. */ /* -This file is part of Terraform (by Hashicorp) provider for Digital Energy Cloud Orchestration -Technology platfom. +Terraform DECORT provider - manage resources provided by DECORT (Digital Energy Cloud +Orchestration Technology) with Terraform by Hashicorp. -Visit https://github.com/rudecs/terraform-provider-decort for full source code package and updates. +Source code: https://github.com/rudecs/terraform-provider-decort + +Please see README.md to learn where to place source code so that it +builds seamlessly. + +Documentation: https://github.com/rudecs/terraform-provider-decort/wiki */ -package decort +package sep import ( + "context" "encoding/json" "github.com/google/uuid" - "github.com/hashicorp/terraform-plugin-sdk/helper/schema" + "github.com/hashicorp/terraform-plugin-sdk/v2/diag" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" + "github.com/rudecs/terraform-provider-decort/internal/constants" + "github.com/rudecs/terraform-provider-decort/internal/flattens" ) func flattenSepList(sl SepList) []map[string]interface{} { @@ -37,7 +48,7 @@ func flattenSepList(sl SepList) []map[string]interface{} { data, _ := json.Marshal(item.Config) temp := map[string]interface{}{ "ckey": item.Ckey, - "meta": flattenMeta(item.Meta), + "meta": flattens.FlattenMeta(item.Meta), "consumed_by": item.ConsumedBy, "desc": item.Desc, "gid": item.Gid, @@ -57,10 +68,10 @@ func flattenSepList(sl SepList) []map[string]interface{} { return res } -func dataSourceSepListRead(d *schema.ResourceData, m interface{}) error { +func dataSourceSepListRead(ctx context.Context, d *schema.ResourceData, m interface{}) diag.Diagnostics { sepList, err := utilitySepListCheckPresence(d, m) if err != nil { - return err + return diag.FromErr(err) } id := uuid.New() d.SetId(id.String()) @@ -164,15 +175,15 @@ func dataSourceSepShortSchemaMake() map[string]*schema.Schema { } } -func dataSourceSepList() *schema.Resource { +func DataSourceSepList() *schema.Resource { return &schema.Resource{ SchemaVersion: 1, - Read: dataSourceSepListRead, + ReadContext: dataSourceSepListRead, Timeouts: &schema.ResourceTimeout{ - Read: &Timeout30s, - Default: &Timeout60s, + Read: &constants.Timeout30s, + Default: &constants.Timeout60s, }, Schema: dataSourceSepListSchemaMake(), diff --git a/decort/data_source_sep_pool.go b/internal/service/cloudbroker/sep/data_source_sep_pool.go similarity index 57% rename from decort/data_source_sep_pool.go rename to internal/service/cloudbroker/sep/data_source_sep_pool.go index 6f401ba..92238e8 100644 --- a/decort/data_source_sep_pool.go +++ b/internal/service/cloudbroker/sep/data_source_sep_pool.go @@ -1,6 +1,8 @@ /* Copyright (c) 2019-2022 Digital Energy Cloud Solutions LLC. All Rights Reserved. -Author: Stanislav Solovev, , +Authors: +Petr Krutov, +Stanislav Solovev, Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. @@ -16,25 +18,33 @@ limitations under the License. */ /* -This file is part of Terraform (by Hashicorp) provider for Digital Energy Cloud Orchestration -Technology platfom. +Terraform DECORT provider - manage resources provided by DECORT (Digital Energy Cloud +Orchestration Technology) with Terraform by Hashicorp. -Visit https://github.com/rudecs/terraform-provider-decort for full source code package and updates. +Source code: https://github.com/rudecs/terraform-provider-decort + +Please see README.md to learn where to place source code so that it +builds seamlessly. + +Documentation: https://github.com/rudecs/terraform-provider-decort/wiki */ -package decort +package sep import ( + "context" "encoding/json" "github.com/google/uuid" - "github.com/hashicorp/terraform-plugin-sdk/helper/schema" + "github.com/hashicorp/terraform-plugin-sdk/v2/diag" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" + "github.com/rudecs/terraform-provider-decort/internal/constants" ) -func dataSourceSepPoolRead(d *schema.ResourceData, m interface{}) error { +func dataSourceSepPoolRead(ctx context.Context, d *schema.ResourceData, m interface{}) diag.Diagnostics { sepPool, err := utilitySepPoolCheckPresence(d, m) if err != nil { - return err + return diag.FromErr(err) } id := uuid.New() d.SetId(id.String()) @@ -64,15 +74,15 @@ func dataSourceSepPoolSchemaMake() map[string]*schema.Schema { } } -func dataSourceSepPool() *schema.Resource { +func DataSourceSepPool() *schema.Resource { return &schema.Resource{ SchemaVersion: 1, - Read: dataSourceSepPoolRead, + ReadContext: dataSourceSepPoolRead, Timeouts: &schema.ResourceTimeout{ - Read: &Timeout30s, - Default: &Timeout60s, + Read: &constants.Timeout30s, + Default: &constants.Timeout60s, }, Schema: dataSourceSepPoolSchemaMake(), diff --git a/internal/service/cloudbroker/sep/models.go b/internal/service/cloudbroker/sep/models.go new file mode 100644 index 0000000..e955887 --- /dev/null +++ b/internal/service/cloudbroker/sep/models.go @@ -0,0 +1,77 @@ +/* +Copyright (c) 2019-2022 Digital Energy Cloud Solutions LLC. All Rights Reserved. +Authors: +Petr Krutov, +Stanislav Solovev, + +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. +*/ + +/* +Terraform DECORT provider - manage resources provided by DECORT (Digital Energy Cloud +Orchestration Technology) with Terraform by Hashicorp. + +Source code: https://github.com/rudecs/terraform-provider-decort + +Please see README.md to learn where to place source code so that it +builds seamlessly. + +Documentation: https://github.com/rudecs/terraform-provider-decort/wiki +*/ + +package sep + +///Sep Models +type SepConsumptionInd struct { + DiskCount int `json:"disk_count"` + DiskUsage int `json:"disk_usage"` + SnapshotCount int `json:"snapshot_count"` + SnapshotUsage int `json:"snapshot_usage"` + Usage int `json:"usage"` + UsageLimit int `json:"usage_limit"` +} + +type SepConsumptionTotal struct { + CapacityLimit int `json:"capacity_limit"` + SepConsumptionInd +} + +type SepConsumption struct { + Total SepConsumptionTotal `json:"total"` + Type string `json:"type"` + ByPool map[string]SepConsumptionInd `json:"byPool"` +} + +type SepDiskList []int + +type Sep struct { + Ckey string `json:"_ckey"` + Meta []interface{} `json:"_meta"` + ConsumedBy []int `json:"consumedBy"` + Desc string `json:"desc"` + Gid int `json:"gid"` + Guid int `json:"guid"` + Id int `json:"id"` + Milestones int `json:"milestones"` + Name string `json:"name"` + ObjStatus string `json:"objStatus"` + ProvidedBy []int `json:"providedBy"` + TechStatus string `json:"techStatus"` + Type string `json:"type"` + Config SepConfig `json:"config"` +} + +type SepConfig map[string]interface{} + +type SepList []Sep +type SepPool map[string]interface{} diff --git a/decort/resource_sep.go b/internal/service/cloudbroker/sep/resource_sep.go similarity index 69% rename from decort/resource_sep.go rename to internal/service/cloudbroker/sep/resource_sep.go index d3608e3..95c341f 100644 --- a/decort/resource_sep.go +++ b/internal/service/cloudbroker/sep/resource_sep.go @@ -1,6 +1,8 @@ /* Copyright (c) 2019-2022 Digital Energy Cloud Solutions LLC. All Rights Reserved. -Author: Stanislav Solovev, +Authors: +Petr Krutov, +Stanislav Solovev, Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. @@ -16,46 +18,55 @@ limitations under the License. */ /* -This file is part of Terraform (by Hashicorp) provider for Digital Energy Cloud Orchestration -Technology platfom. +Terraform DECORT provider - manage resources provided by DECORT (Digital Energy Cloud +Orchestration Technology) with Terraform by Hashicorp. -Visit https://github.com/rudecs/terraform-provider-decort for full source code package and updates. +Source code: https://github.com/rudecs/terraform-provider-decort + +Please see README.md to learn where to place source code so that it +builds seamlessly. + +Documentation: https://github.com/rudecs/terraform-provider-decort/wiki */ -package decort +package sep import ( + "context" "encoding/json" "errors" "net/url" "strconv" "github.com/google/uuid" - "github.com/hashicorp/terraform-plugin-sdk/helper/customdiff" - "github.com/hashicorp/terraform-plugin-sdk/helper/schema" + "github.com/hashicorp/terraform-plugin-sdk/v2/diag" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" + "github.com/rudecs/terraform-provider-decort/internal/constants" + "github.com/rudecs/terraform-provider-decort/internal/controller" + "github.com/rudecs/terraform-provider-decort/internal/flattens" log "github.com/sirupsen/logrus" ) -func resourceSepCreate(d *schema.ResourceData, m interface{}) error { +func resourceSepCreate(ctx context.Context, d *schema.ResourceData, m interface{}) diag.Diagnostics { log.Debugf("resourceSepCreate: called for sep %s", d.Get("name").(string)) if sepId, ok := d.GetOk("sep_id"); ok { if exists, err := resourceSepExists(d, m); exists { if err != nil { - return err + return diag.FromErr(err) } d.SetId(strconv.Itoa(sepId.(int))) - err = resourceSepRead(d, m) - if err != nil { - return err + diagnostics := resourceSepRead(ctx, d, m) + if diagnostics != nil { + return diagnostics } return nil } - return errors.New("provided sep id does not exist") + return diag.Errorf("provided sep id does not exist") } - controller := m.(*ControllerCfg) + c := m.(*controller.ControllerCfg) urlValues := &url.Values{} urlValues.Add("name", d.Get("name").(string)) @@ -98,18 +109,18 @@ func resourceSepCreate(d *schema.ResourceData, m interface{}) error { temp = "[" + temp + "]" urlValues.Add("provider_nids", temp) - sepId, err := controller.decortAPICall("POST", sepCreateAPI, urlValues) + sepId, err := c.DecortAPICall("POST", sepCreateAPI, urlValues) if err != nil { - return err + return diag.FromErr(err) } id := uuid.New() d.SetId(sepId) d.Set("sep_id", sepId) - err = resourceSepRead(d, m) - if err != nil { - return err + diagnostics := resourceSepRead(ctx, d, m) + if diagnostics != nil { + return diagnostics } d.SetId(id.String()) @@ -117,17 +128,17 @@ func resourceSepCreate(d *schema.ResourceData, m interface{}) error { return nil } -func resourceSepRead(d *schema.ResourceData, m interface{}) error { +func resourceSepRead(ctx context.Context, d *schema.ResourceData, m interface{}) diag.Diagnostics { log.Debugf("resourceSepRead: called for %s id: %d", d.Get("name").(string), d.Get("sep_id").(int)) sep, err := utilitySepCheckPresence(d, m) if sep == nil { d.SetId("") - return err + return diag.FromErr(err) } d.Set("ckey", sep.Ckey) - d.Set("meta", flattenMeta(sep.Meta)) + d.Set("meta", flattens.FlattenMeta(sep.Meta)) d.Set("consumed_by", sep.ConsumedBy) d.Set("desc", sep.Desc) d.Set("gid", sep.Gid) @@ -145,24 +156,24 @@ func resourceSepRead(d *schema.ResourceData, m interface{}) error { return nil } -func resourceSepDelete(d *schema.ResourceData, m interface{}) error { +func resourceSepDelete(ctx context.Context, d *schema.ResourceData, m interface{}) diag.Diagnostics { log.Debugf("resourceSepDelete: called for %s, id: %d", d.Get("name").(string), d.Get("sep_id").(int)) sepDes, err := utilitySepCheckPresence(d, m) if sepDes == nil { if err != nil { - return err + return diag.FromErr(err) } return nil } - controller := m.(*ControllerCfg) + c := m.(*controller.ControllerCfg) urlValues := &url.Values{} urlValues.Add("sep_id", strconv.Itoa(d.Get("sep_id").(int))) - _, err = controller.decortAPICall("POST", sepDeleteAPI, urlValues) + _, err = c.DecortAPICall("POST", sepDeleteAPI, urlValues) if err != nil { - return err + return diag.FromErr(err) } d.SetId("") @@ -183,9 +194,9 @@ func resourceSepExists(d *schema.ResourceData, m interface{}) (bool, error) { return true, nil } -func resourceSepEdit(d *schema.ResourceData, m interface{}) error { +func resourceSepEdit(ctx context.Context, d *schema.ResourceData, m interface{}) diag.Diagnostics { log.Debugf("resourceSepEdit: called for %s, id: %d", d.Get("name").(string), d.Get("sep_id").(int)) - c := m.(*ControllerCfg) + c := m.(*controller.ControllerCfg) urlValues := &url.Values{} if d.HasChange("decommission") { @@ -193,9 +204,9 @@ func resourceSepEdit(d *schema.ResourceData, m interface{}) error { if decommission { urlValues.Add("sep_id", strconv.Itoa(d.Get("sep_id").(int))) urlValues.Add("clear_physically", strconv.FormatBool(d.Get("clear_physically").(bool))) - _, err := c.decortAPICall("POST", sepDecommissionAPI, urlValues) + _, err := c.DecortAPICall("POST", sepDecommissionAPI, urlValues) if err != nil { - return err + return diag.FromErr(err) } } } @@ -205,9 +216,9 @@ func resourceSepEdit(d *schema.ResourceData, m interface{}) error { updCapacityLimit := d.Get("upd_capacity_limit").(bool) if updCapacityLimit { urlValues.Add("sep_id", strconv.Itoa(d.Get("sep_id").(int))) - _, err := c.decortAPICall("POST", sepUpdateCapacityLimitAPI, urlValues) + _, err := c.DecortAPICall("POST", sepUpdateCapacityLimitAPI, urlValues) if err != nil { - return err + return diag.FromErr(err) } } } @@ -216,13 +227,13 @@ func resourceSepEdit(d *schema.ResourceData, m interface{}) error { if d.HasChange("config") { urlValues.Add("sep_id", strconv.Itoa(d.Get("sep_id").(int))) urlValues.Add("config", d.Get("config").(string)) - _, err := c.decortAPICall("POST", sepConfigValidateAPI, urlValues) + _, err := c.DecortAPICall("POST", sepConfigValidateAPI, urlValues) if err != nil { - return err + return diag.FromErr(err) } - _, err = c.decortAPICall("POST", sepConfigInsertAPI, urlValues) + _, err = c.DecortAPICall("POST", sepConfigInsertAPI, urlValues) if err != nil { - return err + return diag.FromErr(err) } } @@ -236,24 +247,48 @@ func resourceSepEdit(d *schema.ResourceData, m interface{}) error { urlValues.Add("field_value", field["field_value"].(string)) urlValues.Add("field_type", field["field_type"].(string)) - _, err := c.decortAPICall("POST", sepConfigFieldEditAPI, urlValues) + _, err := c.DecortAPICall("POST", sepConfigFieldEditAPI, urlValues) if err != nil { - return err + return diag.FromErr(err) } } urlValues = &url.Values{} - if err := resourceSepRead(d, m); err != nil { - return err + if d.HasChange("enable") { + err := resourceSepChangeEnabled(d, m) + if err != nil { + return diag.FromErr(err) + } + } + + urlValues = &url.Values{} + if d.HasChange("consumed_by") { + err := resourceSepUpdateNodes(d, m) + if err != nil { + return diag.FromErr(err) + } + } + + urlValues = &url.Values{} + if d.HasChange("provided_by") { + err := resourceSepUpdateProviders(d, m) + if err != nil { + return diag.FromErr(err) + } + } + + urlValues = &url.Values{} + if diagnostics := resourceSepRead(ctx, d, m); diagnostics != nil { + return diagnostics } return nil } -func resourceSepChangeEnabled(d *schema.ResourceDiff, m interface{}) error { +func resourceSepChangeEnabled(d *schema.ResourceData, m interface{}) error { var api string - c := m.(*ControllerCfg) + c := m.(*controller.ControllerCfg) urlValues := &url.Values{} urlValues.Add("sep_id", strconv.Itoa(d.Get("sep_id").(int))) if d.Get("enable").(bool) { @@ -261,7 +296,7 @@ func resourceSepChangeEnabled(d *schema.ResourceDiff, m interface{}) error { } else { api = sepDisableAPI } - resp, err := c.decortAPICall("POST", api, urlValues) + resp, err := c.DecortAPICall("POST", api, urlValues) if err != nil { return err } @@ -275,9 +310,9 @@ func resourceSepChangeEnabled(d *schema.ResourceDiff, m interface{}) error { return nil } -func resourceSepUpdateNodes(d *schema.ResourceDiff, m interface{}) error { +func resourceSepUpdateNodes(d *schema.ResourceData, m interface{}) error { log.Debugf("resourceSepUpdateNodes: called for %s, id: %d", d.Get("name").(string), d.Get("sep_id").(int)) - c := m.(*ControllerCfg) + c := m.(*controller.ControllerCfg) urlValues := &url.Values{} t1, t2 := d.GetChange("consumed_by") @@ -310,7 +345,7 @@ func resourceSepUpdateNodes(d *schema.ResourceDiff, m interface{}) error { } temp = "[" + temp + "]" urlValues.Add("consumer_nids", temp) - _, err := c.decortAPICall("POST", api, urlValues) + _, err := c.DecortAPICall("POST", api, urlValues) if err != nil { return err } @@ -327,9 +362,9 @@ func findElInt(sl []interface{}, el interface{}) bool { return false } -func resourceSepUpdateProviders(d *schema.ResourceDiff, m interface{}) error { +func resourceSepUpdateProviders(d *schema.ResourceData, m interface{}) error { log.Debugf("resourceSepUpdateProviders: called for %s, id: %d", d.Get("name").(string), d.Get("sep_id").(int)) - c := m.(*ControllerCfg) + c := m.(*controller.ControllerCfg) urlValues := &url.Values{} urlValues.Add("sep_id", strconv.Itoa(d.Get("sep_id").(int))) providerIds := d.Get("provided_by").([]interface{}) @@ -344,7 +379,7 @@ func resourceSepUpdateProviders(d *schema.ResourceDiff, m interface{}) error { } temp = "[" + temp + "]" urlValues.Add("provider_nids", temp) - _, err := c.decortAPICall("POST", sepAddProviderNodesAPI, urlValues) + _, err := c.DecortAPICall("POST", sepAddProviderNodesAPI, urlValues) if err != nil { return err } @@ -481,68 +516,28 @@ func resourceSepSchemaMake() map[string]*schema.Schema { } } -func resourceSep() *schema.Resource { +func ResourceSep() *schema.Resource { return &schema.Resource{ SchemaVersion: 1, - Create: resourceSepCreate, - Read: resourceSepRead, - Update: resourceSepEdit, - Delete: resourceSepDelete, - Exists: resourceSepExists, + CreateContext: resourceSepCreate, + ReadContext: resourceSepRead, + UpdateContext: resourceSepEdit, + DeleteContext: resourceSepDelete, + Exists: resourceSepExists, Importer: &schema.ResourceImporter{ State: schema.ImportStatePassthrough, }, Timeouts: &schema.ResourceTimeout{ - Create: &Timeout60s, - Read: &Timeout30s, - Update: &Timeout60s, - Delete: &Timeout60s, - Default: &Timeout60s, + Create: &constants.Timeout60s, + Read: &constants.Timeout30s, + Update: &constants.Timeout60s, + Delete: &constants.Timeout60s, + Default: &constants.Timeout60s, }, Schema: resourceSepSchemaMake(), - - CustomizeDiff: customdiff.All( - customdiff.IfValueChange("enable", func(old, new, meta interface{}) bool { - return old.(bool) != new.(bool) - }, resourceSepChangeEnabled), - customdiff.IfValueChange("consumed_by", func(old, new, meta interface{}) bool { - o := old.([]interface{}) - n := new.([]interface{}) - - if len(o) != len(n) { - return true - } else if len(o) == 0 { - return false - } - count := 0 - for i, v := range n { - if v.(int) == o[i].(int) { - count++ - } - } - return count == 0 - }, resourceSepUpdateNodes), - customdiff.IfValueChange("provided_by", func(old, new, meta interface{}) bool { - o := old.([]interface{}) - n := new.([]interface{}) - - if len(o) != len(n) { - return true - } else if len(o) == 0 { - return false - } - count := 0 - for i, v := range n { - if v.(int) == o[i].(int) { - count++ - } - } - return count == 0 - }, resourceSepUpdateProviders), - ), } } diff --git a/decort/resource_sep_config.go b/internal/service/cloudbroker/sep/resource_sep_config.go similarity index 57% rename from decort/resource_sep_config.go rename to internal/service/cloudbroker/sep/resource_sep_config.go index c16b0f0..dca075f 100644 --- a/decort/resource_sep_config.go +++ b/internal/service/cloudbroker/sep/resource_sep_config.go @@ -1,6 +1,8 @@ /* Copyright (c) 2019-2022 Digital Energy Cloud Solutions LLC. All Rights Reserved. -Author: Stanislav Solovev, +Authors: +Petr Krutov, +Stanislav Solovev, Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. @@ -16,62 +18,70 @@ limitations under the License. */ /* -This file is part of Terraform (by Hashicorp) provider for Digital Energy Cloud Orchestration -Technology platfom. +Terraform DECORT provider - manage resources provided by DECORT (Digital Energy Cloud +Orchestration Technology) with Terraform by Hashicorp. -Visit https://github.com/rudecs/terraform-provider-decort for full source code package and updates. +Source code: https://github.com/rudecs/terraform-provider-decort + +Please see README.md to learn where to place source code so that it +builds seamlessly. + +Documentation: https://github.com/rudecs/terraform-provider-decort/wiki */ -package decort +package sep import ( + "context" "encoding/json" - "errors" "net/url" "strconv" "github.com/google/uuid" - "github.com/hashicorp/terraform-plugin-sdk/helper/schema" + "github.com/hashicorp/terraform-plugin-sdk/v2/diag" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" + "github.com/rudecs/terraform-provider-decort/internal/constants" + "github.com/rudecs/terraform-provider-decort/internal/controller" log "github.com/sirupsen/logrus" ) -func resourceSepConfigCreate(d *schema.ResourceData, m interface{}) error { +func resourceSepConfigCreate(ctx context.Context, d *schema.ResourceData, m interface{}) diag.Diagnostics { log.Debugf("resourceSepConfigCreate: called for sep id %d", d.Get("sep_id").(int)) if _, ok := d.GetOk("sep_id"); ok { if exists, err := resourceSepConfigExists(d, m); exists { if err != nil { - return err + return diag.FromErr(err) } id := uuid.New() d.SetId(id.String()) - err = resourceSepConfigRead(d, m) - if err != nil { - return err + diagnostics := resourceSepConfigRead(ctx, d, m) + if diagnostics != nil { + return diagnostics } return nil } - return errors.New("provided sep id config does not exist") + return diag.Errorf("provided sep id config does not exist") } - return resourceSepConfigRead(d, m) + return resourceSepConfigRead(ctx, d, m) } -func resourceSepConfigRead(d *schema.ResourceData, m interface{}) error { +func resourceSepConfigRead(ctx context.Context, d *schema.ResourceData, m interface{}) diag.Diagnostics { log.Debugf("resourceSepConfigRead: called for sep id: %d", d.Get("sep_id").(int)) sepConfig, err := utilitySepConfigCheckPresence(d, m) if sepConfig == nil { d.SetId("") - return err + return diag.FromErr(err) } data, _ := json.Marshal(sepConfig) d.Set("config", string(data)) return nil } -func resourceSepConfigDelete(d *schema.ResourceData, m interface{}) error { +func resourceSepConfigDelete(ctx context.Context, d *schema.ResourceData, m interface{}) diag.Diagnostics { d.SetId("") return nil } @@ -90,21 +100,21 @@ func resourceSepConfigExists(d *schema.ResourceData, m interface{}) (bool, error return true, nil } -func resourceSepConfigEdit(d *schema.ResourceData, m interface{}) error { +func resourceSepConfigEdit(ctx context.Context, d *schema.ResourceData, m interface{}) diag.Diagnostics { log.Debugf("resourceSepConfigEdit: called for sep id: %d", d.Get("sep_id").(int)) - c := m.(*ControllerCfg) + c := m.(*controller.ControllerCfg) urlValues := &url.Values{} if d.HasChange("config") { urlValues.Add("sep_id", strconv.Itoa(d.Get("sep_id").(int))) urlValues.Add("config", d.Get("config").(string)) - _, err := c.decortAPICall("POST", sepConfigValidateAPI, urlValues) + _, err := c.DecortAPICall("POST", sepConfigValidateAPI, urlValues) if err != nil { - return err + return diag.FromErr(err) } - _, err = c.decortAPICall("POST", sepConfigInsertAPI, urlValues) + _, err = c.DecortAPICall("POST", sepConfigInsertAPI, urlValues) if err != nil { - return err + return diag.FromErr(err) } } @@ -118,15 +128,15 @@ func resourceSepConfigEdit(d *schema.ResourceData, m interface{}) error { urlValues.Add("field_value", field["field_value"].(string)) urlValues.Add("field_type", field["field_type"].(string)) - _, err := c.decortAPICall("POST", sepConfigFieldEditAPI, urlValues) + _, err := c.DecortAPICall("POST", sepConfigFieldEditAPI, urlValues) if err != nil { - return err + return diag.FromErr(err) } } - err := resourceSepConfigRead(d, m) - if err != nil { - return err + diagnostics := resourceSepConfigRead(ctx, d, m) + if diagnostics != nil { + return diagnostics } return nil @@ -168,26 +178,26 @@ func resourceSepConfigSchemaMake() map[string]*schema.Schema { } } -func resourceSepConfig() *schema.Resource { +func ResourceSepConfig() *schema.Resource { return &schema.Resource{ SchemaVersion: 1, - Create: resourceSepConfigCreate, - Read: resourceSepConfigRead, - Update: resourceSepConfigEdit, - Delete: resourceSepConfigDelete, - Exists: resourceSepConfigExists, + CreateContext: resourceSepConfigCreate, + ReadContext: resourceSepConfigRead, + UpdateContext: resourceSepConfigEdit, + DeleteContext: resourceSepConfigDelete, + Exists: resourceSepConfigExists, Importer: &schema.ResourceImporter{ State: schema.ImportStatePassthrough, }, Timeouts: &schema.ResourceTimeout{ - Create: &Timeout60s, - Read: &Timeout30s, - Update: &Timeout60s, - Delete: &Timeout60s, - Default: &Timeout60s, + Create: &constants.Timeout60s, + Read: &constants.Timeout30s, + Update: &constants.Timeout60s, + Delete: &constants.Timeout60s, + Default: &constants.Timeout60s, }, Schema: resourceSepConfigSchemaMake(), diff --git a/decort/utility_sep.go b/internal/service/cloudbroker/sep/utility_sep.go similarity index 59% rename from decort/utility_sep.go rename to internal/service/cloudbroker/sep/utility_sep.go index 20dbf3d..a8f3f9d 100644 --- a/decort/utility_sep.go +++ b/internal/service/cloudbroker/sep/utility_sep.go @@ -1,6 +1,8 @@ /* Copyright (c) 2019-2022 Digital Energy Cloud Solutions LLC. All Rights Reserved. -Author: Stanislav Solovev, , +Authors: +Petr Krutov, +Stanislav Solovev, Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. @@ -16,26 +18,32 @@ limitations under the License. */ /* -This file is part of Terraform (by Hashicorp) provider for Digital Energy Cloud Orchestration -Technology platfom. +Terraform DECORT provider - manage resources provided by DECORT (Digital Energy Cloud +Orchestration Technology) with Terraform by Hashicorp. -Visit https://github.com/rudecs/terraform-provider-decort for full source code package and updates. +Source code: https://github.com/rudecs/terraform-provider-decort + +Please see README.md to learn where to place source code so that it +builds seamlessly. + +Documentation: https://github.com/rudecs/terraform-provider-decort/wiki */ -package decort +package sep import ( "encoding/json" "net/url" "strconv" + "github.com/rudecs/terraform-provider-decort/internal/controller" log "github.com/sirupsen/logrus" - "github.com/hashicorp/terraform-plugin-sdk/helper/schema" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" ) func utilitySepCheckPresence(d *schema.ResourceData, m interface{}) (*Sep, error) { - controller := m.(*ControllerCfg) + c := m.(*controller.ControllerCfg) urlValues := &url.Values{} sep := &Sep{} @@ -47,7 +55,7 @@ func utilitySepCheckPresence(d *schema.ResourceData, m interface{}) (*Sep, error } log.Debugf("utilitySepCheckPresence: load sep") - sepRaw, err := controller.decortAPICall("POST", sepGetAPI, urlValues) + sepRaw, err := c.DecortAPICall("POST", sepGetAPI, urlValues) if err != nil { return nil, err } diff --git a/decort/utility_sep_config.go b/internal/service/cloudbroker/sep/utility_sep_config.go similarity index 59% rename from decort/utility_sep_config.go rename to internal/service/cloudbroker/sep/utility_sep_config.go index ac98899..d63f19f 100644 --- a/decort/utility_sep_config.go +++ b/internal/service/cloudbroker/sep/utility_sep_config.go @@ -1,6 +1,8 @@ /* Copyright (c) 2019-2022 Digital Energy Cloud Solutions LLC. All Rights Reserved. -Author: Stanislav Solovev, , +Authors: +Petr Krutov, +Stanislav Solovev, Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. @@ -16,26 +18,32 @@ limitations under the License. */ /* -This file is part of Terraform (by Hashicorp) provider for Digital Energy Cloud Orchestration -Technology platfom. +Terraform DECORT provider - manage resources provided by DECORT (Digital Energy Cloud +Orchestration Technology) with Terraform by Hashicorp. -Visit https://github.com/rudecs/terraform-provider-decort for full source code package and updates. +Source code: https://github.com/rudecs/terraform-provider-decort + +Please see README.md to learn where to place source code so that it +builds seamlessly. + +Documentation: https://github.com/rudecs/terraform-provider-decort/wiki */ -package decort +package sep import ( "encoding/json" "net/url" "strconv" + "github.com/rudecs/terraform-provider-decort/internal/controller" log "github.com/sirupsen/logrus" - "github.com/hashicorp/terraform-plugin-sdk/helper/schema" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" ) func utilitySepConfigCheckPresence(d *schema.ResourceData, m interface{}) (SepConfig, error) { - controller := m.(*ControllerCfg) + c := m.(*controller.ControllerCfg) urlValues := &url.Values{} sepConfig := SepConfig{} @@ -43,7 +51,7 @@ func utilitySepConfigCheckPresence(d *schema.ResourceData, m interface{}) (SepCo urlValues.Add("sep_id", strconv.Itoa(d.Get("sep_id").(int))) log.Debugf("utilitySepConfigCheckPresence: load sep config") - sepConfigRaw, err := controller.decortAPICall("POST", sepGetConfigAPI, urlValues) + sepConfigRaw, err := c.DecortAPICall("POST", sepGetConfigAPI, urlValues) if err != nil { return nil, err } diff --git a/decort/utility_sep_consumption.go b/internal/service/cloudbroker/sep/utility_sep_consumption.go similarity index 57% rename from decort/utility_sep_consumption.go rename to internal/service/cloudbroker/sep/utility_sep_consumption.go index 413344c..5ce0d8e 100644 --- a/decort/utility_sep_consumption.go +++ b/internal/service/cloudbroker/sep/utility_sep_consumption.go @@ -1,6 +1,8 @@ /* Copyright (c) 2019-2022 Digital Energy Cloud Solutions LLC. All Rights Reserved. -Author: Stanislav Solovev, , +Authors: +Petr Krutov, +Stanislav Solovev, Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. @@ -16,31 +18,37 @@ limitations under the License. */ /* -This file is part of Terraform (by Hashicorp) provider for Digital Energy Cloud Orchestration -Technology platfom. +Terraform DECORT provider - manage resources provided by DECORT (Digital Energy Cloud +Orchestration Technology) with Terraform by Hashicorp. -Visit https://github.com/rudecs/terraform-provider-decort for full source code package and updates. +Source code: https://github.com/rudecs/terraform-provider-decort + +Please see README.md to learn where to place source code so that it +builds seamlessly. + +Documentation: https://github.com/rudecs/terraform-provider-decort/wiki */ -package decort +package sep import ( "encoding/json" "net/url" "strconv" - "github.com/hashicorp/terraform-plugin-sdk/helper/schema" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" + "github.com/rudecs/terraform-provider-decort/internal/controller" ) func utilitySepConsumptionCheckPresence(d *schema.ResourceData, m interface{}) (*SepConsumption, error) { - controller := m.(*ControllerCfg) + c := m.(*controller.ControllerCfg) urlValues := &url.Values{} sepCons := &SepConsumption{} urlValues.Add("sep_id", strconv.Itoa(d.Get("sep_id").(int))) - sepConsRaw, err := controller.decortAPICall("POST", sepConsumptionAPI, urlValues) + sepConsRaw, err := c.DecortAPICall("POST", sepConsumptionAPI, urlValues) if err != nil { return nil, err } diff --git a/decort/utility_sep_disk_list.go b/internal/service/cloudbroker/sep/utility_sep_disk_list.go similarity index 60% rename from decort/utility_sep_disk_list.go rename to internal/service/cloudbroker/sep/utility_sep_disk_list.go index 064d144..2a2676a 100644 --- a/decort/utility_sep_disk_list.go +++ b/internal/service/cloudbroker/sep/utility_sep_disk_list.go @@ -1,6 +1,8 @@ /* Copyright (c) 2019-2022 Digital Energy Cloud Solutions LLC. All Rights Reserved. -Author: Stanislav Solovev, , +Authors: +Petr Krutov, +Stanislav Solovev, Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. @@ -16,26 +18,32 @@ limitations under the License. */ /* -This file is part of Terraform (by Hashicorp) provider for Digital Energy Cloud Orchestration -Technology platfom. +Terraform DECORT provider - manage resources provided by DECORT (Digital Energy Cloud +Orchestration Technology) with Terraform by Hashicorp. -Visit https://github.com/rudecs/terraform-provider-decort for full source code package and updates. +Source code: https://github.com/rudecs/terraform-provider-decort + +Please see README.md to learn where to place source code so that it +builds seamlessly. + +Documentation: https://github.com/rudecs/terraform-provider-decort/wiki */ -package decort +package sep import ( "encoding/json" "net/url" "strconv" + "github.com/rudecs/terraform-provider-decort/internal/controller" log "github.com/sirupsen/logrus" - "github.com/hashicorp/terraform-plugin-sdk/helper/schema" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" ) func utilitySepDiskListCheckPresence(d *schema.ResourceData, m interface{}) ([]int, error) { - controller := m.(*ControllerCfg) + c := m.(*controller.ControllerCfg) urlValues := &url.Values{} sepDiskList := SepDiskList{} @@ -47,7 +55,7 @@ func utilitySepDiskListCheckPresence(d *schema.ResourceData, m interface{}) ([]i } log.Debugf("utilitySepDiskListCheckPresence: load sep") - sepDiskListRaw, err := controller.decortAPICall("POST", sepDiskListAPI, urlValues) + sepDiskListRaw, err := c.DecortAPICall("POST", sepDiskListAPI, urlValues) if err != nil { return nil, err } diff --git a/decort/utility_sep_list.go b/internal/service/cloudbroker/sep/utility_sep_list.go similarity index 61% rename from decort/utility_sep_list.go rename to internal/service/cloudbroker/sep/utility_sep_list.go index 30f7df6..ab1fd2f 100644 --- a/decort/utility_sep_list.go +++ b/internal/service/cloudbroker/sep/utility_sep_list.go @@ -1,6 +1,8 @@ /* Copyright (c) 2019-2022 Digital Energy Cloud Solutions LLC. All Rights Reserved. -Author: Stanislav Solovev, , +Authors: +Petr Krutov, +Stanislav Solovev, Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. @@ -16,27 +18,33 @@ limitations under the License. */ /* -This file is part of Terraform (by Hashicorp) provider for Digital Energy Cloud Orchestration -Technology platfom. +Terraform DECORT provider - manage resources provided by DECORT (Digital Energy Cloud +Orchestration Technology) with Terraform by Hashicorp. -Visit https://github.com/rudecs/terraform-provider-decort for full source code package and updates. +Source code: https://github.com/rudecs/terraform-provider-decort + +Please see README.md to learn where to place source code so that it +builds seamlessly. + +Documentation: https://github.com/rudecs/terraform-provider-decort/wiki */ -package decort +package sep import ( "encoding/json" "net/url" "strconv" + "github.com/rudecs/terraform-provider-decort/internal/controller" log "github.com/sirupsen/logrus" - "github.com/hashicorp/terraform-plugin-sdk/helper/schema" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" ) func utilitySepListCheckPresence(d *schema.ResourceData, m interface{}) (SepList, error) { sepList := SepList{} - controller := m.(*ControllerCfg) + c := m.(*controller.ControllerCfg) urlValues := &url.Values{} if page, ok := d.GetOk("page"); ok { @@ -47,7 +55,7 @@ func utilitySepListCheckPresence(d *schema.ResourceData, m interface{}) (SepList } log.Debugf("utilitySepListCheckPresence: load image list") - sepListRaw, err := controller.decortAPICall("POST", sepListAPI, urlValues) + sepListRaw, err := c.DecortAPICall("POST", sepListAPI, urlValues) if err != nil { return nil, err } diff --git a/decort/utility_sep_pool.go b/internal/service/cloudbroker/sep/utility_sep_pool.go similarity index 59% rename from decort/utility_sep_pool.go rename to internal/service/cloudbroker/sep/utility_sep_pool.go index 048bc4b..a9064fc 100644 --- a/decort/utility_sep_pool.go +++ b/internal/service/cloudbroker/sep/utility_sep_pool.go @@ -1,6 +1,8 @@ /* Copyright (c) 2019-2022 Digital Energy Cloud Solutions LLC. All Rights Reserved. -Author: Stanislav Solovev, , +Authors: +Petr Krutov, +Stanislav Solovev, Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. @@ -16,26 +18,32 @@ limitations under the License. */ /* -This file is part of Terraform (by Hashicorp) provider for Digital Energy Cloud Orchestration -Technology platfom. +Terraform DECORT provider - manage resources provided by DECORT (Digital Energy Cloud +Orchestration Technology) with Terraform by Hashicorp. -Visit https://github.com/rudecs/terraform-provider-decort for full source code package and updates. +Source code: https://github.com/rudecs/terraform-provider-decort + +Please see README.md to learn where to place source code so that it +builds seamlessly. + +Documentation: https://github.com/rudecs/terraform-provider-decort/wiki */ -package decort +package sep import ( "encoding/json" "net/url" "strconv" + "github.com/rudecs/terraform-provider-decort/internal/controller" log "github.com/sirupsen/logrus" - "github.com/hashicorp/terraform-plugin-sdk/helper/schema" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" ) func utilitySepPoolCheckPresence(d *schema.ResourceData, m interface{}) (SepPool, error) { - controller := m.(*ControllerCfg) + c := m.(*controller.ControllerCfg) urlValues := &url.Values{} sepPool := SepPool{} @@ -44,7 +52,7 @@ func utilitySepPoolCheckPresence(d *schema.ResourceData, m interface{}) (SepPool urlValues.Add("pool_name", d.Get("pool_name").(string)) log.Debugf("utilitySepDesPoolCheckPresence: load sep") - sepPoolRaw, err := controller.decortAPICall("POST", sepGetPoolAPI, urlValues) + sepPoolRaw, err := c.DecortAPICall("POST", sepGetPoolAPI, urlValues) if err != nil { return nil, err } From 9a7642cf332bf3971a13e9eaa63ae3a584d65b0c Mon Sep 17 00:00:00 2001 From: stSolo Date: Wed, 29 Jun 2022 16:22:31 +0300 Subject: [PATCH 37/51] Add context to DecortAPICall method --- go.mod | 1 + internal/controller/controller.go | 3 +- internal/location/location.go | 5 +- internal/provider/provider.go | 5 +- .../cloudapi/account/data_source_account.go | 2 +- .../data_source_account_audits_list.go | 2 +- .../data_source_account_computes_list.go | 2 +- .../data_source_account_consumed_units.go | 2 +- ...a_source_account_consumed_units_by_type.go | 2 +- .../data_source_account_deleted_list.go | 2 +- .../account/data_source_account_disks_list.go | 2 +- .../data_source_account_flipgroups_list.go | 2 +- .../account/data_source_account_list.go | 2 +- .../data_source_account_reserved_units.go | 2 +- .../account/data_source_account_rg_list.go | 2 +- .../data_source_account_templates_list.go | 2 +- .../account/data_source_account_vins_list.go | 2 +- .../cloudapi/account/resource_account.go | 31 +++++----- .../cloudapi/account/utility_account.go | 5 +- .../account/utility_account_audits_list.go | 5 +- .../account/utility_account_computes_list.go | 5 +- .../account/utility_account_consumed_units.go | 5 +- .../utility_account_consumed_units_by_type.go | 5 +- .../account/utility_account_deleted_list.go | 5 +- .../account/utility_account_disks_list.go | 5 +- .../account/utility_account_flip_groups.go | 5 +- .../cloudapi/account/utility_account_list.go | 5 +- .../account/utility_account_reserved_units.go | 5 +- .../account/utility_account_rg_list.go | 5 +- .../account/utility_account_templates_list.go | 5 +- .../account/utility_account_vins_list.go | 5 +- .../cloudapi/bservice/data_source_bservice.go | 2 +- .../data_source_bservice_deleted_list.go | 2 +- .../bservice/data_source_bservice_group.go | 2 +- .../bservice/data_source_bservice_list.go | 2 +- .../data_source_bservice_snapshot_list.go | 2 +- .../cloudapi/bservice/resource_bservice.go | 27 +++++---- .../bservice/resource_bservice_group.go | 31 +++++----- .../utility_bservicce_deleted_list.go | 5 +- .../cloudapi/bservice/utility_bservice.go | 5 +- .../bservice/utility_bservice_group.go | 5 +- .../bservice/utility_bservice_list.go | 5 +- .../utility_bservice_snapshot_list.go | 5 +- .../cloudapi/disks/data_source_disk.go | 2 +- .../cloudapi/disks/data_source_disk_list.go | 2 +- .../service/cloudapi/disks/resource_disk.go | 17 +++--- .../service/cloudapi/disks/utility_disk.go | 7 ++- .../cloudapi/disks/utility_disk_list.go | 5 +- .../cloudapi/extnet/data_source_extnet.go | 2 +- .../data_source_extnet_computes_list.go | 2 +- .../extnet/data_source_extnet_default.go | 2 +- .../extnet/data_source_extnet_list.go | 2 +- .../service/cloudapi/extnet/utility_extnet.go | 5 +- .../extnet/utility_extnet_computes_list.go | 5 +- .../cloudapi/extnet/utility_extnet_default.go | 5 +- .../cloudapi/extnet/utility_extnet_list.go | 5 +- internal/service/cloudapi/k8s/resource_k8s.go | 33 +++++------ .../service/cloudapi/k8s/resource_k8s_wg.go | 19 +++--- internal/service/cloudapi/k8s/utility_k8s.go | 5 +- .../service/cloudapi/k8s/utility_k8s_wg.go | 5 +- .../cloudapi/kvmvm/data_source_compute.go | 2 +- .../cloudapi/kvmvm/resource_compute.go | 58 ++++++------------- .../service/cloudapi/kvmvm/utility_compute.go | 25 ++++---- internal/service/cloudapi/pfw/resource_pfw.go | 15 +++-- internal/service/cloudapi/pfw/utility_pfw.go | 5 +- .../service/cloudapi/rg/data_source_rg.go | 2 +- .../cloudapi/rg/data_source_rg_list.go | 2 +- internal/service/cloudapi/rg/resource_rg.go | 17 +++--- internal/service/cloudapi/rg/utility_rg.go | 9 +-- .../service/cloudapi/rg/utility_rg_list.go | 5 +- .../snapshot/data_source_snapshot_list.go | 2 +- .../cloudapi/snapshot/resource_snapshot.go | 17 +++--- .../cloudapi/snapshot/utility_snapshot.go | 5 +- .../snapshot/utility_snapshot_list.go | 5 +- .../service/cloudapi/vgpu/data_source_vgpu.go | 2 +- .../service/cloudapi/vgpu/utility_vgpu.go | 5 +- .../service/cloudapi/vins/data_source_vins.go | 2 +- .../cloudapi/vins/data_source_vins_list.go | 2 +- .../service/cloudapi/vins/resource_vins.go | 17 +++--- .../service/cloudapi/vins/utility_vins.go | 9 +-- .../cloudapi/vins/utility_vins_list.go | 5 +- .../cloudbroker/grid/data_source_grid.go | 2 +- .../cloudbroker/grid/data_source_grid_list.go | 2 +- .../service/cloudbroker/grid/utility_grid.go | 5 +- .../cloudbroker/grid/utility_grid_list.go | 5 +- .../cloudbroker/image/data_source_image.go | 2 +- .../image/data_source_image_list.go | 2 +- .../image/data_source_image_list_stacks.go | 2 +- .../cloudbroker/image/resource_cdrom_image.go | 9 ++- .../image/resource_delete_images.go | 2 +- .../cloudbroker/image/resource_image.go | 53 +++++++++-------- .../image/resource_virtual_image.go | 5 +- .../cloudbroker/image/utility_image.go | 5 +- .../cloudbroker/image/utility_image_list.go | 5 +- .../image/utility_image_list_stacks.go | 5 +- .../pcidevice/data_source_pcidevice.go | 2 +- .../pcidevice/data_source_pcidevice_list.go | 2 +- .../pcidevice/resource_pcidevice.go | 15 +++-- .../pcidevice/utility_pcidevice.go | 5 +- .../pcidevice/utility_pcidevice_list.go | 5 +- .../cloudbroker/sep/data_source_sep.go | 2 +- .../cloudbroker/sep/data_source_sep_config.go | 2 +- .../sep/data_source_sep_consumption.go | 2 +- .../sep/data_source_sep_disk_list.go | 2 +- .../cloudbroker/sep/data_source_sep_list.go | 2 +- .../cloudbroker/sep/data_source_sep_pool.go | 2 +- .../service/cloudbroker/sep/resource_sep.go | 43 +++++++------- .../cloudbroker/sep/resource_sep_config.go | 15 +++-- .../service/cloudbroker/sep/utility_sep.go | 5 +- .../cloudbroker/sep/utility_sep_config.go | 5 +- .../sep/utility_sep_consumption.go | 5 +- .../cloudbroker/sep/utility_sep_disk_list.go | 5 +- .../cloudbroker/sep/utility_sep_list.go | 5 +- .../cloudbroker/sep/utility_sep_pool.go | 5 +- 114 files changed, 406 insertions(+), 390 deletions(-) diff --git a/go.mod b/go.mod index 8663324..1028826 100644 --- a/go.mod +++ b/go.mod @@ -8,4 +8,5 @@ require ( github.com/hashicorp/terraform-plugin-docs v0.5.1 github.com/hashicorp/terraform-plugin-sdk/v2 v2.17.0 // indirect github.com/sirupsen/logrus v1.7.0 + golang.org/x/net v0.0.0-20210326060303-6b1517762897 // indirect ) diff --git a/internal/controller/controller.go b/internal/controller/controller.go index d36389e..ca9d3e3 100644 --- a/internal/controller/controller.go +++ b/internal/controller/controller.go @@ -21,6 +21,7 @@ package controller import ( "bytes" + "context" "crypto/tls" "fmt" "io/ioutil" @@ -325,7 +326,7 @@ func (config *ControllerCfg) validateLegacyUser() (bool, error) { return true, nil } -func (config *ControllerCfg) DecortAPICall(method string, api_name string, url_values *url.Values) (json_resp string, err error) { //nolint:unparam +func (config *ControllerCfg) DecortAPICall(ctx context.Context, method string, api_name string, url_values *url.Values) (json_resp string, err error) { //nolint:unparam // This is a convenience wrapper around standard HTTP request methods that is aware of the // authorization mode for which the provider was initialized and compiles request accordingly. diff --git a/internal/location/location.go b/internal/location/location.go index a5333a9..8305d5f 100644 --- a/internal/location/location.go +++ b/internal/location/location.go @@ -20,6 +20,7 @@ limitations under the License. package location import ( + "context" "encoding/json" "fmt" "net/url" @@ -30,13 +31,13 @@ import ( var DefaultGridID int -func UtilityLocationGetDefaultGridID(m interface{}) (int, error) { +func UtilityLocationGetDefaultGridID(ctx context.Context, m interface{}) (int, error) { c := m.(*controller.ControllerCfg) urlValues := &url.Values{} log.Debug("utilityLocationGetDefaultGridID: retrieving locations list") - apiResp, err := c.DecortAPICall("POST", LocationsListAPI, urlValues) + apiResp, err := c.DecortAPICall(ctx, "POST", LocationsListAPI, urlValues) if err != nil { return 0, err } diff --git a/internal/provider/provider.go b/internal/provider/provider.go index ec3d24d..c6c76f1 100644 --- a/internal/provider/provider.go +++ b/internal/provider/provider.go @@ -25,6 +25,7 @@ import ( "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" "github.com/hashicorp/terraform-plugin-sdk/v2/helper/validation" + "golang.org/x/net/context" "github.com/rudecs/terraform-provider-decort/internal/controller" "github.com/rudecs/terraform-provider-decort/internal/location" @@ -122,7 +123,9 @@ func providerConfigure(d *schema.ResourceData) (interface{}, error) { return nil, err } - gridId, err := location.UtilityLocationGetDefaultGridID(decsController) + ctx := context.Background() + + gridId, err := location.UtilityLocationGetDefaultGridID(ctx, decsController) if err != nil { return nil, err } diff --git a/internal/service/cloudapi/account/data_source_account.go b/internal/service/cloudapi/account/data_source_account.go index 85f4003..f3b2c6e 100644 --- a/internal/service/cloudapi/account/data_source_account.go +++ b/internal/service/cloudapi/account/data_source_account.go @@ -42,7 +42,7 @@ import ( ) func dataSourceAccountRead(ctx context.Context, d *schema.ResourceData, m interface{}) diag.Diagnostics { - acc, err := utilityAccountCheckPresence(d, m) + acc, err := utilityAccountCheckPresence(ctx, d, m) if err != nil { return diag.FromErr(err) } diff --git a/internal/service/cloudapi/account/data_source_account_audits_list.go b/internal/service/cloudapi/account/data_source_account_audits_list.go index 6351c70..d904d12 100644 --- a/internal/service/cloudapi/account/data_source_account_audits_list.go +++ b/internal/service/cloudapi/account/data_source_account_audits_list.go @@ -57,7 +57,7 @@ func flattenAccountAuditsList(aal AccountAuditsList) []map[string]interface{} { } func dataSourceAccountAuditsListRead(ctx context.Context, d *schema.ResourceData, m interface{}) diag.Diagnostics { - accountAuditsList, err := utilityAccountAuditsListCheckPresence(d, m) + accountAuditsList, err := utilityAccountAuditsListCheckPresence(ctx, d, m) if err != nil { return diag.FromErr(err) } diff --git a/internal/service/cloudapi/account/data_source_account_computes_list.go b/internal/service/cloudapi/account/data_source_account_computes_list.go index 9828c2a..39eda42 100644 --- a/internal/service/cloudapi/account/data_source_account_computes_list.go +++ b/internal/service/cloudapi/account/data_source_account_computes_list.go @@ -72,7 +72,7 @@ func flattenAccountComputesList(acl AccountComputesList) []map[string]interface{ } func dataSourceAccountComputesListRead(ctx context.Context, d *schema.ResourceData, m interface{}) diag.Diagnostics { - accountComputesList, err := utilityAccountComputesListCheckPresence(d, m) + accountComputesList, err := utilityAccountComputesListCheckPresence(ctx, d, m) if err != nil { return diag.FromErr(err) } diff --git a/internal/service/cloudapi/account/data_source_account_consumed_units.go b/internal/service/cloudapi/account/data_source_account_consumed_units.go index 52b9f19..bfcc492 100644 --- a/internal/service/cloudapi/account/data_source_account_consumed_units.go +++ b/internal/service/cloudapi/account/data_source_account_consumed_units.go @@ -41,7 +41,7 @@ import ( ) func dataSourceAccountConsumedUnitsRead(ctx context.Context, d *schema.ResourceData, m interface{}) diag.Diagnostics { - accountConsumedUnits, err := utilityAccountConsumedUnitsCheckPresence(d, m) + accountConsumedUnits, err := utilityAccountConsumedUnitsCheckPresence(ctx, d, m) if err != nil { return diag.FromErr(err) } diff --git a/internal/service/cloudapi/account/data_source_account_consumed_units_by_type.go b/internal/service/cloudapi/account/data_source_account_consumed_units_by_type.go index 877608e..1528efb 100644 --- a/internal/service/cloudapi/account/data_source_account_consumed_units_by_type.go +++ b/internal/service/cloudapi/account/data_source_account_consumed_units_by_type.go @@ -41,7 +41,7 @@ import ( ) func dataSourceAccountConsumedUnitsByTypeRead(ctx context.Context, d *schema.ResourceData, m interface{}) diag.Diagnostics { - result, err := utilityAccountConsumedUnitsByTypeCheckPresence(d, m) + result, err := utilityAccountConsumedUnitsByTypeCheckPresence(ctx, d, m) if err != nil { return diag.FromErr(err) } diff --git a/internal/service/cloudapi/account/data_source_account_deleted_list.go b/internal/service/cloudapi/account/data_source_account_deleted_list.go index 0dc1d3f..04120b4 100644 --- a/internal/service/cloudapi/account/data_source_account_deleted_list.go +++ b/internal/service/cloudapi/account/data_source_account_deleted_list.go @@ -41,7 +41,7 @@ import ( ) func dataSourceAccountDeletedListRead(ctx context.Context, d *schema.ResourceData, m interface{}) diag.Diagnostics { - accountDeletedList, err := utilityAccountDeletedListCheckPresence(d, m) + accountDeletedList, err := utilityAccountDeletedListCheckPresence(ctx, d, m) if err != nil { return diag.FromErr(err) } diff --git a/internal/service/cloudapi/account/data_source_account_disks_list.go b/internal/service/cloudapi/account/data_source_account_disks_list.go index 9871eed..fcc12b3 100644 --- a/internal/service/cloudapi/account/data_source_account_disks_list.go +++ b/internal/service/cloudapi/account/data_source_account_disks_list.go @@ -57,7 +57,7 @@ func flattenAccountDisksList(adl AccountDisksList) []map[string]interface{} { } func dataSourceAccountDisksListRead(ctx context.Context, d *schema.ResourceData, m interface{}) diag.Diagnostics { - accountDisksList, err := utilityAccountDisksListCheckPresence(d, m) + accountDisksList, err := utilityAccountDisksListCheckPresence(ctx, d, m) if err != nil { return diag.FromErr(err) } diff --git a/internal/service/cloudapi/account/data_source_account_flipgroups_list.go b/internal/service/cloudapi/account/data_source_account_flipgroups_list.go index 09bc65b..3bcc489 100644 --- a/internal/service/cloudapi/account/data_source_account_flipgroups_list.go +++ b/internal/service/cloudapi/account/data_source_account_flipgroups_list.go @@ -73,7 +73,7 @@ func flattenAccountFlipGroupsList(afgl AccountFlipGroupsList) []map[string]inter } func dataSourceAccountFlipGroupsListRead(ctx context.Context, d *schema.ResourceData, m interface{}) diag.Diagnostics { - accountFlipGroupsList, err := utilityAccountFlipGroupsListCheckPresence(d, m) + accountFlipGroupsList, err := utilityAccountFlipGroupsListCheckPresence(ctx, d, m) if err != nil { return diag.FromErr(err) } diff --git a/internal/service/cloudapi/account/data_source_account_list.go b/internal/service/cloudapi/account/data_source_account_list.go index df625d0..d5370df 100644 --- a/internal/service/cloudapi/account/data_source_account_list.go +++ b/internal/service/cloudapi/account/data_source_account_list.go @@ -119,7 +119,7 @@ func flattenAccountList(al AccountList) []map[string]interface{} { */ func dataSourceAccountListRead(ctx context.Context, d *schema.ResourceData, m interface{}) diag.Diagnostics { - accountList, err := utilityAccountListCheckPresence(d, m) + accountList, err := utilityAccountListCheckPresence(ctx, d, m) if err != nil { return diag.FromErr(err) } diff --git a/internal/service/cloudapi/account/data_source_account_reserved_units.go b/internal/service/cloudapi/account/data_source_account_reserved_units.go index d708129..3d345ea 100644 --- a/internal/service/cloudapi/account/data_source_account_reserved_units.go +++ b/internal/service/cloudapi/account/data_source_account_reserved_units.go @@ -41,7 +41,7 @@ import ( ) func dataSourceAccountReservedUnitsRead(ctx context.Context, d *schema.ResourceData, m interface{}) diag.Diagnostics { - accountReservedUnits, err := utilityAccountReservedUnitsCheckPresence(d, m) + accountReservedUnits, err := utilityAccountReservedUnitsCheckPresence(ctx, d, m) if err != nil { return diag.FromErr(err) } diff --git a/internal/service/cloudapi/account/data_source_account_rg_list.go b/internal/service/cloudapi/account/data_source_account_rg_list.go index 29f885f..c9b94d4 100644 --- a/internal/service/cloudapi/account/data_source_account_rg_list.go +++ b/internal/service/cloudapi/account/data_source_account_rg_list.go @@ -86,7 +86,7 @@ func flattenAccRGResources(argr AccountRGResources) []map[string]interface{} { } func dataSourceAccountRGListRead(ctx context.Context, d *schema.ResourceData, m interface{}) diag.Diagnostics { - accountRGList, err := utilityAccountRGListCheckPresence(d, m) + accountRGList, err := utilityAccountRGListCheckPresence(ctx, d, m) if err != nil { return diag.FromErr(err) } diff --git a/internal/service/cloudapi/account/data_source_account_templates_list.go b/internal/service/cloudapi/account/data_source_account_templates_list.go index 113d9a7..92a6293 100644 --- a/internal/service/cloudapi/account/data_source_account_templates_list.go +++ b/internal/service/cloudapi/account/data_source_account_templates_list.go @@ -62,7 +62,7 @@ func flattenAccountTemplatesList(atl AccountTemplatesList) []map[string]interfac } func dataSourceAccountTemplatesListRead(ctx context.Context, d *schema.ResourceData, m interface{}) diag.Diagnostics { - accountTemplatesList, err := utilityAccountTemplatesListCheckPresence(d, m) + accountTemplatesList, err := utilityAccountTemplatesListCheckPresence(ctx, d, m) if err != nil { return diag.FromErr(err) } diff --git a/internal/service/cloudapi/account/data_source_account_vins_list.go b/internal/service/cloudapi/account/data_source_account_vins_list.go index 6542018..b631e35 100644 --- a/internal/service/cloudapi/account/data_source_account_vins_list.go +++ b/internal/service/cloudapi/account/data_source_account_vins_list.go @@ -69,7 +69,7 @@ func flattenAccountVinsList(avl AccountVinsList) []map[string]interface{} { } func dataSourceAccountVinsListRead(ctx context.Context, d *schema.ResourceData, m interface{}) diag.Diagnostics { - accountVinsList, err := utilityAccountVinsListCheckPresence(d, m) + accountVinsList, err := utilityAccountVinsListCheckPresence(ctx, d, m) if err != nil { return diag.FromErr(err) } diff --git a/internal/service/cloudapi/account/resource_account.go b/internal/service/cloudapi/account/resource_account.go index 14a1222..5aa57f7 100644 --- a/internal/service/cloudapi/account/resource_account.go +++ b/internal/service/cloudapi/account/resource_account.go @@ -50,7 +50,7 @@ func resourceAccountCreate(ctx context.Context, d *schema.ResourceData, m interf log.Debugf("resourceAccountCreate") if accountId, ok := d.GetOk("account_id"); ok { - if exists, err := resourceAccountExists(d, m); exists { + if exists, err := resourceAccountExists(ctx, d, m); exists { if err != nil { return diag.FromErr(err) } @@ -133,7 +133,7 @@ func resourceAccountCreate(ctx context.Context, d *schema.ResourceData, m interf } } - accountId, err := c.DecortAPICall("POST", accountCreateAPI, urlValues) + accountId, err := c.DecortAPICall(ctx, "POST", accountCreateAPI, urlValues) if err != nil { return diag.FromErr(err) } @@ -155,7 +155,7 @@ func resourceAccountCreate(ctx context.Context, d *schema.ResourceData, m interf func resourceAccountRead(ctx context.Context, d *schema.ResourceData, m interface{}) diag.Diagnostics { log.Debugf("resourceAccountRead") - acc, err := utilityAccountCheckPresence(d, m) + acc, err := utilityAccountCheckPresence(ctx, d, m) if acc == nil { d.SetId("") return diag.FromErr(err) @@ -194,7 +194,7 @@ func resourceAccountRead(ctx context.Context, d *schema.ResourceData, m interfac func resourceAccountDelete(ctx context.Context, d *schema.ResourceData, m interface{}) diag.Diagnostics { log.Debugf("resourceAccountDelete") - account, err := utilityAccountCheckPresence(d, m) + account, err := utilityAccountCheckPresence(ctx, d, m) if account == nil { if err != nil { return diag.FromErr(err) @@ -207,7 +207,7 @@ func resourceAccountDelete(ctx context.Context, d *schema.ResourceData, m interf urlValues.Add("accountId", strconv.Itoa(d.Get("account_id").(int))) urlValues.Add("permanently", strconv.FormatBool(d.Get("permanently").(bool))) - _, err = c.DecortAPICall("POST", accountDeleteAPI, urlValues) + _, err = c.DecortAPICall(ctx, "POST", accountDeleteAPI, urlValues) if err != nil { return diag.FromErr(err) } @@ -216,10 +216,10 @@ func resourceAccountDelete(ctx context.Context, d *schema.ResourceData, m interf return nil } -func resourceAccountExists(d *schema.ResourceData, m interface{}) (bool, error) { +func resourceAccountExists(ctx context.Context, d *schema.ResourceData, m interface{}) (bool, error) { log.Debugf("resourceAccountExists") - account, err := utilityAccountCheckPresence(d, m) + account, err := utilityAccountCheckPresence(ctx, d, m) if account == nil { if err != nil { return false, err @@ -243,7 +243,7 @@ func resourceAccountEdit(ctx context.Context, d *schema.ResourceData, m interfac } urlValues.Add("accountId", strconv.Itoa(d.Get("account_id").(int))) - _, err := c.DecortAPICall("POST", api, urlValues) + _, err := c.DecortAPICall(ctx, "POST", api, urlValues) if err != nil { return diag.FromErr(err) } @@ -254,7 +254,7 @@ func resourceAccountEdit(ctx context.Context, d *schema.ResourceData, m interfac if d.HasChange("account_name") { urlValues.Add("name", d.Get("account_name").(string)) urlValues.Add("accountId", strconv.Itoa(d.Get("account_id").(int))) - _, err := c.DecortAPICall("POST", accountUpdateAPI, urlValues) + _, err := c.DecortAPICall(ctx, "POST", accountUpdateAPI, urlValues) if err != nil { return diag.FromErr(err) } @@ -318,7 +318,7 @@ func resourceAccountEdit(ctx context.Context, d *schema.ResourceData, m interfac } urlValues.Add("accountId", strconv.Itoa(d.Get("account_id").(int))) - _, err := c.DecortAPICall("POST", accountUpdateAPI, urlValues) + _, err := c.DecortAPICall(ctx, "POST", accountUpdateAPI, urlValues) if err != nil { return diag.FromErr(err) } @@ -329,7 +329,7 @@ func resourceAccountEdit(ctx context.Context, d *schema.ResourceData, m interfac if d.HasChange("send_access_emails") { urlValues.Add("sendAccessEmails", strconv.FormatBool(d.Get("send_access_emails").(bool))) urlValues.Add("accountId", strconv.Itoa(d.Get("account_id").(int))) - _, err := c.DecortAPICall("POST", accountUpdateAPI, urlValues) + _, err := c.DecortAPICall(ctx, "POST", accountUpdateAPI, urlValues) if err != nil { return diag.FromErr(err) } @@ -341,7 +341,7 @@ func resourceAccountEdit(ctx context.Context, d *schema.ResourceData, m interfac restore := d.Get("restore").(bool) if restore { urlValues.Add("accountId", strconv.Itoa(d.Get("account_id").(int))) - _, err := c.DecortAPICall("POST", accountRestoreAPI, urlValues) + _, err := c.DecortAPICall(ctx, "POST", accountRestoreAPI, urlValues) if err != nil { return diag.FromErr(err) } @@ -379,7 +379,7 @@ func resourceAccountEdit(ctx context.Context, d *schema.ResourceData, m interfac urlValues.Add("accountId", strconv.Itoa(d.Get("account_id").(int))) urlValues.Add("userId", userConv["user_id"].(string)) urlValues.Add("recursivedelete", strconv.FormatBool(userConv["recursive_delete"].(bool))) - _, err := c.DecortAPICall("POST", accountDeleteUserAPI, urlValues) + _, err := c.DecortAPICall(ctx, "POST", accountDeleteUserAPI, urlValues) if err != nil { return diag.FromErr(err) } @@ -394,7 +394,7 @@ func resourceAccountEdit(ctx context.Context, d *schema.ResourceData, m interfac urlValues.Add("accountId", strconv.Itoa(d.Get("account_id").(int))) urlValues.Add("userId", userConv["user_id"].(string)) urlValues.Add("accesstype", strings.ToUpper(userConv["access_type"].(string))) - _, err := c.DecortAPICall("POST", accountAddUserAPI, urlValues) + _, err := c.DecortAPICall(ctx, "POST", accountAddUserAPI, urlValues) if err != nil { return diag.FromErr(err) } @@ -409,7 +409,7 @@ func resourceAccountEdit(ctx context.Context, d *schema.ResourceData, m interfac urlValues.Add("accountId", strconv.Itoa(d.Get("account_id").(int))) urlValues.Add("userId", userConv["user_id"].(string)) urlValues.Add("accesstype", strings.ToUpper(userConv["access_type"].(string))) - _, err := c.DecortAPICall("POST", accountUpdateUserAPI, urlValues) + _, err := c.DecortAPICall(ctx, "POST", accountUpdateUserAPI, urlValues) if err != nil { return diag.FromErr(err) } @@ -786,7 +786,6 @@ func ResourceAccount() *schema.Resource { ReadContext: resourceAccountRead, UpdateContext: resourceAccountEdit, DeleteContext: resourceAccountDelete, - Exists: resourceAccountExists, Importer: &schema.ResourceImporter{ State: schema.ImportStatePassthrough, diff --git a/internal/service/cloudapi/account/utility_account.go b/internal/service/cloudapi/account/utility_account.go index 5d89df6..092162b 100644 --- a/internal/service/cloudapi/account/utility_account.go +++ b/internal/service/cloudapi/account/utility_account.go @@ -32,6 +32,7 @@ Documentation: https://github.com/rudecs/terraform-provider-decort/wiki package account import ( + "context" "encoding/json" "net/url" "strconv" @@ -42,7 +43,7 @@ import ( "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" ) -func utilityAccountCheckPresence(d *schema.ResourceData, m interface{}) (*AccountWithResources, error) { +func utilityAccountCheckPresence(ctx context.Context, d *schema.ResourceData, m interface{}) (*AccountWithResources, error) { account := &AccountWithResources{} c := m.(*controller.ControllerCfg) urlValues := &url.Values{} @@ -54,7 +55,7 @@ func utilityAccountCheckPresence(d *schema.ResourceData, m interface{}) (*Accoun } log.Debugf("utilityAccountCheckPresence: load account") - accountRaw, err := c.DecortAPICall("POST", accountGetAPI, urlValues) + accountRaw, err := c.DecortAPICall(ctx, "POST", accountGetAPI, urlValues) if err != nil { return nil, err } diff --git a/internal/service/cloudapi/account/utility_account_audits_list.go b/internal/service/cloudapi/account/utility_account_audits_list.go index dc61dc8..c89cedd 100644 --- a/internal/service/cloudapi/account/utility_account_audits_list.go +++ b/internal/service/cloudapi/account/utility_account_audits_list.go @@ -32,6 +32,7 @@ Documentation: https://github.com/rudecs/terraform-provider-decort/wiki package account import ( + "context" "encoding/json" "net/url" "strconv" @@ -42,7 +43,7 @@ import ( "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" ) -func utilityAccountAuditsListCheckPresence(d *schema.ResourceData, m interface{}) (AccountAuditsList, error) { +func utilityAccountAuditsListCheckPresence(ctx context.Context, d *schema.ResourceData, m interface{}) (AccountAuditsList, error) { accountAuditsList := AccountAuditsList{} c := m.(*controller.ControllerCfg) urlValues := &url.Values{} @@ -50,7 +51,7 @@ func utilityAccountAuditsListCheckPresence(d *schema.ResourceData, m interface{} urlValues.Add("accountId", strconv.Itoa(d.Get("account_id").(int))) log.Debugf("utilityAccountAuditsListCheckPresence: load account list") - accountAuditsListRaw, err := c.DecortAPICall("POST", accountAuditsAPI, urlValues) + accountAuditsListRaw, err := c.DecortAPICall(ctx, "POST", accountAuditsAPI, urlValues) if err != nil { return nil, err } diff --git a/internal/service/cloudapi/account/utility_account_computes_list.go b/internal/service/cloudapi/account/utility_account_computes_list.go index 957af49..9b746da 100644 --- a/internal/service/cloudapi/account/utility_account_computes_list.go +++ b/internal/service/cloudapi/account/utility_account_computes_list.go @@ -32,6 +32,7 @@ Documentation: https://github.com/rudecs/terraform-provider-decort/wiki package account import ( + "context" "encoding/json" "net/url" "strconv" @@ -42,7 +43,7 @@ import ( "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" ) -func utilityAccountComputesListCheckPresence(d *schema.ResourceData, m interface{}) (AccountComputesList, error) { +func utilityAccountComputesListCheckPresence(ctx context.Context, d *schema.ResourceData, m interface{}) (AccountComputesList, error) { accountComputesList := AccountComputesList{} c := m.(*controller.ControllerCfg) urlValues := &url.Values{} @@ -50,7 +51,7 @@ func utilityAccountComputesListCheckPresence(d *schema.ResourceData, m interface urlValues.Add("accountId", strconv.Itoa(d.Get("account_id").(int))) log.Debugf("utilityAccountComputesListCheckPresence: load account list") - accountComputesListRaw, err := c.DecortAPICall("POST", accountListComputesAPI, urlValues) + accountComputesListRaw, err := c.DecortAPICall(ctx, "POST", accountListComputesAPI, urlValues) if err != nil { return nil, err } diff --git a/internal/service/cloudapi/account/utility_account_consumed_units.go b/internal/service/cloudapi/account/utility_account_consumed_units.go index 295a4fe..5c610fb 100644 --- a/internal/service/cloudapi/account/utility_account_consumed_units.go +++ b/internal/service/cloudapi/account/utility_account_consumed_units.go @@ -32,6 +32,7 @@ Documentation: https://github.com/rudecs/terraform-provider-decort/wiki package account import ( + "context" "encoding/json" "net/url" "strconv" @@ -42,7 +43,7 @@ import ( "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" ) -func utilityAccountConsumedUnitsCheckPresence(d *schema.ResourceData, m interface{}) (*ResourceLimits, error) { +func utilityAccountConsumedUnitsCheckPresence(ctx context.Context, d *schema.ResourceData, m interface{}) (*ResourceLimits, error) { accountConsumedUnits := &ResourceLimits{} c := m.(*controller.ControllerCfg) urlValues := &url.Values{} @@ -50,7 +51,7 @@ func utilityAccountConsumedUnitsCheckPresence(d *schema.ResourceData, m interfac urlValues.Add("accountId", strconv.Itoa(d.Get("account_id").(int))) log.Debugf("utilityAccountConsumedUnitsCheckPresence: load account list") - accountConsumedUnitsRaw, err := c.DecortAPICall("POST", accountGetConsumedUnitsAPI, urlValues) + accountConsumedUnitsRaw, err := c.DecortAPICall(ctx, "POST", accountGetConsumedUnitsAPI, urlValues) if err != nil { return nil, err } diff --git a/internal/service/cloudapi/account/utility_account_consumed_units_by_type.go b/internal/service/cloudapi/account/utility_account_consumed_units_by_type.go index f102c01..1dc9d6b 100644 --- a/internal/service/cloudapi/account/utility_account_consumed_units_by_type.go +++ b/internal/service/cloudapi/account/utility_account_consumed_units_by_type.go @@ -32,6 +32,7 @@ Documentation: https://github.com/rudecs/terraform-provider-decort/wiki package account import ( + "context" "net/url" "strconv" "strings" @@ -42,7 +43,7 @@ import ( "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" ) -func utilityAccountConsumedUnitsByTypeCheckPresence(d *schema.ResourceData, m interface{}) (float64, error) { +func utilityAccountConsumedUnitsByTypeCheckPresence(ctx context.Context, d *schema.ResourceData, m interface{}) (float64, error) { c := m.(*controller.ControllerCfg) urlValues := &url.Values{} @@ -50,7 +51,7 @@ func utilityAccountConsumedUnitsByTypeCheckPresence(d *schema.ResourceData, m in urlValues.Add("cutype", strings.ToUpper(d.Get("cu_type").(string))) log.Debugf("utilityAccountConsumedUnitsByTypeCheckPresence") - resultRaw, err := c.DecortAPICall("POST", accountGetConsumedUnitsByTypeAPI, urlValues) + resultRaw, err := c.DecortAPICall(ctx, "POST", accountGetConsumedUnitsByTypeAPI, urlValues) if err != nil { return 0, err } diff --git a/internal/service/cloudapi/account/utility_account_deleted_list.go b/internal/service/cloudapi/account/utility_account_deleted_list.go index 2395001..f9a8b50 100644 --- a/internal/service/cloudapi/account/utility_account_deleted_list.go +++ b/internal/service/cloudapi/account/utility_account_deleted_list.go @@ -32,6 +32,7 @@ Documentation: https://github.com/rudecs/terraform-provider-decort/wiki package account import ( + "context" "encoding/json" "net/url" "strconv" @@ -42,7 +43,7 @@ import ( "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" ) -func utilityAccountDeletedListCheckPresence(d *schema.ResourceData, m interface{}) (AccountCloudApiList, error) { +func utilityAccountDeletedListCheckPresence(ctx context.Context, d *schema.ResourceData, m interface{}) (AccountCloudApiList, error) { accountDeletedList := AccountCloudApiList{} c := m.(*controller.ControllerCfg) urlValues := &url.Values{} @@ -55,7 +56,7 @@ func utilityAccountDeletedListCheckPresence(d *schema.ResourceData, m interface{ } log.Debugf("utilityAccountDeletedListCheckPresence: load") - accountDeletedListRaw, err := c.DecortAPICall("POST", accountListDeletedAPI, urlValues) + accountDeletedListRaw, err := c.DecortAPICall(ctx, "POST", accountListDeletedAPI, urlValues) if err != nil { return nil, err } diff --git a/internal/service/cloudapi/account/utility_account_disks_list.go b/internal/service/cloudapi/account/utility_account_disks_list.go index 4c0dbd3..7cea8a2 100644 --- a/internal/service/cloudapi/account/utility_account_disks_list.go +++ b/internal/service/cloudapi/account/utility_account_disks_list.go @@ -32,6 +32,7 @@ Documentation: https://github.com/rudecs/terraform-provider-decort/wiki package account import ( + "context" "encoding/json" "net/url" "strconv" @@ -42,7 +43,7 @@ import ( "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" ) -func utilityAccountDisksListCheckPresence(d *schema.ResourceData, m interface{}) (AccountDisksList, error) { +func utilityAccountDisksListCheckPresence(ctx context.Context, d *schema.ResourceData, m interface{}) (AccountDisksList, error) { accountDisksList := AccountDisksList{} c := m.(*controller.ControllerCfg) urlValues := &url.Values{} @@ -50,7 +51,7 @@ func utilityAccountDisksListCheckPresence(d *schema.ResourceData, m interface{}) urlValues.Add("accountId", strconv.Itoa(d.Get("account_id").(int))) log.Debugf("utilityAccountDisksListCheckPresence: load account list") - accountDisksListRaw, err := c.DecortAPICall("POST", accountListDisksAPI, urlValues) + accountDisksListRaw, err := c.DecortAPICall(ctx, "POST", accountListDisksAPI, urlValues) if err != nil { return nil, err } diff --git a/internal/service/cloudapi/account/utility_account_flip_groups.go b/internal/service/cloudapi/account/utility_account_flip_groups.go index d2862b5..1585f6b 100644 --- a/internal/service/cloudapi/account/utility_account_flip_groups.go +++ b/internal/service/cloudapi/account/utility_account_flip_groups.go @@ -32,6 +32,7 @@ Documentation: https://github.com/rudecs/terraform-provider-decort/wiki package account import ( + "context" "encoding/json" "net/url" "strconv" @@ -42,7 +43,7 @@ import ( "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" ) -func utilityAccountFlipGroupsListCheckPresence(d *schema.ResourceData, m interface{}) (AccountFlipGroupsList, error) { +func utilityAccountFlipGroupsListCheckPresence(ctx context.Context, d *schema.ResourceData, m interface{}) (AccountFlipGroupsList, error) { accountFlipGroupsList := AccountFlipGroupsList{} c := m.(*controller.ControllerCfg) urlValues := &url.Values{} @@ -50,7 +51,7 @@ func utilityAccountFlipGroupsListCheckPresence(d *schema.ResourceData, m interfa urlValues.Add("accountId", strconv.Itoa(d.Get("account_id").(int))) log.Debugf("utilityAccountFlipGroupsListCheckPresence") - accountFlipGroupsListRaw, err := c.DecortAPICall("POST", accountListFlipGroupsAPI, urlValues) + accountFlipGroupsListRaw, err := c.DecortAPICall(ctx, "POST", accountListFlipGroupsAPI, urlValues) if err != nil { return nil, err } diff --git a/internal/service/cloudapi/account/utility_account_list.go b/internal/service/cloudapi/account/utility_account_list.go index 3d814ff..2eb7d36 100644 --- a/internal/service/cloudapi/account/utility_account_list.go +++ b/internal/service/cloudapi/account/utility_account_list.go @@ -32,6 +32,7 @@ Documentation: https://github.com/rudecs/terraform-provider-decort/wiki package account import ( + "context" "encoding/json" "net/url" "strconv" @@ -42,7 +43,7 @@ import ( "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" ) -func utilityAccountListCheckPresence(d *schema.ResourceData, m interface{}) (AccountCloudApiList, error) { +func utilityAccountListCheckPresence(ctx context.Context, d *schema.ResourceData, m interface{}) (AccountCloudApiList, error) { accountList := AccountCloudApiList{} c := m.(*controller.ControllerCfg) urlValues := &url.Values{} @@ -55,7 +56,7 @@ func utilityAccountListCheckPresence(d *schema.ResourceData, m interface{}) (Acc } log.Debugf("utilityAccountListCheckPresence: load account list") - accountListRaw, err := c.DecortAPICall("POST", accountListAPI, urlValues) + accountListRaw, err := c.DecortAPICall(ctx, "POST", accountListAPI, urlValues) if err != nil { return nil, err } diff --git a/internal/service/cloudapi/account/utility_account_reserved_units.go b/internal/service/cloudapi/account/utility_account_reserved_units.go index 599964c..5474a12 100644 --- a/internal/service/cloudapi/account/utility_account_reserved_units.go +++ b/internal/service/cloudapi/account/utility_account_reserved_units.go @@ -32,6 +32,7 @@ Documentation: https://github.com/rudecs/terraform-provider-decort/wiki package account import ( + "context" "encoding/json" "net/url" "strconv" @@ -42,7 +43,7 @@ import ( "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" ) -func utilityAccountReservedUnitsCheckPresence(d *schema.ResourceData, m interface{}) (*ResourceLimits, error) { +func utilityAccountReservedUnitsCheckPresence(ctx context.Context, d *schema.ResourceData, m interface{}) (*ResourceLimits, error) { accountReservedUnits := &ResourceLimits{} c := m.(*controller.ControllerCfg) urlValues := &url.Values{} @@ -50,7 +51,7 @@ func utilityAccountReservedUnitsCheckPresence(d *schema.ResourceData, m interfac urlValues.Add("accountId", strconv.Itoa(d.Get("account_id").(int))) log.Debugf("utilityAccountReservedUnitsCheckPresence: load units") - accountReservedUnitsRaw, err := c.DecortAPICall("POST", accountGetReservedUnitsAPI, urlValues) + accountReservedUnitsRaw, err := c.DecortAPICall(ctx, "POST", accountGetReservedUnitsAPI, urlValues) if err != nil { return nil, err } diff --git a/internal/service/cloudapi/account/utility_account_rg_list.go b/internal/service/cloudapi/account/utility_account_rg_list.go index 266ba1c..41c1a76 100644 --- a/internal/service/cloudapi/account/utility_account_rg_list.go +++ b/internal/service/cloudapi/account/utility_account_rg_list.go @@ -32,6 +32,7 @@ Documentation: https://github.com/rudecs/terraform-provider-decort/wiki package account import ( + "context" "encoding/json" "net/url" "strconv" @@ -42,7 +43,7 @@ import ( "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" ) -func utilityAccountRGListCheckPresence(d *schema.ResourceData, m interface{}) (AccountRGList, error) { +func utilityAccountRGListCheckPresence(ctx context.Context, d *schema.ResourceData, m interface{}) (AccountRGList, error) { accountRGList := AccountRGList{} c := m.(*controller.ControllerCfg) urlValues := &url.Values{} @@ -50,7 +51,7 @@ func utilityAccountRGListCheckPresence(d *schema.ResourceData, m interface{}) (A urlValues.Add("accountId", strconv.Itoa(d.Get("account_id").(int))) log.Debugf("utilityAccountRGListCheckPresence: load account list") - accountRGListRaw, err := c.DecortAPICall("POST", accountListRGAPI, urlValues) + accountRGListRaw, err := c.DecortAPICall(ctx, "POST", accountListRGAPI, urlValues) if err != nil { return nil, err } diff --git a/internal/service/cloudapi/account/utility_account_templates_list.go b/internal/service/cloudapi/account/utility_account_templates_list.go index 76f9930..47c13db 100644 --- a/internal/service/cloudapi/account/utility_account_templates_list.go +++ b/internal/service/cloudapi/account/utility_account_templates_list.go @@ -32,6 +32,7 @@ Documentation: https://github.com/rudecs/terraform-provider-decort/wiki package account import ( + "context" "encoding/json" "net/url" "strconv" @@ -42,7 +43,7 @@ import ( "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" ) -func utilityAccountTemplatesListCheckPresence(d *schema.ResourceData, m interface{}) (AccountTemplatesList, error) { +func utilityAccountTemplatesListCheckPresence(ctx context.Context, d *schema.ResourceData, m interface{}) (AccountTemplatesList, error) { accountTemplatesList := AccountTemplatesList{} c := m.(*controller.ControllerCfg) urlValues := &url.Values{} @@ -50,7 +51,7 @@ func utilityAccountTemplatesListCheckPresence(d *schema.ResourceData, m interfac urlValues.Add("accountId", strconv.Itoa(d.Get("account_id").(int))) log.Debugf("utilityAccountTemplatesListCheckPresence: load") - accountTemplatesListRaw, err := c.DecortAPICall("POST", accountListTemplatesAPI, urlValues) + accountTemplatesListRaw, err := c.DecortAPICall(ctx, "POST", accountListTemplatesAPI, urlValues) if err != nil { return nil, err } diff --git a/internal/service/cloudapi/account/utility_account_vins_list.go b/internal/service/cloudapi/account/utility_account_vins_list.go index 72fc5d6..db2e931 100644 --- a/internal/service/cloudapi/account/utility_account_vins_list.go +++ b/internal/service/cloudapi/account/utility_account_vins_list.go @@ -32,6 +32,7 @@ Documentation: https://github.com/rudecs/terraform-provider-decort/wiki package account import ( + "context" "encoding/json" "net/url" "strconv" @@ -42,7 +43,7 @@ import ( "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" ) -func utilityAccountVinsListCheckPresence(d *schema.ResourceData, m interface{}) (AccountVinsList, error) { +func utilityAccountVinsListCheckPresence(ctx context.Context, d *schema.ResourceData, m interface{}) (AccountVinsList, error) { accountVinsList := AccountVinsList{} c := m.(*controller.ControllerCfg) urlValues := &url.Values{} @@ -50,7 +51,7 @@ func utilityAccountVinsListCheckPresence(d *schema.ResourceData, m interface{}) urlValues.Add("accountId", strconv.Itoa(d.Get("account_id").(int))) log.Debugf("utilityAccountVinsListCheckPresence: load account list") - accountVinsListRaw, err := c.DecortAPICall("POST", accountListVinsAPI, urlValues) + accountVinsListRaw, err := c.DecortAPICall(ctx, "POST", accountListVinsAPI, urlValues) if err != nil { return nil, err } diff --git a/internal/service/cloudapi/bservice/data_source_bservice.go b/internal/service/cloudapi/bservice/data_source_bservice.go index ef1fc17..513e0b9 100644 --- a/internal/service/cloudapi/bservice/data_source_bservice.go +++ b/internal/service/cloudapi/bservice/data_source_bservice.go @@ -41,7 +41,7 @@ import ( ) func dataSourceBasicServiceRead(ctx context.Context, d *schema.ResourceData, m interface{}) diag.Diagnostics { - bs, err := utilityBasicServiceCheckPresence(d, m) + bs, err := utilityBasicServiceCheckPresence(ctx, d, m) if err != nil { return diag.FromErr(err) } diff --git a/internal/service/cloudapi/bservice/data_source_bservice_deleted_list.go b/internal/service/cloudapi/bservice/data_source_bservice_deleted_list.go index 4341c43..9be56bf 100644 --- a/internal/service/cloudapi/bservice/data_source_bservice_deleted_list.go +++ b/internal/service/cloudapi/bservice/data_source_bservice_deleted_list.go @@ -41,7 +41,7 @@ import ( ) func dataSourceBasicServiceDeletedListRead(ctx context.Context, d *schema.ResourceData, m interface{}) diag.Diagnostics { - basicServiceDeletedList, err := utilityBasicServiceDeletedListCheckPresence(d, m) + basicServiceDeletedList, err := utilityBasicServiceDeletedListCheckPresence(ctx, d, m) if err != nil { return diag.FromErr(err) } diff --git a/internal/service/cloudapi/bservice/data_source_bservice_group.go b/internal/service/cloudapi/bservice/data_source_bservice_group.go index f333d1c..eaac251 100644 --- a/internal/service/cloudapi/bservice/data_source_bservice_group.go +++ b/internal/service/cloudapi/bservice/data_source_bservice_group.go @@ -41,7 +41,7 @@ import ( ) func dataSourceBasicServiceGroupRead(ctx context.Context, d *schema.ResourceData, m interface{}) diag.Diagnostics { - bsg, err := utilityBasicServiceGroupCheckPresence(d, m) + bsg, err := utilityBasicServiceGroupCheckPresence(ctx, d, m) if err != nil { return diag.FromErr(err) } diff --git a/internal/service/cloudapi/bservice/data_source_bservice_list.go b/internal/service/cloudapi/bservice/data_source_bservice_list.go index d3b2e43..0a367a7 100644 --- a/internal/service/cloudapi/bservice/data_source_bservice_list.go +++ b/internal/service/cloudapi/bservice/data_source_bservice_list.go @@ -73,7 +73,7 @@ func flattenBasicServiceList(bsl BasicServiceList) []map[string]interface{} { } func dataSourceBasicServiceListRead(ctx context.Context, d *schema.ResourceData, m interface{}) diag.Diagnostics { - basicServiceList, err := utilityBasicServiceListCheckPresence(d, m) + basicServiceList, err := utilityBasicServiceListCheckPresence(ctx, d, m) if err != nil { return diag.FromErr(err) } diff --git a/internal/service/cloudapi/bservice/data_source_bservice_snapshot_list.go b/internal/service/cloudapi/bservice/data_source_bservice_snapshot_list.go index 93fe820..ab601e2 100644 --- a/internal/service/cloudapi/bservice/data_source_bservice_snapshot_list.go +++ b/internal/service/cloudapi/bservice/data_source_bservice_snapshot_list.go @@ -41,7 +41,7 @@ import ( ) func dataSourceBasicServiceSnapshotListRead(ctx context.Context, d *schema.ResourceData, m interface{}) diag.Diagnostics { - basicServiceSnapshotList, err := utilityBasicServiceSnapshotListCheckPresence(d, m) + basicServiceSnapshotList, err := utilityBasicServiceSnapshotListCheckPresence(ctx, d, m) if err != nil { return diag.FromErr(err) } diff --git a/internal/service/cloudapi/bservice/resource_bservice.go b/internal/service/cloudapi/bservice/resource_bservice.go index 7456728..9ce62e4 100644 --- a/internal/service/cloudapi/bservice/resource_bservice.go +++ b/internal/service/cloudapi/bservice/resource_bservice.go @@ -48,7 +48,7 @@ func resourceBasicServiceCreate(ctx context.Context, d *schema.ResourceData, m i log.Debugf("resourceBasicServiceCreate") if serviceId, ok := d.GetOk("service_id"); ok { - if exists, err := resourceBasicServiceExists(d, m); exists { + if exists, err := resourceBasicServiceExists(ctx, d, m); exists { if err != nil { return diag.FromErr(err) } @@ -78,7 +78,7 @@ func resourceBasicServiceCreate(ctx context.Context, d *schema.ResourceData, m i urlValues.Add("sshUser", sshUser.(string)) } - serviceId, err := c.DecortAPICall("POST", bserviceCreateAPI, urlValues) + serviceId, err := c.DecortAPICall(ctx, "POST", bserviceCreateAPI, urlValues) if err != nil { return diag.FromErr(err) } @@ -100,7 +100,7 @@ func resourceBasicServiceCreate(ctx context.Context, d *schema.ResourceData, m i func resourceBasicServiceRead(ctx context.Context, d *schema.ResourceData, m interface{}) diag.Diagnostics { log.Debugf("resourceBasicServiceRead") - bs, err := utilityBasicServiceCheckPresence(d, m) + bs, err := utilityBasicServiceCheckPresence(ctx, d, m) if bs == nil { d.SetId("") return diag.FromErr(err) @@ -143,7 +143,7 @@ func resourceBasicServiceRead(ctx context.Context, d *schema.ResourceData, m int func resourceBasicServiceDelete(ctx context.Context, d *schema.ResourceData, m interface{}) diag.Diagnostics { log.Debugf("resourceBasicServiceDelete") - bs, err := utilityBasicServiceCheckPresence(d, m) + bs, err := utilityBasicServiceCheckPresence(ctx, d, m) if bs == nil { if err != nil { return diag.FromErr(err) @@ -156,7 +156,7 @@ func resourceBasicServiceDelete(ctx context.Context, d *schema.ResourceData, m i urlValues.Add("serviceId", strconv.Itoa(d.Get("service_id").(int))) urlValues.Add("permanently", strconv.FormatBool(d.Get("permanently").(bool))) - _, err = c.DecortAPICall("POST", bserviceDeleteAPI, urlValues) + _, err = c.DecortAPICall(ctx, "POST", bserviceDeleteAPI, urlValues) if err != nil { return diag.FromErr(err) } @@ -165,10 +165,10 @@ func resourceBasicServiceDelete(ctx context.Context, d *schema.ResourceData, m i return nil } -func resourceBasicServiceExists(d *schema.ResourceData, m interface{}) (bool, error) { +func resourceBasicServiceExists(ctx context.Context, d *schema.ResourceData, m interface{}) (bool, error) { log.Debugf("resourceBasicServiceExists") - bservice, err := utilityBasicServiceCheckPresence(d, m) + bservice, err := utilityBasicServiceCheckPresence(ctx, d, m) if bservice == nil { if err != nil { return false, err @@ -192,7 +192,7 @@ func resourceBasicServiceEdit(ctx context.Context, d *schema.ResourceData, m int } urlValues.Add("serviceId", strconv.Itoa(d.Get("service_id").(int))) - _, err := c.DecortAPICall("POST", api, urlValues) + _, err := c.DecortAPICall(ctx, "POST", api, urlValues) if err != nil { return diag.FromErr(err) } @@ -204,7 +204,7 @@ func resourceBasicServiceEdit(ctx context.Context, d *schema.ResourceData, m int restore := d.Get("restore").(bool) if restore { urlValues.Add("serviceId", strconv.Itoa(d.Get("service_id").(int))) - _, err := c.DecortAPICall("POST", bserviceRestoreAPI, urlValues) + _, err := c.DecortAPICall(ctx, "POST", bserviceRestoreAPI, urlValues) if err != nil { return diag.FromErr(err) } @@ -221,7 +221,7 @@ func resourceBasicServiceEdit(ctx context.Context, d *schema.ResourceData, m int } urlValues.Add("serviceId", strconv.Itoa(d.Get("service_id").(int))) - _, err := c.DecortAPICall("POST", api, urlValues) + _, err := c.DecortAPICall(ctx, "POST", api, urlValues) if err != nil { return diag.FromErr(err) } @@ -257,7 +257,7 @@ func resourceBasicServiceEdit(ctx context.Context, d *schema.ResourceData, m int snapshotConv := snapshot.(map[string]interface{}) urlValues.Add("serviceId", strconv.Itoa(d.Get("service_id").(int))) urlValues.Add("label", snapshotConv["label"].(string)) - _, err := c.DecortAPICall("POST", bserviceSnapshotDeleteAPI, urlValues) + _, err := c.DecortAPICall(ctx, "POST", bserviceSnapshotDeleteAPI, urlValues) if err != nil { return diag.FromErr(err) } @@ -271,7 +271,7 @@ func resourceBasicServiceEdit(ctx context.Context, d *schema.ResourceData, m int snapshotConv := snapshot.(map[string]interface{}) urlValues.Add("serviceId", strconv.Itoa(d.Get("service_id").(int))) urlValues.Add("label", snapshotConv["label"].(string)) - _, err := c.DecortAPICall("POST", bserviceSnapshotCreateAPI, urlValues) + _, err := c.DecortAPICall(ctx, "POST", bserviceSnapshotCreateAPI, urlValues) if err != nil { return diag.FromErr(err) } @@ -285,7 +285,7 @@ func resourceBasicServiceEdit(ctx context.Context, d *schema.ResourceData, m int snapshotConv := snapshot.(map[string]interface{}) urlValues.Add("serviceId", strconv.Itoa(d.Get("service_id").(int))) urlValues.Add("label", snapshotConv["label"].(string)) - _, err := c.DecortAPICall("POST", bserviceSnapshotRollbackAPI, urlValues) + _, err := c.DecortAPICall(ctx, "POST", bserviceSnapshotRollbackAPI, urlValues) if err != nil { return diag.FromErr(err) } @@ -545,7 +545,6 @@ func ResourceBasicService() *schema.Resource { ReadContext: resourceBasicServiceRead, UpdateContext: resourceBasicServiceEdit, DeleteContext: resourceBasicServiceDelete, - Exists: resourceBasicServiceExists, Importer: &schema.ResourceImporter{ State: schema.ImportStatePassthrough, diff --git a/internal/service/cloudapi/bservice/resource_bservice_group.go b/internal/service/cloudapi/bservice/resource_bservice_group.go index aa2d5a3..47271c8 100644 --- a/internal/service/cloudapi/bservice/resource_bservice_group.go +++ b/internal/service/cloudapi/bservice/resource_bservice_group.go @@ -51,7 +51,7 @@ func resourceBasicServiceGroupCreate(ctx context.Context, d *schema.ResourceData if compgroupId, ok := d.GetOk("compgroup_id"); ok { if _, ok := d.GetOk("service_id"); ok { - if exists, err := resourceBasicServiceGroupExists(d, m); exists { + if exists, err := resourceBasicServiceGroupExists(ctx, d, m); exists { if err != nil { return diag.FromErr(err) } @@ -119,7 +119,7 @@ func resourceBasicServiceGroupCreate(ctx context.Context, d *schema.ResourceData urlValues.Add("extnets", temp) } - compgroupId, err := c.DecortAPICall("POST", bserviceGroupAddAPI, urlValues) + compgroupId, err := c.DecortAPICall(ctx, "POST", bserviceGroupAddAPI, urlValues) if err != nil { return diag.FromErr(err) } @@ -141,7 +141,7 @@ func resourceBasicServiceGroupCreate(ctx context.Context, d *schema.ResourceData func resourceBasicServiceGroupRead(ctx context.Context, d *schema.ResourceData, m interface{}) diag.Diagnostics { log.Debugf("resourceBasicServiceGroupRead") - bsg, err := utilityBasicServiceGroupCheckPresence(d, m) + bsg, err := utilityBasicServiceGroupCheckPresence(ctx, d, m) if bsg == nil { d.SetId("") return diag.FromErr(err) @@ -185,7 +185,7 @@ func resourceBasicServiceGroupRead(ctx context.Context, d *schema.ResourceData, func resourceBasicServiceGroupDelete(ctx context.Context, d *schema.ResourceData, m interface{}) diag.Diagnostics { log.Debugf("resourceBasicServiceGroupDelete") - bsg, err := utilityBasicServiceGroupCheckPresence(d, m) + bsg, err := utilityBasicServiceGroupCheckPresence(ctx, d, m) if bsg == nil { if err != nil { return diag.FromErr(err) @@ -198,7 +198,7 @@ func resourceBasicServiceGroupDelete(ctx context.Context, d *schema.ResourceData urlValues.Add("serviceId", strconv.Itoa(d.Get("service_id").(int))) urlValues.Add("compgroupId", strconv.Itoa(d.Get("compgroup_id").(int))) - _, err = c.DecortAPICall("POST", bserviceGroupRemoveAPI, urlValues) + _, err = c.DecortAPICall(ctx, "POST", bserviceGroupRemoveAPI, urlValues) if err != nil { return diag.FromErr(err) } @@ -207,10 +207,10 @@ func resourceBasicServiceGroupDelete(ctx context.Context, d *schema.ResourceData return nil } -func resourceBasicServiceGroupExists(d *schema.ResourceData, m interface{}) (bool, error) { +func resourceBasicServiceGroupExists(ctx context.Context, d *schema.ResourceData, m interface{}) (bool, error) { log.Debugf("resourceBasicServiceGroupExists") - bserviceGroup, err := utilityBasicServiceGroupCheckPresence(d, m) + bserviceGroup, err := utilityBasicServiceGroupCheckPresence(ctx, d, m) if bserviceGroup == nil { if err != nil { return false, err @@ -232,7 +232,7 @@ func resourceBasicServiceGroupEdit(ctx context.Context, d *schema.ResourceData, urlValues.Add("compgroupId", strconv.Itoa(d.Get("compgroup_id").(int))) urlValues.Add("count", strconv.Itoa(d.Get("comp_count").(int))) urlValues.Add("mode", strings.ToUpper(d.Get("mode").(string))) - _, err := c.DecortAPICall("POST", bserviceGroupResizeAPI, urlValues) + _, err := c.DecortAPICall(ctx, "POST", bserviceGroupResizeAPI, urlValues) if err != nil { return diag.FromErr(err) } @@ -251,7 +251,7 @@ func resourceBasicServiceGroupEdit(ctx context.Context, d *schema.ResourceData, urlValues.Add("serviceId", strconv.Itoa(d.Get("service_id").(int))) urlValues.Add("compgroupId", strconv.Itoa(d.Get("compgroup_id").(int))) - _, err := c.DecortAPICall("POST", api, urlValues) + _, err := c.DecortAPICall(ctx, "POST", api, urlValues) if err != nil { return diag.FromErr(err) } @@ -270,7 +270,7 @@ func resourceBasicServiceGroupEdit(ctx context.Context, d *schema.ResourceData, urlValues.Add("serviceId", strconv.Itoa(d.Get("service_id").(int))) urlValues.Add("compgroupId", strconv.Itoa(d.Get("compgroup_id").(int))) - _, err := c.DecortAPICall("POST", bserviceGroupUpdateAPI, urlValues) + _, err := c.DecortAPICall(ctx, "POST", bserviceGroupUpdateAPI, urlValues) if err != nil { return diag.FromErr(err) } @@ -296,7 +296,7 @@ func resourceBasicServiceGroupEdit(ctx context.Context, d *schema.ResourceData, urlValues.Add("serviceId", strconv.Itoa(d.Get("service_id").(int))) urlValues.Add("compgroupId", strconv.Itoa(d.Get("compgroup_id").(int))) urlValues.Add("extnets", temp) - _, err := c.DecortAPICall("POST", bserviceGroupUpdateExtnetAPI, urlValues) + _, err := c.DecortAPICall(ctx, "POST", bserviceGroupUpdateExtnetAPI, urlValues) if err != nil { return diag.FromErr(err) } @@ -322,7 +322,7 @@ func resourceBasicServiceGroupEdit(ctx context.Context, d *schema.ResourceData, urlValues.Add("serviceId", strconv.Itoa(d.Get("service_id").(int))) urlValues.Add("compgroupId", strconv.Itoa(d.Get("compgroup_id").(int))) urlValues.Add("vinses", temp) - _, err := c.DecortAPICall("POST", bserviceGroupUpdateVinsAPI, urlValues) + _, err := c.DecortAPICall(ctx, "POST", bserviceGroupUpdateVinsAPI, urlValues) if err != nil { return diag.FromErr(err) } @@ -356,7 +356,7 @@ func resourceBasicServiceGroupEdit(ctx context.Context, d *schema.ResourceData, urlValues.Add("compgroupId", strconv.Itoa(d.Get("compgroup_id").(int))) urlValues.Add("parentId", strconv.Itoa(parentConv)) - _, err := c.DecortAPICall("POST", bserviceGroupParentRemoveAPI, urlValues) + _, err := c.DecortAPICall(ctx, "POST", bserviceGroupParentRemoveAPI, urlValues) if err != nil { return diag.FromErr(err) } @@ -371,7 +371,7 @@ func resourceBasicServiceGroupEdit(ctx context.Context, d *schema.ResourceData, urlValues.Add("serviceId", strconv.Itoa(d.Get("service_id").(int))) urlValues.Add("compgroupId", strconv.Itoa(d.Get("compgroup_id").(int))) urlValues.Add("parentId", strconv.Itoa(parentConv)) - _, err := c.DecortAPICall("POST", bserviceGroupParentAddAPI, urlValues) + _, err := c.DecortAPICall(ctx, "POST", bserviceGroupParentAddAPI, urlValues) if err != nil { return diag.FromErr(err) } @@ -389,7 +389,7 @@ func resourceBasicServiceGroupEdit(ctx context.Context, d *schema.ResourceData, urlValues.Add("compgroupId", strconv.Itoa(d.Get("compgroup_id").(int))) urlValues.Add("computeId", strconv.Itoa(rc.(int))) - _, err := c.DecortAPICall("POST", bserviceGroupComputeRemoveAPI, urlValues) + _, err := c.DecortAPICall(ctx, "POST", bserviceGroupComputeRemoveAPI, urlValues) if err != nil { return diag.FromErr(err) } @@ -652,7 +652,6 @@ func ResourceBasicServiceGroup() *schema.Resource { ReadContext: resourceBasicServiceGroupRead, UpdateContext: resourceBasicServiceGroupEdit, DeleteContext: resourceBasicServiceGroupDelete, - Exists: resourceBasicServiceGroupExists, Importer: &schema.ResourceImporter{ State: schema.ImportStatePassthrough, diff --git a/internal/service/cloudapi/bservice/utility_bservicce_deleted_list.go b/internal/service/cloudapi/bservice/utility_bservicce_deleted_list.go index 29d1b7f..114bda1 100644 --- a/internal/service/cloudapi/bservice/utility_bservicce_deleted_list.go +++ b/internal/service/cloudapi/bservice/utility_bservicce_deleted_list.go @@ -32,6 +32,7 @@ Documentation: https://github.com/rudecs/terraform-provider-decort/wiki package bservice import ( + "context" "encoding/json" "net/url" "strconv" @@ -42,7 +43,7 @@ import ( "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" ) -func utilityBasicServiceDeletedListCheckPresence(d *schema.ResourceData, m interface{}) (BasicServiceList, error) { +func utilityBasicServiceDeletedListCheckPresence(ctx context.Context, d *schema.ResourceData, m interface{}) (BasicServiceList, error) { basicServiceDeletedList := BasicServiceList{} c := m.(*controller.ControllerCfg) urlValues := &url.Values{} @@ -61,7 +62,7 @@ func utilityBasicServiceDeletedListCheckPresence(d *schema.ResourceData, m inter } log.Debugf("utilityBasicServiceDeletedListCheckPresence") - basicServiceDeletedListRaw, err := c.DecortAPICall("POST", bserviceListDeletedAPI, urlValues) + basicServiceDeletedListRaw, err := c.DecortAPICall(ctx, "POST", bserviceListDeletedAPI, urlValues) if err != nil { return nil, err } diff --git a/internal/service/cloudapi/bservice/utility_bservice.go b/internal/service/cloudapi/bservice/utility_bservice.go index 57ff329..d2fc168 100644 --- a/internal/service/cloudapi/bservice/utility_bservice.go +++ b/internal/service/cloudapi/bservice/utility_bservice.go @@ -32,6 +32,7 @@ Documentation: https://github.com/rudecs/terraform-provider-decort/wiki package bservice import ( + "context" "encoding/json" "net/url" "strconv" @@ -42,7 +43,7 @@ import ( "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" ) -func utilityBasicServiceCheckPresence(d *schema.ResourceData, m interface{}) (*BasicServiceExtend, error) { +func utilityBasicServiceCheckPresence(ctx context.Context, d *schema.ResourceData, m interface{}) (*BasicServiceExtend, error) { bservice := &BasicServiceExtend{} c := m.(*controller.ControllerCfg) urlValues := &url.Values{} @@ -54,7 +55,7 @@ func utilityBasicServiceCheckPresence(d *schema.ResourceData, m interface{}) (*B } log.Debugf("utilityBasicServiceCheckPresence") - bserviceRaw, err := c.DecortAPICall("POST", bserviceGetAPI, urlValues) + bserviceRaw, err := c.DecortAPICall(ctx, "POST", bserviceGetAPI, urlValues) if err != nil { return nil, err } diff --git a/internal/service/cloudapi/bservice/utility_bservice_group.go b/internal/service/cloudapi/bservice/utility_bservice_group.go index b91d2a7..613258c 100644 --- a/internal/service/cloudapi/bservice/utility_bservice_group.go +++ b/internal/service/cloudapi/bservice/utility_bservice_group.go @@ -32,6 +32,7 @@ Documentation: https://github.com/rudecs/terraform-provider-decort/wiki package bservice import ( + "context" "encoding/json" "net/url" "strconv" @@ -42,7 +43,7 @@ import ( "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" ) -func utilityBasicServiceGroupCheckPresence(d *schema.ResourceData, m interface{}) (*BasicServiceGroup, error) { +func utilityBasicServiceGroupCheckPresence(ctx context.Context, d *schema.ResourceData, m interface{}) (*BasicServiceGroup, error) { bserviceGroup := &BasicServiceGroup{} c := m.(*controller.ControllerCfg) urlValues := &url.Values{} @@ -55,7 +56,7 @@ func utilityBasicServiceGroupCheckPresence(d *schema.ResourceData, m interface{} } log.Debugf("utilityBasicServiceGroupCheckPresence") - bserviceGroupRaw, err := c.DecortAPICall("POST", bserviceGroupGetAPI, urlValues) + bserviceGroupRaw, err := c.DecortAPICall(ctx, "POST", bserviceGroupGetAPI, urlValues) if err != nil { return nil, err } diff --git a/internal/service/cloudapi/bservice/utility_bservice_list.go b/internal/service/cloudapi/bservice/utility_bservice_list.go index 73ec82d..f828fa3 100644 --- a/internal/service/cloudapi/bservice/utility_bservice_list.go +++ b/internal/service/cloudapi/bservice/utility_bservice_list.go @@ -32,6 +32,7 @@ Documentation: https://github.com/rudecs/terraform-provider-decort/wiki package bservice import ( + "context" "encoding/json" "net/url" "strconv" @@ -42,7 +43,7 @@ import ( "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" ) -func utilityBasicServiceListCheckPresence(d *schema.ResourceData, m interface{}) (BasicServiceList, error) { +func utilityBasicServiceListCheckPresence(ctx context.Context, d *schema.ResourceData, m interface{}) (BasicServiceList, error) { basicServiceList := BasicServiceList{} c := m.(*controller.ControllerCfg) urlValues := &url.Values{} @@ -61,7 +62,7 @@ func utilityBasicServiceListCheckPresence(d *schema.ResourceData, m interface{}) } log.Debugf("utilityBasicServiceListCheckPresence") - basicServiceListRaw, err := c.DecortAPICall("POST", bserviceListAPI, urlValues) + basicServiceListRaw, err := c.DecortAPICall(ctx, "POST", bserviceListAPI, urlValues) if err != nil { return nil, err } diff --git a/internal/service/cloudapi/bservice/utility_bservice_snapshot_list.go b/internal/service/cloudapi/bservice/utility_bservice_snapshot_list.go index 3bacdbe..4b7c983 100644 --- a/internal/service/cloudapi/bservice/utility_bservice_snapshot_list.go +++ b/internal/service/cloudapi/bservice/utility_bservice_snapshot_list.go @@ -32,6 +32,7 @@ Documentation: https://github.com/rudecs/terraform-provider-decort/wiki package bservice import ( + "context" "encoding/json" "net/url" "strconv" @@ -42,7 +43,7 @@ import ( "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" ) -func utilityBasicServiceSnapshotListCheckPresence(d *schema.ResourceData, m interface{}) (BasicServiceSnapshots, error) { +func utilityBasicServiceSnapshotListCheckPresence(ctx context.Context, d *schema.ResourceData, m interface{}) (BasicServiceSnapshots, error) { basicServiceSnapshotList := BasicServiceSnapshots{} c := m.(*controller.ControllerCfg) urlValues := &url.Values{} @@ -52,7 +53,7 @@ func utilityBasicServiceSnapshotListCheckPresence(d *schema.ResourceData, m inte } log.Debugf("utilityBasicServiceSnapshotListCheckPresence") - basicServiceSnapshotListRaw, err := c.DecortAPICall("POST", bserviceSnapshotListAPI, urlValues) + basicServiceSnapshotListRaw, err := c.DecortAPICall(ctx, "POST", bserviceSnapshotListAPI, urlValues) if err != nil { return nil, err } diff --git a/internal/service/cloudapi/disks/data_source_disk.go b/internal/service/cloudapi/disks/data_source_disk.go index acaeb0a..46b8cdd 100644 --- a/internal/service/cloudapi/disks/data_source_disk.go +++ b/internal/service/cloudapi/disks/data_source_disk.go @@ -82,7 +82,7 @@ func flattenDisk(d *schema.ResourceData, disk_facts string) error { } func dataSourceDiskRead(ctx context.Context, d *schema.ResourceData, m interface{}) diag.Diagnostics { - disk_facts, err := utilityDiskCheckPresence(d, m) + disk_facts, err := utilityDiskCheckPresence(ctx, d, m) if disk_facts == "" { // if empty string is returned from utilityDiskCheckPresence then there is no // such Disk and err tells so - just return it to the calling party diff --git a/internal/service/cloudapi/disks/data_source_disk_list.go b/internal/service/cloudapi/disks/data_source_disk_list.go index 86914ef..dc73729 100644 --- a/internal/service/cloudapi/disks/data_source_disk_list.go +++ b/internal/service/cloudapi/disks/data_source_disk_list.go @@ -120,7 +120,7 @@ func flattendDiskSnapshotList(sl SnapshotRecordList) []interface{} { } func dataSourceDiskListRead(ctx context.Context, d *schema.ResourceData, m interface{}) diag.Diagnostics { - diskList, err := utilityDiskListCheckPresence(d, m) + diskList, err := utilityDiskListCheckPresence(ctx, d, m) if err != nil { return diag.FromErr(err) } diff --git a/internal/service/cloudapi/disks/resource_disk.go b/internal/service/cloudapi/disks/resource_disk.go index b29f199..1fe2b4a 100644 --- a/internal/service/cloudapi/disks/resource_disk.go +++ b/internal/service/cloudapi/disks/resource_disk.go @@ -73,7 +73,7 @@ func resourceDiskCreate(ctx context.Context, d *schema.ResourceData, m interface urlValues.Add("description", argVal.(string)) } - apiResp, err := c.DecortAPICall("POST", DisksCreateAPI, urlValues) + apiResp, err := c.DecortAPICall(ctx, "POST", DisksCreateAPI, urlValues) if err != nil { return diag.FromErr(err) } @@ -91,7 +91,7 @@ func resourceDiskCreate(ctx context.Context, d *schema.ResourceData, m interface } func resourceDiskRead(ctx context.Context, d *schema.ResourceData, m interface{}) diag.Diagnostics { - diskFacts, err := utilityDiskCheckPresence(d, m) + diskFacts, err := utilityDiskCheckPresence(ctx, d, m) if diskFacts == "" { // if empty string is returned from utilityDiskCheckPresence then there is no // such Disk and err tells so - just return it to the calling party @@ -121,7 +121,7 @@ func resourceDiskUpdate(ctx context.Context, d *schema.ResourceData, m interface sizeParams := &url.Values{} sizeParams.Add("diskId", d.Id()) sizeParams.Add("size", fmt.Sprintf("%d", newSize.(int))) - _, err := c.DecortAPICall("POST", DisksResizeAPI, sizeParams) + _, err := c.DecortAPICall(ctx, "POST", DisksResizeAPI, sizeParams) if err != nil { return diag.FromErr(err) } @@ -137,7 +137,7 @@ func resourceDiskUpdate(ctx context.Context, d *schema.ResourceData, m interface renameParams := &url.Values{} renameParams.Add("diskId", d.Id()) renameParams.Add("name", newName.(string)) - _, err := c.DecortAPICall("POST", DisksRenameAPI, renameParams) + _, err := c.DecortAPICall(ctx, "POST", DisksRenameAPI, renameParams) if err != nil { return diag.FromErr(err) } @@ -165,7 +165,7 @@ func resourceDiskDelete(ctx context.Context, d *schema.ResourceData, m interface log.Debugf("resourceDiskDelete: called for Disk ID / name %d / %s, Account ID %d", d.Get("disk_id").(int), d.Get("name").(string), d.Get("account_id").(int)) - diskFacts, err := utilityDiskCheckPresence(d, m) + diskFacts, err := utilityDiskCheckPresence(ctx, d, m) if diskFacts == "" { if err != nil { return diag.FromErr(err) @@ -187,7 +187,7 @@ func resourceDiskDelete(ctx context.Context, d *schema.ResourceData, m interface params.Add("permanently", "1") c := m.(*controller.ControllerCfg) - _, err = c.DecortAPICall("POST", DisksDeleteAPI, params) + _, err = c.DecortAPICall(ctx, "POST", DisksDeleteAPI, params) if err != nil { return diag.FromErr(err) } @@ -195,12 +195,12 @@ func resourceDiskDelete(ctx context.Context, d *schema.ResourceData, m interface return nil } -func resourceDiskExists(d *schema.ResourceData, m interface{}) (bool, error) { +func resourceDiskExists(ctx context.Context, d *schema.ResourceData, m interface{}) (bool, error) { // Reminder: according to Terraform rules, this function should not modify its ResourceData argument log.Debugf("resourceDiskExists: called for Disk ID / name %d / %s, Account ID %d", d.Get("disk_id").(int), d.Get("name").(string), d.Get("account_id").(int)) - diskFacts, err := utilityDiskCheckPresence(d, m) + diskFacts, err := utilityDiskCheckPresence(ctx, d, m) if diskFacts == "" { if err != nil { return false, err @@ -320,7 +320,6 @@ func ResourceDisk() *schema.Resource { ReadContext: resourceDiskRead, UpdateContext: resourceDiskUpdate, DeleteContext: resourceDiskDelete, - Exists: resourceDiskExists, Importer: &schema.ResourceImporter{ State: schema.ImportStatePassthrough, diff --git a/internal/service/cloudapi/disks/utility_disk.go b/internal/service/cloudapi/disks/utility_disk.go index a76edf0..73053a8 100644 --- a/internal/service/cloudapi/disks/utility_disk.go +++ b/internal/service/cloudapi/disks/utility_disk.go @@ -32,6 +32,7 @@ Documentation: https://github.com/rudecs/terraform-provider-decort/wiki package disks import ( + "context" "encoding/json" "fmt" "net/url" @@ -43,7 +44,7 @@ import ( "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" ) -func utilityDiskCheckPresence(d *schema.ResourceData, m interface{}) (string, error) { +func utilityDiskCheckPresence(ctx context.Context, d *schema.ResourceData, m interface{}) (string, error) { // This function tries to locate Disk by one of the following algorithms depending on // the parameters passed: // - if disk ID is specified -> by disk ID @@ -81,7 +82,7 @@ func utilityDiskCheckPresence(d *schema.ResourceData, m interface{}) (string, er // disk ID is specified, try to get disk instance straight by this ID log.Debugf("utilityDiskCheckPresence: locating disk by its ID %d", theId) urlValues.Add("diskId", fmt.Sprintf("%d", theId)) - diskFacts, err := c.DecortAPICall("POST", DisksGetAPI, urlValues) + diskFacts, err := c.DecortAPICall(ctx, "POST", DisksGetAPI, urlValues) if err != nil { return "", err } @@ -100,7 +101,7 @@ func utilityDiskCheckPresence(d *schema.ResourceData, m interface{}) (string, er // obtain Account ID by account name - it should not be zero on success urlValues.Add("accountId", fmt.Sprintf("%d", d.Get("account_id").(int))) - diskFacts, err := c.DecortAPICall("POST", DisksListAPI, urlValues) + diskFacts, err := c.DecortAPICall(ctx, "POST", DisksListAPI, urlValues) if err != nil { return "", err } diff --git a/internal/service/cloudapi/disks/utility_disk_list.go b/internal/service/cloudapi/disks/utility_disk_list.go index 9100172..50d3cf4 100644 --- a/internal/service/cloudapi/disks/utility_disk_list.go +++ b/internal/service/cloudapi/disks/utility_disk_list.go @@ -32,6 +32,7 @@ Documentation: https://github.com/rudecs/terraform-provider-decort/wiki package disks import ( + "context" "encoding/json" "net/url" "strconv" @@ -43,7 +44,7 @@ import ( "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" ) -func utilityDiskListCheckPresence(d *schema.ResourceData, m interface{}) (DisksListResp, error) { +func utilityDiskListCheckPresence(ctx context.Context, d *schema.ResourceData, m interface{}) (DisksListResp, error) { diskList := DisksListResp{} c := m.(*controller.ControllerCfg) urlValues := &url.Values{} @@ -62,7 +63,7 @@ func utilityDiskListCheckPresence(d *schema.ResourceData, m interface{}) (DisksL } log.Debugf("utilityDiskListCheckPresence: load grid list") - diskListRaw, err := c.DecortAPICall("POST", DisksListAPI, urlValues) + diskListRaw, err := c.DecortAPICall(ctx, "POST", DisksListAPI, urlValues) if err != nil { return nil, err } diff --git a/internal/service/cloudapi/extnet/data_source_extnet.go b/internal/service/cloudapi/extnet/data_source_extnet.go index ec16727..9744b3c 100644 --- a/internal/service/cloudapi/extnet/data_source_extnet.go +++ b/internal/service/cloudapi/extnet/data_source_extnet.go @@ -42,7 +42,7 @@ import ( ) func dataSourceExtnetRead(ctx context.Context, d *schema.ResourceData, m interface{}) diag.Diagnostics { - e, err := utilityExtnetCheckPresence(d, m) + e, err := utilityExtnetCheckPresence(ctx, d, m) if err != nil { return diag.FromErr(err) } diff --git a/internal/service/cloudapi/extnet/data_source_extnet_computes_list.go b/internal/service/cloudapi/extnet/data_source_extnet_computes_list.go index 521f2a7..2ab06e4 100644 --- a/internal/service/cloudapi/extnet/data_source_extnet_computes_list.go +++ b/internal/service/cloudapi/extnet/data_source_extnet_computes_list.go @@ -72,7 +72,7 @@ func flattenExtnetComputesList(ecl ExtnetComputesList) []map[string]interface{} } func dataSourceExtnetComputesListRead(ctx context.Context, d *schema.ResourceData, m interface{}) diag.Diagnostics { - extnetComputesList, err := utilityExtnetComputesListCheckPresence(d, m) + extnetComputesList, err := utilityExtnetComputesListCheckPresence(ctx, d, m) if err != nil { return diag.FromErr(err) } diff --git a/internal/service/cloudapi/extnet/data_source_extnet_default.go b/internal/service/cloudapi/extnet/data_source_extnet_default.go index bf14365..22463eb 100644 --- a/internal/service/cloudapi/extnet/data_source_extnet_default.go +++ b/internal/service/cloudapi/extnet/data_source_extnet_default.go @@ -42,7 +42,7 @@ import ( ) func dataSourceExtnetDefaultRead(ctx context.Context, d *schema.ResourceData, m interface{}) diag.Diagnostics { - extnetId, err := utilityExtnetDefaultCheckPresence(d, m) + extnetId, err := utilityExtnetDefaultCheckPresence(ctx, d, m) if err != nil { return diag.FromErr(err) } diff --git a/internal/service/cloudapi/extnet/data_source_extnet_list.go b/internal/service/cloudapi/extnet/data_source_extnet_list.go index 4d88625..1984b13 100644 --- a/internal/service/cloudapi/extnet/data_source_extnet_list.go +++ b/internal/service/cloudapi/extnet/data_source_extnet_list.go @@ -54,7 +54,7 @@ func flattenExtnetList(el ExtnetList) []map[string]interface{} { } func dataSourceExtnetListRead(ctx context.Context, d *schema.ResourceData, m interface{}) diag.Diagnostics { - extnetList, err := utilityExtnetListCheckPresence(d, m) + extnetList, err := utilityExtnetListCheckPresence(ctx, d, m) if err != nil { return diag.FromErr(err) } diff --git a/internal/service/cloudapi/extnet/utility_extnet.go b/internal/service/cloudapi/extnet/utility_extnet.go index 037dcf9..b3c05d4 100644 --- a/internal/service/cloudapi/extnet/utility_extnet.go +++ b/internal/service/cloudapi/extnet/utility_extnet.go @@ -32,6 +32,7 @@ Documentation: https://github.com/rudecs/terraform-provider-decort/wiki package extnet import ( + "context" "encoding/json" "net/url" "strconv" @@ -42,7 +43,7 @@ import ( "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" ) -func utilityExtnetCheckPresence(d *schema.ResourceData, m interface{}) (*ExtnetDetailed, error) { +func utilityExtnetCheckPresence(ctx context.Context, d *schema.ResourceData, m interface{}) (*ExtnetDetailed, error) { extnet := &ExtnetDetailed{} c := m.(*controller.ControllerCfg) urlValues := &url.Values{} @@ -50,7 +51,7 @@ func utilityExtnetCheckPresence(d *schema.ResourceData, m interface{}) (*ExtnetD urlValues.Add("net_id", strconv.Itoa(d.Get("net_id").(int))) log.Debugf("utilityExtnetCheckPresence") - extnetRaw, err := c.DecortAPICall("POST", extnetGetAPI, urlValues) + extnetRaw, err := c.DecortAPICall(ctx, "POST", extnetGetAPI, urlValues) if err != nil { return nil, err } diff --git a/internal/service/cloudapi/extnet/utility_extnet_computes_list.go b/internal/service/cloudapi/extnet/utility_extnet_computes_list.go index 69f0c5e..68f3d83 100644 --- a/internal/service/cloudapi/extnet/utility_extnet_computes_list.go +++ b/internal/service/cloudapi/extnet/utility_extnet_computes_list.go @@ -32,6 +32,7 @@ Documentation: https://github.com/rudecs/terraform-provider-decort/wiki package extnet import ( + "context" "encoding/json" "net/url" "strconv" @@ -42,7 +43,7 @@ import ( "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" ) -func utilityExtnetComputesListCheckPresence(d *schema.ResourceData, m interface{}) (ExtnetComputesList, error) { +func utilityExtnetComputesListCheckPresence(ctx context.Context, d *schema.ResourceData, m interface{}) (ExtnetComputesList, error) { extnetComputesList := ExtnetComputesList{} c := m.(*controller.ControllerCfg) urlValues := &url.Values{} @@ -50,7 +51,7 @@ func utilityExtnetComputesListCheckPresence(d *schema.ResourceData, m interface{ urlValues.Add("accountId", strconv.Itoa(d.Get("account_id").(int))) log.Debugf("utilityExtnetComputesListCheckPresence") - extnetComputesListRaw, err := c.DecortAPICall("POST", extnetListComputesAPI, urlValues) + extnetComputesListRaw, err := c.DecortAPICall(ctx, "POST", extnetListComputesAPI, urlValues) if err != nil { return nil, err } diff --git a/internal/service/cloudapi/extnet/utility_extnet_default.go b/internal/service/cloudapi/extnet/utility_extnet_default.go index cdf6686..7b7257b 100644 --- a/internal/service/cloudapi/extnet/utility_extnet_default.go +++ b/internal/service/cloudapi/extnet/utility_extnet_default.go @@ -32,6 +32,7 @@ Documentation: https://github.com/rudecs/terraform-provider-decort/wiki package extnet import ( + "context" "net/url" "github.com/rudecs/terraform-provider-decort/internal/controller" @@ -40,12 +41,12 @@ import ( "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" ) -func utilityExtnetDefaultCheckPresence(_ *schema.ResourceData, m interface{}) (string, error) { +func utilityExtnetDefaultCheckPresence(ctx context.Context, d *schema.ResourceData, m interface{}) (string, error) { c := m.(*controller.ControllerCfg) urlValues := &url.Values{} log.Debugf("utilityExtnetDefaultCheckPresence") - res, err := c.DecortAPICall("POST", extnetGetDefaultAPI, urlValues) + res, err := c.DecortAPICall(ctx, "POST", extnetGetDefaultAPI, urlValues) if err != nil { return "", err } diff --git a/internal/service/cloudapi/extnet/utility_extnet_list.go b/internal/service/cloudapi/extnet/utility_extnet_list.go index 56411bf..91b2d5a 100644 --- a/internal/service/cloudapi/extnet/utility_extnet_list.go +++ b/internal/service/cloudapi/extnet/utility_extnet_list.go @@ -32,6 +32,7 @@ Documentation: https://github.com/rudecs/terraform-provider-decort/wiki package extnet import ( + "context" "encoding/json" "net/url" "strconv" @@ -42,7 +43,7 @@ import ( "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" ) -func utilityExtnetListCheckPresence(d *schema.ResourceData, m interface{}) (ExtnetList, error) { +func utilityExtnetListCheckPresence(ctx context.Context, d *schema.ResourceData, m interface{}) (ExtnetList, error) { extnetList := ExtnetList{} c := m.(*controller.ControllerCfg) urlValues := &url.Values{} @@ -58,7 +59,7 @@ func utilityExtnetListCheckPresence(d *schema.ResourceData, m interface{}) (Extn } log.Debugf("utilityExtnetListCheckPresence") - extnetListRaw, err := c.DecortAPICall("POST", extnetListAPI, urlValues) + extnetListRaw, err := c.DecortAPICall(ctx, "POST", extnetListAPI, urlValues) if err != nil { return nil, err } diff --git a/internal/service/cloudapi/k8s/resource_k8s.go b/internal/service/cloudapi/k8s/resource_k8s.go index 59d240c..a7f6301 100644 --- a/internal/service/cloudapi/k8s/resource_k8s.go +++ b/internal/service/cloudapi/k8s/resource_k8s.go @@ -94,7 +94,7 @@ func resourceK8sCreate(ctx context.Context, d *schema.ResourceData, m interface{ //urlValues.Add("desc", desc.(string)) //} - resp, err := c.DecortAPICall("POST", K8sCreateAPI, urlValues) + resp, err := c.DecortAPICall(ctx, "POST", K8sCreateAPI, urlValues) if err != nil { return diag.FromErr(err) } @@ -103,7 +103,7 @@ func resourceK8sCreate(ctx context.Context, d *schema.ResourceData, m interface{ urlValues.Add("auditId", strings.Trim(resp, `"`)) for { - resp, err := c.DecortAPICall("POST", AsyncTaskGetAPI, urlValues) + resp, err := c.DecortAPICall(ctx, "POST", AsyncTaskGetAPI, urlValues) if err != nil { return diag.FromErr(err) } @@ -126,7 +126,7 @@ func resourceK8sCreate(ctx context.Context, d *schema.ResourceData, m interface{ time.Sleep(time.Second * 10) } - k8s, err := utilityK8sCheckPresence(d, m) + k8s, err := utilityK8sCheckPresence(ctx, d, m) if err != nil { return diag.FromErr(err) } @@ -136,7 +136,7 @@ func resourceK8sCreate(ctx context.Context, d *schema.ResourceData, m interface{ urlValues = &url.Values{} urlValues.Add("lbId", strconv.Itoa(k8s.LbID)) - resp, err = c.DecortAPICall("POST", LbGetAPI, urlValues) + resp, err = c.DecortAPICall(ctx, "POST", LbGetAPI, urlValues) if err != nil { return diag.FromErr(err) } @@ -150,7 +150,7 @@ func resourceK8sCreate(ctx context.Context, d *schema.ResourceData, m interface{ urlValues = &url.Values{} urlValues.Add("k8sId", d.Id()) - kubeconfig, err := c.DecortAPICall("POST", K8sGetConfigAPI, urlValues) + kubeconfig, err := c.DecortAPICall(ctx, "POST", K8sGetConfigAPI, urlValues) if err != nil { log.Warnf("could not get kubeconfig: %v", err) } @@ -162,7 +162,7 @@ func resourceK8sCreate(ctx context.Context, d *schema.ResourceData, m interface{ func resourceK8sRead(ctx context.Context, d *schema.ResourceData, m interface{}) diag.Diagnostics { log.Debugf("resourceK8sRead: called with id %s, rg %d", d.Id(), d.Get("rg_id").(int)) - k8s, err := utilityK8sCheckPresence(d, m) + k8s, err := utilityK8sCheckPresence(ctx, d, m) if k8s == nil { d.SetId("") return diag.FromErr(err) @@ -180,7 +180,7 @@ func resourceK8sRead(ctx context.Context, d *schema.ResourceData, m interface{}) urlValues := &url.Values{} urlValues.Add("lbId", strconv.Itoa(k8s.LbID)) - resp, err := c.DecortAPICall("POST", LbGetAPI, urlValues) + resp, err := c.DecortAPICall(ctx, "POST", LbGetAPI, urlValues) if err != nil { return diag.FromErr(err) } @@ -194,7 +194,7 @@ func resourceK8sRead(ctx context.Context, d *schema.ResourceData, m interface{}) urlValues = &url.Values{} urlValues.Add("k8sId", d.Id()) - kubeconfig, err := c.DecortAPICall("POST", K8sGetConfigAPI, urlValues) + kubeconfig, err := c.DecortAPICall(ctx, "POST", K8sGetConfigAPI, urlValues) if err != nil { log.Warnf("could not get kubeconfig: %v", err) } @@ -213,14 +213,14 @@ func resourceK8sUpdate(ctx context.Context, d *schema.ResourceData, m interface{ urlValues.Add("k8sId", d.Id()) urlValues.Add("name", d.Get("name").(string)) - _, err := c.DecortAPICall("POST", K8sUpdateAPI, urlValues) + _, err := c.DecortAPICall(ctx, "POST", K8sUpdateAPI, urlValues) if err != nil { return diag.FromErr(err) } } if d.HasChange("workers") { - k8s, err := utilityK8sCheckPresence(d, m) + k8s, err := utilityK8sCheckPresence(ctx, d, m) if err != nil { return diag.FromErr(err) } @@ -234,13 +234,13 @@ func resourceK8sUpdate(ctx context.Context, d *schema.ResourceData, m interface{ if newWorkers.Num > wg.Num { urlValues.Add("num", strconv.Itoa(newWorkers.Num-wg.Num)) - if _, err := c.DecortAPICall("POST", K8sWorkerAddAPI, urlValues); err != nil { + if _, err := c.DecortAPICall(ctx, "POST", K8sWorkerAddAPI, urlValues); err != nil { return diag.FromErr(err) } } else { for i := wg.Num - 1; i >= newWorkers.Num; i-- { urlValues.Set("workerId", strconv.Itoa(wg.DetailedInfo[i].ID)) - if _, err := c.DecortAPICall("POST", K8sWorkerDeleteAPI, urlValues); err != nil { + if _, err := c.DecortAPICall(ctx, "POST", K8sWorkerDeleteAPI, urlValues); err != nil { return diag.FromErr(err) } } @@ -253,7 +253,7 @@ func resourceK8sUpdate(ctx context.Context, d *schema.ResourceData, m interface{ func resourceK8sDelete(ctx context.Context, d *schema.ResourceData, m interface{}) diag.Diagnostics { log.Debugf("resourceK8sDelete: called with id %s, rg %d", d.Id(), d.Get("rg_id").(int)) - k8s, err := utilityK8sCheckPresence(d, m) + k8s, err := utilityK8sCheckPresence(ctx, d, m) if k8s == nil { if err != nil { return diag.FromErr(err) @@ -266,7 +266,7 @@ func resourceK8sDelete(ctx context.Context, d *schema.ResourceData, m interface{ urlValues.Add("k8sId", d.Id()) urlValues.Add("permanently", "true") - _, err = c.DecortAPICall("POST", K8sDeleteAPI, urlValues) + _, err = c.DecortAPICall(ctx, "POST", K8sDeleteAPI, urlValues) if err != nil { return diag.FromErr(err) } @@ -274,10 +274,10 @@ func resourceK8sDelete(ctx context.Context, d *schema.ResourceData, m interface{ return nil } -func resourceK8sExists(d *schema.ResourceData, m interface{}) (bool, error) { +func resourceK8sExists(ctx context.Context, d *schema.ResourceData, m interface{}) (bool, error) { log.Debugf("resourceK8sExists: called with id %s, rg %d", d.Id(), d.Get("rg_id").(int)) - k8s, err := utilityK8sCheckPresence(d, m) + k8s, err := utilityK8sCheckPresence(ctx, d, m) if k8s == nil { return false, err } @@ -385,7 +385,6 @@ func ResourceK8s() *schema.Resource { ReadContext: resourceK8sRead, UpdateContext: resourceK8sUpdate, DeleteContext: resourceK8sDelete, - Exists: resourceK8sExists, Importer: &schema.ResourceImporter{ State: schema.ImportStatePassthrough, diff --git a/internal/service/cloudapi/k8s/resource_k8s_wg.go b/internal/service/cloudapi/k8s/resource_k8s_wg.go index 420130d..d1eeafb 100644 --- a/internal/service/cloudapi/k8s/resource_k8s_wg.go +++ b/internal/service/cloudapi/k8s/resource_k8s_wg.go @@ -55,7 +55,7 @@ func resourceK8sWgCreate(ctx context.Context, d *schema.ResourceData, m interfac urlValues.Add("workerRam", strconv.Itoa(d.Get("ram").(int))) urlValues.Add("workerDisk", strconv.Itoa(d.Get("disk").(int))) - resp, err := c.DecortAPICall("POST", K8sWgCreateAPI, urlValues) + resp, err := c.DecortAPICall(ctx, "POST", K8sWgCreateAPI, urlValues) if err != nil { return diag.FromErr(err) } @@ -97,7 +97,7 @@ func resourceK8sWgCreate(ctx context.Context, d *schema.ResourceData, m interfac func resourceK8sWgRead(ctx context.Context, d *schema.ResourceData, m interface{}) diag.Diagnostics { log.Debugf("resourceK8sWgRead: called with k8s id %d", d.Get("k8s_id").(int)) - wg, err := utilityK8sWgCheckPresence(d, m) + wg, err := utilityK8sWgCheckPresence(ctx, d, m) if wg == nil { d.SetId("") return diag.FromErr(err) @@ -117,7 +117,7 @@ func resourceK8sWgUpdate(ctx context.Context, d *schema.ResourceData, m interfac c := m.(*controller.ControllerCfg) - wg, err := utilityK8sWgCheckPresence(d, m) + wg, err := utilityK8sWgCheckPresence(ctx, d, m) if err != nil { return diag.FromErr(err) } @@ -128,14 +128,14 @@ func resourceK8sWgUpdate(ctx context.Context, d *schema.ResourceData, m interfac if newNum := d.Get("num").(int); newNum > wg.Num { urlValues.Add("num", strconv.Itoa(newNum-wg.Num)) - _, err := c.DecortAPICall("POST", K8sWorkerAddAPI, urlValues) + _, err := c.DecortAPICall(ctx, "POST", K8sWorkerAddAPI, urlValues) if err != nil { return diag.FromErr(err) } } else { for i := wg.Num - 1; i >= newNum; i-- { urlValues.Set("workerId", strconv.Itoa(wg.DetailedInfo[i].ID)) - _, err := c.DecortAPICall("POST", K8sWorkerDeleteAPI, urlValues) + _, err := c.DecortAPICall(ctx, "POST", K8sWorkerDeleteAPI, urlValues) if err != nil { return diag.FromErr(err) } @@ -148,7 +148,7 @@ func resourceK8sWgUpdate(ctx context.Context, d *schema.ResourceData, m interfac func resourceK8sWgDelete(ctx context.Context, d *schema.ResourceData, m interface{}) diag.Diagnostics { log.Debugf("resourceK8sWgDelete: called with k8s id %d", d.Get("k8s_id").(int)) - wg, err := utilityK8sWgCheckPresence(d, m) + wg, err := utilityK8sWgCheckPresence(ctx, d, m) if wg == nil { if err != nil { return diag.FromErr(err) @@ -161,7 +161,7 @@ func resourceK8sWgDelete(ctx context.Context, d *schema.ResourceData, m interfac urlValues.Add("k8sId", strconv.Itoa(d.Get("k8s_id").(int))) urlValues.Add("workersGroupId", strconv.Itoa(wg.ID)) - _, err = c.DecortAPICall("POST", K8sWgDeleteAPI, urlValues) + _, err = c.DecortAPICall(ctx, "POST", K8sWgDeleteAPI, urlValues) if err != nil { return diag.FromErr(err) } @@ -169,10 +169,10 @@ func resourceK8sWgDelete(ctx context.Context, d *schema.ResourceData, m interfac return nil } -func resourceK8sWgExists(d *schema.ResourceData, m interface{}) (bool, error) { +func resourceK8sWgExists(ctx context.Context, d *schema.ResourceData, m interface{}) (bool, error) { log.Debugf("resourceK8sWgExists: called with k8s id %d", d.Get("k8s_id").(int)) - wg, err := utilityK8sWgCheckPresence(d, m) + wg, err := utilityK8sWgCheckPresence(ctx, d, m) if wg == nil { if err != nil { return false, err @@ -240,7 +240,6 @@ func ResourceK8sWg() *schema.Resource { ReadContext: resourceK8sWgRead, UpdateContext: resourceK8sWgUpdate, DeleteContext: resourceK8sWgDelete, - Exists: resourceK8sWgExists, Importer: &schema.ResourceImporter{ State: schema.ImportStatePassthrough, diff --git a/internal/service/cloudapi/k8s/utility_k8s.go b/internal/service/cloudapi/k8s/utility_k8s.go index b9a5db7..2c4270c 100644 --- a/internal/service/cloudapi/k8s/utility_k8s.go +++ b/internal/service/cloudapi/k8s/utility_k8s.go @@ -32,6 +32,7 @@ Documentation: https://github.com/rudecs/terraform-provider-decort/wiki package k8s import ( + "context" "encoding/json" "net/url" @@ -39,12 +40,12 @@ import ( "github.com/rudecs/terraform-provider-decort/internal/controller" ) -func utilityK8sCheckPresence(d *schema.ResourceData, m interface{}) (*K8sRecord, error) { +func utilityK8sCheckPresence(ctx context.Context, d *schema.ResourceData, m interface{}) (*K8sRecord, error) { c := m.(*controller.ControllerCfg) urlValues := &url.Values{} urlValues.Add("k8sId", d.Id()) - resp, err := c.DecortAPICall("POST", K8sGetAPI, urlValues) + resp, err := c.DecortAPICall(ctx, "POST", K8sGetAPI, urlValues) if err != nil { return nil, err } diff --git a/internal/service/cloudapi/k8s/utility_k8s_wg.go b/internal/service/cloudapi/k8s/utility_k8s_wg.go index e95f6c6..9aef352 100644 --- a/internal/service/cloudapi/k8s/utility_k8s_wg.go +++ b/internal/service/cloudapi/k8s/utility_k8s_wg.go @@ -32,6 +32,7 @@ Documentation: https://github.com/rudecs/terraform-provider-decort/wiki package k8s import ( + "context" "encoding/json" "net/url" "strconv" @@ -40,12 +41,12 @@ import ( "github.com/rudecs/terraform-provider-decort/internal/controller" ) -func utilityK8sWgCheckPresence(d *schema.ResourceData, m interface{}) (*K8sNodeRecord, error) { +func utilityK8sWgCheckPresence(ctx context.Context, d *schema.ResourceData, m interface{}) (*K8sNodeRecord, error) { c := m.(*controller.ControllerCfg) urlValues := &url.Values{} urlValues.Add("k8sId", strconv.Itoa(d.Get("k8s_id").(int))) - resp, err := c.DecortAPICall("POST", K8sGetAPI, urlValues) + resp, err := c.DecortAPICall(ctx, "POST", K8sGetAPI, urlValues) if err != nil { return nil, err } diff --git a/internal/service/cloudapi/kvmvm/data_source_compute.go b/internal/service/cloudapi/kvmvm/data_source_compute.go index 6e66b98..7738409 100644 --- a/internal/service/cloudapi/kvmvm/data_source_compute.go +++ b/internal/service/cloudapi/kvmvm/data_source_compute.go @@ -196,7 +196,7 @@ func flattenCompute(d *schema.ResourceData, compFacts string) error { } func dataSourceComputeRead(ctx context.Context, d *schema.ResourceData, m interface{}) diag.Diagnostics { - compFacts, err := utilityComputeCheckPresence(d, m) + compFacts, err := utilityComputeCheckPresence(ctx, d, m) if compFacts == "" { // if empty string is returned from utilityComputeCheckPresence then there is no // such Compute and err tells so - just return it to the calling party diff --git a/internal/service/cloudapi/kvmvm/resource_compute.go b/internal/service/cloudapi/kvmvm/resource_compute.go index 575c2a8..75dde35 100644 --- a/internal/service/cloudapi/kvmvm/resource_compute.go +++ b/internal/service/cloudapi/kvmvm/resource_compute.go @@ -112,7 +112,7 @@ func resourceComputeCreate(ctx context.Context, d *schema.ResourceData, m interf } } - apiResp, err := c.DecortAPICall("POST", computeCreateAPI, urlValues) + apiResp, err := c.DecortAPICall(ctx, "POST", computeCreateAPI, urlValues) if err != nil { return diag.FromErr(err) } @@ -124,41 +124,26 @@ func resourceComputeCreate(ctx context.Context, d *schema.ResourceData, m interf log.Debugf("resourceComputeCreate: new simple Compute ID %d, name %s created", compId, d.Get("name").(string)) // Configure data disks if any - extraDisksOk := true argVal, argSet = d.GetOk("extra_disks") if argSet && argVal.(*schema.Set).Len() > 0 { // urlValues.Add("desc", argVal.(string)) log.Debugf("resourceComputeCreate: calling utilityComputeExtraDisksConfigure to attach %d extra disk(s)", argVal.(*schema.Set).Len()) - err = utilityComputeExtraDisksConfigure(d, m, false) // do_delta=false, as we are working on a new compute + err = utilityComputeExtraDisksConfigure(ctx, d, m, false) // do_delta=false, as we are working on a new compute if err != nil { log.Errorf("resourceComputeCreate: error when attaching extra disk(s) to a new Compute ID %d: %v", compId, err) - extraDisksOk = false + return diag.FromErr(err) } } - if extraDisksOk { - d.SetPartial("extra_disks") - } - // Configure external networks if any - netsOk := true argVal, argSet = d.GetOk("network") if argSet && argVal.(*schema.Set).Len() > 0 { log.Debugf("resourceComputeCreate: calling utilityComputeNetworksConfigure to attach %d network(s)", argVal.(*schema.Set).Len()) - err = utilityComputeNetworksConfigure(d, m, false) // do_delta=false, as we are working on a new compute + err = utilityComputeNetworksConfigure(ctx, d, m, false) // do_delta=false, as we are working on a new compute if err != nil { log.Errorf("resourceComputeCreate: error when attaching networks to a new Compute ID %d: %s", compId, err) - netsOk = false + return diag.FromErr(err) } } - if netsOk { - // there were no errors reported when configuring networks - d.SetPartial("network") - } - - if extraDisksOk && netsOk { - // if there were no errors in setting any of the subresources, we may leave Partial mode - d.Partial(false) - } // Note bene: we created compute in a STOPPED state (this is required to properly attach 1st network interface), // now we need to start it before we report the sequence complete @@ -166,7 +151,7 @@ func resourceComputeCreate(ctx context.Context, d *schema.ResourceData, m interf reqValues := &url.Values{} reqValues.Add("computeId", fmt.Sprintf("%d", compId)) log.Debugf("resourceComputeCreate: starting Compute ID %d after completing its resource configuration", compId) - if _, err := c.DecortAPICall("POST", ComputeStartAPI, reqValues); err != nil { + if _, err := c.DecortAPICall(ctx, "POST", ComputeStartAPI, reqValues); err != nil { return diag.FromErr(err) } } @@ -184,7 +169,7 @@ func resourceComputeRead(ctx context.Context, d *schema.ResourceData, m interfac log.Debugf("resourceComputeRead: called for Compute name %s, RG ID %d", d.Get("name").(string), d.Get("rg_id").(int)) - compFacts, err := utilityComputeCheckPresence(d, m) + compFacts, err := utilityComputeCheckPresence(ctx, d, m) if compFacts == "" { if err != nil { return diag.FromErr(err) @@ -222,8 +207,6 @@ func resourceComputeUpdate(ctx context.Context, d *schema.ResourceData, m interf doUpdate := false params.Add("computeId", d.Id()) - d.Partial(true) - oldCpu, newCpu := d.GetChange("cpu") if oldCpu.(int) != newCpu.(int) { params.Add("cpu", fmt.Sprintf("%d", newCpu.(int))) @@ -245,13 +228,10 @@ func resourceComputeUpdate(ctx context.Context, d *schema.ResourceData, m interf oldCpu.(int), newCpu.(int), oldRam.(int), newRam.(int)) params.Add("force", "true") - _, err := c.DecortAPICall("POST", ComputeResizeAPI, params) + _, err := c.DecortAPICall(ctx, "POST", ComputeResizeAPI, params) if err != nil { return diag.FromErr(err) } - - d.SetPartial("cpu") - d.SetPartial("ram") } // 2. Resize (grow) Boot disk @@ -262,23 +242,22 @@ func resourceComputeUpdate(ctx context.Context, d *schema.ResourceData, m interf bdsParams.Add("size", fmt.Sprintf("%d", newSize.(int))) log.Debugf("resourceComputeUpdate: compute ID %s, boot disk ID %d resize %d -> %d", d.Id(), d.Get("boot_disk_id").(int), oldSize.(int), newSize.(int)) - _, err := c.DecortAPICall("POST", DisksResizeAPI, bdsParams) + _, err := c.DecortAPICall(ctx, "POST", DisksResizeAPI, bdsParams) if err != nil { return diag.FromErr(err) } - d.SetPartial("boot_disk_size") } else if oldSize.(int) > newSize.(int) { log.Warnf("resourceComputeUpdate: compute ID %s - shrinking boot disk is not allowed", d.Id()) } // 3. Calculate and apply changes to data disks - err := utilityComputeExtraDisksConfigure(d, m, true) // pass do_delta = true to apply changes, if any + err := utilityComputeExtraDisksConfigure(ctx, d, m, true) // pass do_delta = true to apply changes, if any if err != nil { return diag.FromErr(err) } // 4. Calculate and apply changes to network connections - err = utilityComputeNetworksConfigure(d, m, true) // pass do_delta = true to apply changes, if any + err = utilityComputeNetworksConfigure(ctx, d, m, true) // pass do_delta = true to apply changes, if any if err != nil { return diag.FromErr(err) } @@ -287,11 +266,11 @@ func resourceComputeUpdate(ctx context.Context, d *schema.ResourceData, m interf params := &url.Values{} params.Add("computeId", d.Id()) if d.Get("started").(bool) { - if _, err := c.DecortAPICall("POST", ComputeStartAPI, params); err != nil { + if _, err := c.DecortAPICall(ctx, "POST", ComputeStartAPI, params); err != nil { return diag.FromErr(err) } } else { - if _, err := c.DecortAPICall("POST", ComputeStopAPI, params); err != nil { + if _, err := c.DecortAPICall(ctx, "POST", ComputeStopAPI, params); err != nil { return diag.FromErr(err) } } @@ -310,7 +289,7 @@ func resourceComputeDelete(ctx context.Context, d *schema.ResourceData, m interf log.Debugf("resourceComputeDelete: called for Compute name %s, RG ID %d", d.Get("name").(string), d.Get("rg_id").(int)) - compFacts, err := utilityComputeCheckPresence(d, m) + compFacts, err := utilityComputeCheckPresence(ctx, d, m) if compFacts == "" { if err != nil { return diag.FromErr(err) @@ -340,7 +319,7 @@ func resourceComputeDelete(ctx context.Context, d *schema.ResourceData, m interf detachParams.Add("computeId", d.Id()) detachParams.Add("diskId", fmt.Sprintf("%d", diskFacts.ID)) - _, err = c.DecortAPICall("POST", ComputeDiskDetachAPI, detachParams) + _, err = c.DecortAPICall(ctx, "POST", ComputeDiskDetachAPI, detachParams) if err != nil { // We do not fail compute deletion on data disk detach errors log.Errorf("resourceComputeDelete: error when detaching Disk ID %d: %s", diskFacts.ID, err) @@ -353,7 +332,7 @@ func resourceComputeDelete(ctx context.Context, d *schema.ResourceData, m interf params.Add("permanently", "1") // TODO: this is for the upcoming API update - params.Add("detachdisks", "1") - _, err = c.DecortAPICall("POST", ComputeDeleteAPI, params) + _, err = c.DecortAPICall(ctx, "POST", ComputeDeleteAPI, params) if err != nil { return diag.FromErr(err) } @@ -361,12 +340,12 @@ func resourceComputeDelete(ctx context.Context, d *schema.ResourceData, m interf return nil } -func resourceComputeExists(d *schema.ResourceData, m interface{}) (bool, error) { +func resourceComputeExists(ctx context.Context, d *schema.ResourceData, m interface{}) (bool, error) { // Reminder: according to Terraform rules, this function should not modify its ResourceData argument log.Debugf("resourceComputeExist: called for Compute name %s, RG ID %d", d.Get("name").(string), d.Get("rg_id").(int)) - compFacts, err := utilityComputeCheckPresence(d, m) + compFacts, err := utilityComputeCheckPresence(ctx, d, m) if compFacts == "" { if err != nil { return false, err @@ -384,7 +363,6 @@ func ResourceCompute() *schema.Resource { ReadContext: resourceComputeRead, UpdateContext: resourceComputeUpdate, DeleteContext: resourceComputeDelete, - Exists: resourceComputeExists, Importer: &schema.ResourceImporter{ State: schema.ImportStatePassthrough, diff --git a/internal/service/cloudapi/kvmvm/utility_compute.go b/internal/service/cloudapi/kvmvm/utility_compute.go index 894e81d..0bf64ea 100644 --- a/internal/service/cloudapi/kvmvm/utility_compute.go +++ b/internal/service/cloudapi/kvmvm/utility_compute.go @@ -32,6 +32,7 @@ Documentation: https://github.com/rudecs/terraform-provider-decort/wiki package kvmvm import ( + "context" "encoding/json" "fmt" "net/url" @@ -43,7 +44,7 @@ import ( "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" ) -func utilityComputeExtraDisksConfigure(d *schema.ResourceData, m interface{}, do_delta bool) error { +func utilityComputeExtraDisksConfigure(ctx context.Context, d *schema.ResourceData, m interface{}, do_delta bool) error { // d is filled with data according to computeResource schema, so extra disks config is retrieved via "extra_disks" key // If do_delta is true, this function will identify changes between new and existing specs for extra disks and try to // update compute configuration accordingly @@ -71,7 +72,7 @@ func utilityComputeExtraDisksConfigure(d *schema.ResourceData, m interface{}, do urlValues := &url.Values{} urlValues.Add("computeId", d.Id()) urlValues.Add("diskId", fmt.Sprintf("%d", disk.(int))) - _, err := c.DecortAPICall("POST", ComputeDiskAttachAPI, urlValues) + _, err := c.DecortAPICall(ctx, "POST", ComputeDiskAttachAPI, urlValues) if err != nil { // failed to attach extra disk - partial resource update apiErrCount++ @@ -94,7 +95,7 @@ func utilityComputeExtraDisksConfigure(d *schema.ResourceData, m interface{}, do urlValues := &url.Values{} urlValues.Add("computeId", d.Id()) urlValues.Add("diskId", fmt.Sprintf("%d", diskId.(int))) - _, err := c.DecortAPICall("POST", ComputeDiskDetachAPI, urlValues) + _, err := c.DecortAPICall(ctx, "POST", ComputeDiskDetachAPI, urlValues) if err != nil { // failed to detach disk - there will be partial resource update log.Errorf("utilityComputeExtraDisksConfigure: failed to detach disk ID %d from Compute ID %s: %s", diskId.(int), d.Id(), err) @@ -109,7 +110,7 @@ func utilityComputeExtraDisksConfigure(d *schema.ResourceData, m interface{}, do urlValues := &url.Values{} urlValues.Add("computeId", d.Id()) urlValues.Add("diskId", fmt.Sprintf("%d", diskId.(int))) - _, err := c.DecortAPICall("POST", ComputeDiskAttachAPI, urlValues) + _, err := c.DecortAPICall(ctx, "POST", ComputeDiskAttachAPI, urlValues) if err != nil { // failed to attach disk - there will be partial resource update log.Errorf("utilityComputeExtraDisksConfigure: failed to attach disk ID %d to Compute ID %s: %s", diskId.(int), d.Id(), err) @@ -127,7 +128,7 @@ func utilityComputeExtraDisksConfigure(d *schema.ResourceData, m interface{}, do return nil } -func utilityComputeNetworksConfigure(d *schema.ResourceData, m interface{}, do_delta bool) error { +func utilityComputeNetworksConfigure(ctx context.Context, d *schema.ResourceData, m interface{}, do_delta bool) error { // "d" is filled with data according to computeResource schema, so extra networks config is retrieved via "network" key // If do_delta is true, this function will identify changes between new and existing specs for network and try to // update compute configuration accordingly @@ -156,7 +157,7 @@ func utilityComputeNetworksConfigure(d *schema.ResourceData, m interface{}, do_d if ipSet { urlValues.Add("ipAddr", ipaddr.(string)) } - _, err := c.DecortAPICall("POST", ComputeNetAttachAPI, urlValues) + _, err := c.DecortAPICall(ctx, "POST", ComputeNetAttachAPI, urlValues) if err != nil { // failed to attach network - partial resource update apiErrCount++ @@ -180,7 +181,7 @@ func utilityComputeNetworksConfigure(d *schema.ResourceData, m interface{}, do_d urlValues.Add("computeId", d.Id()) urlValues.Add("ipAddr", net_data["ip_address"].(string)) urlValues.Add("mac", net_data["mac"].(string)) - _, err := c.DecortAPICall("POST", ComputeNetDetachAPI, urlValues) + _, err := c.DecortAPICall(ctx, "POST", ComputeNetDetachAPI, urlValues) if err != nil { // failed to detach this network - there will be partial resource update log.Errorf("utilityComputeNetworksConfigure: failed to detach net ID %d of type %s from Compute ID %s: %s", @@ -201,7 +202,7 @@ func utilityComputeNetworksConfigure(d *schema.ResourceData, m interface{}, do_d if net_data["ip_address"].(string) != "" { urlValues.Add("ipAddr", net_data["ip_address"].(string)) } - _, err := c.DecortAPICall("POST", ComputeNetAttachAPI, urlValues) + _, err := c.DecortAPICall(ctx, "POST", ComputeNetAttachAPI, urlValues) if err != nil { // failed to attach this network - there will be partial resource update log.Errorf("utilityComputeNetworksConfigure: failed to attach net ID %d of type %s to Compute ID %s: %s", @@ -220,7 +221,7 @@ func utilityComputeNetworksConfigure(d *schema.ResourceData, m interface{}, do_d return nil } -func utilityComputeCheckPresence(d *schema.ResourceData, m interface{}) (string, error) { +func utilityComputeCheckPresence(ctx context.Context, d *schema.ResourceData, m interface{}) (string, error) { // This function tries to locate Compute by one of the following approaches: // - if compute_id is specified - locate by compute ID // - if compute_name is specified - locate by a combination of compute name and resource @@ -255,7 +256,7 @@ func utilityComputeCheckPresence(d *schema.ResourceData, m interface{}) (string, // compute ID is specified, try to get compute instance straight by this ID log.Debugf("utilityComputeCheckPresence: locating compute by its ID %d", theId) urlValues.Add("computeId", fmt.Sprintf("%d", theId)) - computeFacts, err := c.DecortAPICall("POST", ComputeGetAPI, urlValues) + computeFacts, err := c.DecortAPICall(ctx, "POST", ComputeGetAPI, urlValues) if err != nil { return "", err } @@ -275,7 +276,7 @@ func utilityComputeCheckPresence(d *schema.ResourceData, m interface{}) (string, } urlValues.Add("rgId", fmt.Sprintf("%d", rgId)) - apiResp, err := c.DecortAPICall("POST", RgListComputesAPI, urlValues) + apiResp, err := c.DecortAPICall(ctx, "POST", RgListComputesAPI, urlValues) if err != nil { return "", err } @@ -297,7 +298,7 @@ func utilityComputeCheckPresence(d *schema.ResourceData, m interface{}) (string, // we found the Compute we need - now get detailed information via compute/get API cgetValues := &url.Values{} cgetValues.Add("computeId", fmt.Sprintf("%d", item.ID)) - apiResp, err = c.DecortAPICall("POST", ComputeGetAPI, cgetValues) + apiResp, err = c.DecortAPICall(ctx, "POST", ComputeGetAPI, cgetValues) if err != nil { return "", err } diff --git a/internal/service/cloudapi/pfw/resource_pfw.go b/internal/service/cloudapi/pfw/resource_pfw.go index 381bcb2..199187b 100644 --- a/internal/service/cloudapi/pfw/resource_pfw.go +++ b/internal/service/cloudapi/pfw/resource_pfw.go @@ -59,14 +59,14 @@ func resourcePfwCreate(ctx context.Context, d *schema.ResourceData, m interface{ urlValues.Add("publicPortEnd", strconv.Itoa(portEnd.(int))) } - pfwId, err := c.DecortAPICall("POST", ComputePfwAddAPI, urlValues) + pfwId, err := c.DecortAPICall(ctx, "POST", ComputePfwAddAPI, urlValues) if err != nil { return diag.FromErr(err) } d.SetId(fmt.Sprintf("%d-%s", d.Get("compute_id").(int), pfwId)) - pfw, err := utilityPfwCheckPresence(d, m) + pfw, err := utilityPfwCheckPresence(ctx, d, m) if err != nil { return diag.FromErr(err) } @@ -82,7 +82,7 @@ func resourcePfwCreate(ctx context.Context, d *schema.ResourceData, m interface{ func resourcePfwRead(ctx context.Context, d *schema.ResourceData, m interface{}) diag.Diagnostics { log.Debugf("resourcePfwRead: called for compute %d, rule %s", d.Get("compute_id").(int), d.Id()) - pfw, err := utilityPfwCheckPresence(d, m) + pfw, err := utilityPfwCheckPresence(ctx, d, m) if pfw == nil { d.SetId("") return diag.FromErr(err) @@ -101,7 +101,7 @@ func resourcePfwRead(ctx context.Context, d *schema.ResourceData, m interface{}) func resourcePfwDelete(ctx context.Context, d *schema.ResourceData, m interface{}) diag.Diagnostics { log.Debugf("resourcePfwDelete: called for compute %d, rule %s", d.Get("compute_id").(int), d.Id()) - pfw, err := utilityPfwCheckPresence(d, m) + pfw, err := utilityPfwCheckPresence(ctx, d, m) if pfw == nil { if err != nil { return diag.FromErr(err) @@ -114,7 +114,7 @@ func resourcePfwDelete(ctx context.Context, d *schema.ResourceData, m interface{ urlValues.Add("computeId", strconv.Itoa(d.Get("compute_id").(int))) urlValues.Add("ruleId", strconv.Itoa(pfw.ID)) - _, err = c.DecortAPICall("POST", ComputePfwDelAPI, urlValues) + _, err = c.DecortAPICall(ctx, "POST", ComputePfwDelAPI, urlValues) if err != nil { return diag.FromErr(err) } @@ -122,10 +122,10 @@ func resourcePfwDelete(ctx context.Context, d *schema.ResourceData, m interface{ return nil } -func resourcePfwExists(d *schema.ResourceData, m interface{}) (bool, error) { +func resourcePfwExists(ctx context.Context, d *schema.ResourceData, m interface{}) (bool, error) { log.Debugf("resourcePfwExists: called for compute %d, rule %s", d.Get("compute_id").(int), d.Id()) - pfw, err := utilityPfwCheckPresence(d, m) + pfw, err := utilityPfwCheckPresence(ctx, d, m) if pfw == nil { if err != nil { return false, err @@ -193,7 +193,6 @@ func ResourcePfw() *schema.Resource { CreateContext: resourcePfwCreate, ReadContext: resourcePfwRead, DeleteContext: resourcePfwDelete, - Exists: resourcePfwExists, Importer: &schema.ResourceImporter{ State: schema.ImportStatePassthrough, diff --git a/internal/service/cloudapi/pfw/utility_pfw.go b/internal/service/cloudapi/pfw/utility_pfw.go index af7937f..0f5729f 100644 --- a/internal/service/cloudapi/pfw/utility_pfw.go +++ b/internal/service/cloudapi/pfw/utility_pfw.go @@ -32,6 +32,7 @@ Documentation: https://github.com/rudecs/terraform-provider-decort/wiki package pfw import ( + "context" "encoding/json" "net/url" "strconv" @@ -41,12 +42,12 @@ import ( "github.com/rudecs/terraform-provider-decort/internal/controller" ) -func utilityPfwCheckPresence(d *schema.ResourceData, m interface{}) (*PfwRecord, error) { +func utilityPfwCheckPresence(ctx context.Context, d *schema.ResourceData, m interface{}) (*PfwRecord, error) { c := m.(*controller.ControllerCfg) urlValues := &url.Values{} urlValues.Add("computeId", strconv.Itoa(d.Get("compute_id").(int))) - resp, err := c.DecortAPICall("POST", ComputePfwListAPI, urlValues) + resp, err := c.DecortAPICall(ctx, "POST", ComputePfwListAPI, urlValues) if err != nil { return nil, err } diff --git a/internal/service/cloudapi/rg/data_source_rg.go b/internal/service/cloudapi/rg/data_source_rg.go index 33f7f0e..09d42ec 100644 --- a/internal/service/cloudapi/rg/data_source_rg.go +++ b/internal/service/cloudapi/rg/data_source_rg.go @@ -83,7 +83,7 @@ func flattenResgroup(d *schema.ResourceData, rg_facts string) error { } func dataSourceResgroupRead(ctx context.Context, d *schema.ResourceData, m interface{}) diag.Diagnostics { - rg_facts, err := utilityResgroupCheckPresence(d, m) + rg_facts, err := utilityResgroupCheckPresence(ctx, d, m) if rg_facts == "" { // if empty string is returned from utilityResgroupCheckPresence then there is no // such resource group and err tells so - just return it to the calling party diff --git a/internal/service/cloudapi/rg/data_source_rg_list.go b/internal/service/cloudapi/rg/data_source_rg_list.go index cfd71ba..b33c5ea 100644 --- a/internal/service/cloudapi/rg/data_source_rg_list.go +++ b/internal/service/cloudapi/rg/data_source_rg_list.go @@ -108,7 +108,7 @@ func flattenRgResourceLimits(rl ResourceLimits) []map[string]interface{} { } func dataSourceRgListRead(ctx context.Context, d *schema.ResourceData, m interface{}) diag.Diagnostics { - rgList, err := utilityRgListCheckPresence(d, m) + rgList, err := utilityRgListCheckPresence(ctx, d, m) if err != nil { return diag.FromErr(err) } diff --git a/internal/service/cloudapi/rg/resource_rg.go b/internal/service/cloudapi/rg/resource_rg.go index 815c427..d893334 100644 --- a/internal/service/cloudapi/rg/resource_rg.go +++ b/internal/service/cloudapi/rg/resource_rg.go @@ -125,7 +125,7 @@ func resourceResgroupCreate(ctx context.Context, d *schema.ResourceData, m inter url_values.Add("extIp", ext_ip.(string)) } - api_resp, err := c.DecortAPICall("POST", ResgroupCreateAPI, url_values) + api_resp, err := c.DecortAPICall(ctx, "POST", ResgroupCreateAPI, url_values) if err != nil { return diag.FromErr(err) } @@ -133,7 +133,7 @@ func resourceResgroupCreate(ctx context.Context, d *schema.ResourceData, m inter d.SetId(api_resp) // rg/create API returns ID of the newly creted resource group on success // rg.ID, _ = strconv.Atoi(api_resp) if !set_quota { - resp, err := utilityResgroupCheckPresence(d, m) + resp, err := utilityResgroupCheckPresence(ctx, d, m) if err != nil { return diag.FromErr(err) } @@ -154,7 +154,7 @@ func resourceResgroupRead(ctx context.Context, d *schema.ResourceData, m interfa log.Debugf("resourceResgroupRead: called for RG name %s, account ID %d", d.Get("name").(string), d.Get("account_id").(int)) - rg_facts, err := utilityResgroupCheckPresence(d, m) + rg_facts, err := utilityResgroupCheckPresence(ctx, d, m) if rg_facts == "" { // if empty string is returned from utilityResgroupCheckPresence then there is no // such resource group and err tells so - just return it to the calling party @@ -255,7 +255,7 @@ func resourceResgroupUpdate(ctx context.Context, d *schema.ResourceData, m inter if do_general_update { log.Debugf("resourceResgroupUpdate: detected delta between new and old RG specs - updating the RG") - _, err := c.DecortAPICall("POST", ResgroupUpdateAPI, url_values) + _, err := c.DecortAPICall(ctx, "POST", ResgroupUpdateAPI, url_values) if err != nil { return diag.FromErr(err) } @@ -272,7 +272,7 @@ func resourceResgroupDelete(ctx context.Context, d *schema.ResourceData, m inter log.Debugf("resourceResgroupDelete: called for RG name %s, account ID %d", d.Get("name").(string), d.Get("account_id").(int)) - rg_facts, err := utilityResgroupCheckPresence(d, m) + rg_facts, err := utilityResgroupCheckPresence(ctx, d, m) if rg_facts == "" { if err != nil { return diag.FromErr(err) @@ -289,7 +289,7 @@ func resourceResgroupDelete(ctx context.Context, d *schema.ResourceData, m inter url_values.Add("reason", "Destroyed by DECORT Terraform provider") c := m.(*controller.ControllerCfg) - _, err = c.DecortAPICall("POST", ResgroupDeleteAPI, url_values) + _, err = c.DecortAPICall(ctx, "POST", ResgroupDeleteAPI, url_values) if err != nil { return diag.FromErr(err) } @@ -297,9 +297,9 @@ func resourceResgroupDelete(ctx context.Context, d *schema.ResourceData, m inter return nil } -func resourceResgroupExists(d *schema.ResourceData, m interface{}) (bool, error) { +func resourceResgroupExists(ctx context.Context, d *schema.ResourceData, m interface{}) (bool, error) { // Reminder: according to Terraform rules, this function should NOT modify ResourceData argument - rg_facts, err := utilityResgroupCheckPresence(d, m) + rg_facts, err := utilityResgroupCheckPresence(ctx, d, m) if rg_facts == "" { if err != nil { return false, err @@ -317,7 +317,6 @@ func ResourceResgroup() *schema.Resource { ReadContext: resourceResgroupRead, UpdateContext: resourceResgroupUpdate, DeleteContext: resourceResgroupDelete, - Exists: resourceResgroupExists, Importer: &schema.ResourceImporter{ State: schema.ImportStatePassthrough, diff --git a/internal/service/cloudapi/rg/utility_rg.go b/internal/service/cloudapi/rg/utility_rg.go index f2253e8..c7c3b94 100644 --- a/internal/service/cloudapi/rg/utility_rg.go +++ b/internal/service/cloudapi/rg/utility_rg.go @@ -32,6 +32,7 @@ Documentation: https://github.com/rudecs/terraform-provider-decort/wiki package rg import ( + "context" "encoding/json" "fmt" "net/url" @@ -45,7 +46,7 @@ import ( // On success this function returns a string, as returned by API rg/get, which could be unmarshalled // into ResgroupGetResp structure -func utilityResgroupCheckPresence(d *schema.ResourceData, m interface{}) (string, error) { +func utilityResgroupCheckPresence(ctx context.Context, d *schema.ResourceData, m interface{}) (string, error) { // This function tries to locate resource group by one of the following algorithms depending // on the parameters passed: // - if resource group ID is specified -> by RG ID @@ -84,7 +85,7 @@ func utilityResgroupCheckPresence(d *schema.ResourceData, m interface{}) (string // go straight for the RG by its ID log.Debugf("utilityResgroupCheckPresence: locating RG by its ID %d", theId) urlValues.Add("rgId", fmt.Sprintf("%d", theId)) - rgFacts, err := c.DecortAPICall("POST", ResgroupGetAPI, urlValues) + rgFacts, err := c.DecortAPICall(ctx, "POST", ResgroupGetAPI, urlValues) if err != nil { return "", err } @@ -101,7 +102,7 @@ func utilityResgroupCheckPresence(d *schema.ResourceData, m interface{}) (string // obtain Account ID by account name - it should not be zero on success urlValues.Add("includedeleted", "false") - apiResp, err := c.DecortAPICall("POST", ResgroupListAPI, urlValues) + apiResp, err := c.DecortAPICall(ctx, "POST", ResgroupListAPI, urlValues) if err != nil { return "", err } @@ -125,7 +126,7 @@ func utilityResgroupCheckPresence(d *schema.ResourceData, m interface{}) (string // Namely, we need resource quota settings reqValues := &url.Values{} reqValues.Add("rgId", fmt.Sprintf("%d", item.ID)) - apiResp, err := c.DecortAPICall("POST", ResgroupGetAPI, reqValues) + apiResp, err := c.DecortAPICall(ctx, "POST", ResgroupGetAPI, reqValues) if err != nil { return "", err } diff --git a/internal/service/cloudapi/rg/utility_rg_list.go b/internal/service/cloudapi/rg/utility_rg_list.go index 19a3b81..3342105 100644 --- a/internal/service/cloudapi/rg/utility_rg_list.go +++ b/internal/service/cloudapi/rg/utility_rg_list.go @@ -32,6 +32,7 @@ Documentation: https://github.com/rudecs/terraform-provider-decort/wiki package rg import ( + "context" "encoding/json" "net/url" "strconv" @@ -42,7 +43,7 @@ import ( "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" ) -func utilityRgListCheckPresence(d *schema.ResourceData, m interface{}) (ResgroupListResp, error) { +func utilityRgListCheckPresence(ctx context.Context, d *schema.ResourceData, m interface{}) (ResgroupListResp, error) { c := m.(*controller.ControllerCfg) urlValues := &url.Values{} @@ -59,7 +60,7 @@ func utilityRgListCheckPresence(d *schema.ResourceData, m interface{}) (Resgroup } log.Debugf("utilityRgListCheckPresence: load rg list") - rgListRaw, err := c.DecortAPICall("POST", ResgroupListAPI, urlValues) + rgListRaw, err := c.DecortAPICall(ctx, "POST", ResgroupListAPI, urlValues) if err != nil { return nil, err } diff --git a/internal/service/cloudapi/snapshot/data_source_snapshot_list.go b/internal/service/cloudapi/snapshot/data_source_snapshot_list.go index 61a1cb5..0fe01c1 100644 --- a/internal/service/cloudapi/snapshot/data_source_snapshot_list.go +++ b/internal/service/cloudapi/snapshot/data_source_snapshot_list.go @@ -56,7 +56,7 @@ func flattenSnapshotList(gl SnapshotList) []map[string]interface{} { } func dataSourceSnapshotListRead(ctx context.Context, d *schema.ResourceData, m interface{}) diag.Diagnostics { - snapshotList, err := utilitySnapshotListCheckPresence(d, m) + snapshotList, err := utilitySnapshotListCheckPresence(ctx, d, m) if err != nil { return diag.FromErr(err) } diff --git a/internal/service/cloudapi/snapshot/resource_snapshot.go b/internal/service/cloudapi/snapshot/resource_snapshot.go index b208092..9a8fbc7 100644 --- a/internal/service/cloudapi/snapshot/resource_snapshot.go +++ b/internal/service/cloudapi/snapshot/resource_snapshot.go @@ -52,7 +52,7 @@ func resourceSnapshotCreate(ctx context.Context, d *schema.ResourceData, m inter urlValues.Add("label", d.Get("label").(string)) urlValues.Add("computeId", strconv.Itoa(d.Get("compute_id").(int))) - snapshotId, err := c.DecortAPICall("POST", snapshotCreateAPI, urlValues) + snapshotId, err := c.DecortAPICall(ctx, "POST", snapshotCreateAPI, urlValues) if err != nil { return diag.FromErr(err) } @@ -71,7 +71,7 @@ func resourceSnapshotCreate(ctx context.Context, d *schema.ResourceData, m inter } func resourceSnapshotRead(ctx context.Context, d *schema.ResourceData, m interface{}) diag.Diagnostics { - snapshot, err := utilitySnapshotCheckPresence(d, m) + snapshot, err := utilitySnapshotCheckPresence(ctx, d, m) if err != nil { return diag.FromErr(err) } @@ -92,7 +92,7 @@ func resourceSnapshotDelete(ctx context.Context, d *schema.ResourceData, m inter urlValues.Add("computeId", strconv.Itoa(d.Get("compute_id").(int))) urlValues.Add("label", d.Get("label").(string)) - _, err := c.DecortAPICall("POST", snapshotDeleteAPI, urlValues) + _, err := c.DecortAPICall(ctx, "POST", snapshotDeleteAPI, urlValues) if err != nil { return diag.FromErr(err) } @@ -101,8 +101,8 @@ func resourceSnapshotDelete(ctx context.Context, d *schema.ResourceData, m inter return nil } -func resourceSnapshotExists(d *schema.ResourceData, m interface{}) (bool, error) { - snapshot, err := utilitySnapshotCheckPresence(d, m) +func resourceSnapshotExists(ctx context.Context, d *schema.ResourceData, m interface{}) (bool, error) { + snapshot, err := utilitySnapshotCheckPresence(ctx, d, m) if err != nil { return false, err } @@ -116,7 +116,7 @@ func resourceSnapshotExists(d *schema.ResourceData, m interface{}) (bool, error) func resourceSnapshotEdit(ctx context.Context, d *schema.ResourceData, m interface{}) diag.Diagnostics { if d.HasChange("rollback") { if d.Get("rollback").(bool) { - err := resourceSnapshotRollback(d, m) + err := resourceSnapshotRollback(ctx, d, m) if err != nil { return diag.FromErr(err) } @@ -126,14 +126,14 @@ func resourceSnapshotEdit(ctx context.Context, d *schema.ResourceData, m interfa return nil } -func resourceSnapshotRollback(d *schema.ResourceData, m interface{}) error { +func resourceSnapshotRollback(ctx context.Context, d *schema.ResourceData, m interface{}) error { c := m.(*controller.ControllerCfg) urlValues := &url.Values{} urlValues.Add("computeId", strconv.Itoa(d.Get("compute_id").(int))) urlValues.Add("label", d.Get("label").(string)) - _, err := c.DecortAPICall("POST", snapshotRollbackAPI, urlValues) + _, err := c.DecortAPICall(ctx, "POST", snapshotRollbackAPI, urlValues) if err != nil { return err } @@ -188,7 +188,6 @@ func ResourceSnapshot() *schema.Resource { ReadContext: resourceSnapshotRead, UpdateContext: resourceSnapshotEdit, DeleteContext: resourceSnapshotDelete, - Exists: resourceSnapshotExists, Importer: &schema.ResourceImporter{ State: schema.ImportStatePassthrough, diff --git a/internal/service/cloudapi/snapshot/utility_snapshot.go b/internal/service/cloudapi/snapshot/utility_snapshot.go index e126a10..b99509b 100644 --- a/internal/service/cloudapi/snapshot/utility_snapshot.go +++ b/internal/service/cloudapi/snapshot/utility_snapshot.go @@ -32,13 +32,14 @@ Documentation: https://github.com/rudecs/terraform-provider-decort/wiki package snapshot import ( + "context" "errors" "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" ) -func utilitySnapshotCheckPresence(d *schema.ResourceData, m interface{}) (*Snapshot, error) { - snapShotList, err := utilitySnapshotListCheckPresence(d, m) +func utilitySnapshotCheckPresence(ctx context.Context, d *schema.ResourceData, m interface{}) (*Snapshot, error) { + snapShotList, err := utilitySnapshotListCheckPresence(ctx, d, m) if err != nil { return nil, err } diff --git a/internal/service/cloudapi/snapshot/utility_snapshot_list.go b/internal/service/cloudapi/snapshot/utility_snapshot_list.go index 4f80c90..e06ac5b 100644 --- a/internal/service/cloudapi/snapshot/utility_snapshot_list.go +++ b/internal/service/cloudapi/snapshot/utility_snapshot_list.go @@ -32,6 +32,7 @@ Documentation: https://github.com/rudecs/terraform-provider-decort/wiki package snapshot import ( + "context" "encoding/json" "net/url" "strconv" @@ -40,12 +41,12 @@ import ( "github.com/rudecs/terraform-provider-decort/internal/controller" ) -func utilitySnapshotListCheckPresence(d *schema.ResourceData, m interface{}) (SnapshotList, error) { +func utilitySnapshotListCheckPresence(ctx context.Context, d *schema.ResourceData, m interface{}) (SnapshotList, error) { c := m.(*controller.ControllerCfg) urlValues := &url.Values{} urlValues.Add("computeId", strconv.Itoa(d.Get("compute_id").(int))) - resp, err := c.DecortAPICall("POST", snapshotListAPI, urlValues) + resp, err := c.DecortAPICall(ctx, "POST", snapshotListAPI, urlValues) if err != nil { return nil, err } diff --git a/internal/service/cloudapi/vgpu/data_source_vgpu.go b/internal/service/cloudapi/vgpu/data_source_vgpu.go index 0c66086..763b26d 100644 --- a/internal/service/cloudapi/vgpu/data_source_vgpu.go +++ b/internal/service/cloudapi/vgpu/data_source_vgpu.go @@ -40,7 +40,7 @@ import ( ) func dataSourceVGPURead(ctx context.Context, d *schema.ResourceData, m interface{}) diag.Diagnostics { - vgpu, err := utilityVGPUCheckPresence(d, m) + vgpu, err := utilityVGPUCheckPresence(ctx, d, m) if vgpu == nil { d.SetId("") return diag.FromErr(err) diff --git a/internal/service/cloudapi/vgpu/utility_vgpu.go b/internal/service/cloudapi/vgpu/utility_vgpu.go index fd00ee4..65366cd 100644 --- a/internal/service/cloudapi/vgpu/utility_vgpu.go +++ b/internal/service/cloudapi/vgpu/utility_vgpu.go @@ -32,6 +32,7 @@ Documentation: https://github.com/rudecs/terraform-provider-decort/wiki package vgpu import ( + "context" "encoding/json" "net/url" "strconv" @@ -40,7 +41,7 @@ import ( "github.com/rudecs/terraform-provider-decort/internal/controller" ) -func utilityVGPUCheckPresence(d *schema.ResourceData, m interface{}) (*VGPU, error) { +func utilityVGPUCheckPresence(ctx context.Context, d *schema.ResourceData, m interface{}) (*VGPU, error) { c := m.(*controller.ControllerCfg) urlValues := &url.Values{} urlValues.Add("size", "50") @@ -59,7 +60,7 @@ func utilityVGPUCheckPresence(d *schema.ResourceData, m interface{}) (*VGPU, err for page := 1; ; page++ { urlValues.Set("page", strconv.Itoa(page)) - resp, err := c.DecortAPICall("POST", vgpuListAPI, urlValues) + resp, err := c.DecortAPICall(ctx, "POST", vgpuListAPI, urlValues) if err != nil { return nil, err } diff --git a/internal/service/cloudapi/vins/data_source_vins.go b/internal/service/cloudapi/vins/data_source_vins.go index b6419b7..2bcd362 100644 --- a/internal/service/cloudapi/vins/data_source_vins.go +++ b/internal/service/cloudapi/vins/data_source_vins.go @@ -97,7 +97,7 @@ func flattenVins(d *schema.ResourceData, vins_facts string) diag.Diagnostics { } func dataSourceVinsRead(ctx context.Context, d *schema.ResourceData, m interface{}) diag.Diagnostics { - vinsFacts, err := utilityVinsCheckPresence(d, m) + vinsFacts, err := utilityVinsCheckPresence(ctx, d, m) if vinsFacts == "" { // if empty string is returned from utilityVinsCheckPresence then there is no // such ViNS and err tells so - just return it to the calling party diff --git a/internal/service/cloudapi/vins/data_source_vins_list.go b/internal/service/cloudapi/vins/data_source_vins_list.go index 76365db..2178eb5 100644 --- a/internal/service/cloudapi/vins/data_source_vins_list.go +++ b/internal/service/cloudapi/vins/data_source_vins_list.go @@ -67,7 +67,7 @@ func flattenVinsList(vl VinsList) []map[string]interface{} { } func dataSourceVinsListRead(ctx context.Context, d *schema.ResourceData, m interface{}) diag.Diagnostics { - vinsList, err := utilityVinsListCheckPresence(d, m) + vinsList, err := utilityVinsListCheckPresence(ctx, d, m) if err != nil { return diag.FromErr(err) } diff --git a/internal/service/cloudapi/vins/resource_vins.go b/internal/service/cloudapi/vins/resource_vins.go index fc0170d..22729f6 100644 --- a/internal/service/cloudapi/vins/resource_vins.go +++ b/internal/service/cloudapi/vins/resource_vins.go @@ -115,7 +115,7 @@ func resourceVinsCreate(ctx context.Context, d *schema.ResourceData, m interface urlValues.Add("desc", argVal.(string)) } - apiResp, err := c.DecortAPICall("POST", apiToCall, urlValues) + apiResp, err := c.DecortAPICall(ctx, "POST", apiToCall, urlValues) if err != nil { return diag.FromErr(err) } @@ -133,7 +133,7 @@ func resourceVinsCreate(ctx context.Context, d *schema.ResourceData, m interface } func resourceVinsRead(ctx context.Context, d *schema.ResourceData, m interface{}) diag.Diagnostics { - vinsFacts, err := utilityVinsCheckPresence(d, m) + vinsFacts, err := utilityVinsCheckPresence(ctx, d, m) if vinsFacts == "" { // if empty string is returned from utilityVinsCheckPresence then there is no // such ViNS and err tells so - just return it to the calling party @@ -161,7 +161,7 @@ func resourceVinsUpdate(ctx context.Context, d *schema.ResourceData, m interface if oldExtNetId.(int) > 0 { // there was preexisting external net connection - disconnect ViNS - _, err := c.DecortAPICall("POST", VinsExtNetDisconnectAPI, extnetParams) + _, err := c.DecortAPICall(ctx, "POST", VinsExtNetDisconnectAPI, extnetParams) if err != nil { return diag.FromErr(err) } @@ -170,7 +170,7 @@ func resourceVinsUpdate(ctx context.Context, d *schema.ResourceData, m interface if newExtNedId.(int) > 0 { // new external network connection requested - connect ViNS extnetParams.Add("netId", fmt.Sprintf("%d", newExtNedId.(int))) - _, err := c.DecortAPICall("POST", VinsExtNetConnectAPI, extnetParams) + _, err := c.DecortAPICall(ctx, "POST", VinsExtNetConnectAPI, extnetParams) if err != nil { return diag.FromErr(err) } @@ -186,7 +186,7 @@ func resourceVinsDelete(ctx context.Context, d *schema.ResourceData, m interface log.Debugf("resourceVinsDelete: called for ViNS ID / name %s / %s, Account ID %d, RG ID %d", d.Id(), d.Get("name").(string), d.Get("account_id").(int), d.Get("rg_id").(int)) - vinsFacts, err := utilityVinsCheckPresence(d, m) + vinsFacts, err := utilityVinsCheckPresence(ctx, d, m) if vinsFacts == "" { if err != nil { return diag.FromErr(err) @@ -202,7 +202,7 @@ func resourceVinsDelete(ctx context.Context, d *schema.ResourceData, m interface params.Add("permanently", "1") // delete ViNS immediately bypassing recycle bin c := m.(*controller.ControllerCfg) - _, err = c.DecortAPICall("POST", VinsDeleteAPI, params) + _, err = c.DecortAPICall(ctx, "POST", VinsDeleteAPI, params) if err != nil { return diag.FromErr(err) } @@ -210,12 +210,12 @@ func resourceVinsDelete(ctx context.Context, d *schema.ResourceData, m interface return nil } -func resourceVinsExists(d *schema.ResourceData, m interface{}) (bool, error) { +func resourceVinsExists(ctx context.Context, d *schema.ResourceData, m interface{}) (bool, error) { // Reminder: according to Terraform rules, this function should not modify its ResourceData argument log.Debugf("resourceVinsExists: called for ViNS name %s, Account ID %d, RG ID %d", d.Get("name").(string), d.Get("account_id").(int), d.Get("rg_id").(int)) - vinsFacts, err := utilityVinsCheckPresence(d, m) + vinsFacts, err := utilityVinsCheckPresence(ctx, d, m) if vinsFacts == "" { if err != nil { return false, err @@ -305,7 +305,6 @@ func ResourceVins() *schema.Resource { ReadContext: resourceVinsRead, UpdateContext: resourceVinsUpdate, DeleteContext: resourceVinsDelete, - Exists: resourceVinsExists, Importer: &schema.ResourceImporter{ State: schema.ImportStatePassthrough, diff --git a/internal/service/cloudapi/vins/utility_vins.go b/internal/service/cloudapi/vins/utility_vins.go index c8e363b..a53ea85 100644 --- a/internal/service/cloudapi/vins/utility_vins.go +++ b/internal/service/cloudapi/vins/utility_vins.go @@ -32,6 +32,7 @@ Documentation: https://github.com/rudecs/terraform-provider-decort/wiki package vins import ( + "context" "encoding/json" "fmt" "net/url" @@ -45,7 +46,7 @@ import ( // On success this function returns a string, as returned by API vins/get, which could be unmarshalled // into VinsGetResp structure -func utilityVinsCheckPresence(d *schema.ResourceData, m interface{}) (string, error) { +func utilityVinsCheckPresence(ctx context.Context, d *schema.ResourceData, m interface{}) (string, error) { // This function tries to locate ViNS by one of the following algorithms depending // on the parameters passed: // - if resource group ID is specified -> it looks for a ViNS at the RG level @@ -80,7 +81,7 @@ func utilityVinsCheckPresence(d *schema.ResourceData, m interface{}) (string, er // ViNS ID is specified, try to get compute instance straight by this ID log.Debugf("utilityVinsCheckPresence: locating ViNS by its ID %d", theId) urlValues.Add("vinsId", fmt.Sprintf("%d", theId)) - vinsFacts, err := c.DecortAPICall("POST", VinsGetAPI, urlValues) + vinsFacts, err := c.DecortAPICall(ctx, "POST", VinsGetAPI, urlValues) if err != nil { return "", err } @@ -111,7 +112,7 @@ func utilityVinsCheckPresence(d *schema.ResourceData, m interface{}) (string, er urlValues.Add("accountId", fmt.Sprintf("%d", accountId.(int))) } - apiResp, err := c.DecortAPICall("POST", VinsSearchAPI, urlValues) + apiResp, err := c.DecortAPICall(ctx, "POST", VinsSearchAPI, urlValues) if err != nil { return "", err } @@ -140,7 +141,7 @@ func utilityVinsCheckPresence(d *schema.ResourceData, m interface{}) (string, er // manage ViNS, so we have to get detailed info by calling API vins/get rqValues := &url.Values{} rqValues.Add("vinsId", fmt.Sprintf("%d", item.ID)) - vinsGetResp, err := c.DecortAPICall("POST", VinsGetAPI, rqValues) + vinsGetResp, err := c.DecortAPICall(ctx, "POST", VinsGetAPI, rqValues) if err != nil { return "", err } diff --git a/internal/service/cloudapi/vins/utility_vins_list.go b/internal/service/cloudapi/vins/utility_vins_list.go index c886c68..4746f23 100644 --- a/internal/service/cloudapi/vins/utility_vins_list.go +++ b/internal/service/cloudapi/vins/utility_vins_list.go @@ -32,6 +32,7 @@ Documentation: https://github.com/rudecs/terraform-provider-decort/wiki package vins import ( + "context" "encoding/json" "net/url" "strconv" @@ -42,7 +43,7 @@ import ( "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" ) -func utilityVinsListCheckPresence(d *schema.ResourceData, m interface{}) (VinsList, error) { +func utilityVinsListCheckPresence(ctx context.Context, d *schema.ResourceData, m interface{}) (VinsList, error) { vinsList := VinsList{} c := m.(*controller.ControllerCfg) urlValues := &url.Values{} @@ -58,7 +59,7 @@ func utilityVinsListCheckPresence(d *schema.ResourceData, m interface{}) (VinsLi } log.Debugf("utilityVinsListCheckPresence") - vinsListRaw, err := c.DecortAPICall("POST", VinsListAPI, urlValues) + vinsListRaw, err := c.DecortAPICall(ctx, "POST", VinsListAPI, urlValues) if err != nil { return nil, err } diff --git a/internal/service/cloudbroker/grid/data_source_grid.go b/internal/service/cloudbroker/grid/data_source_grid.go index 7ba9abe..634d987 100644 --- a/internal/service/cloudbroker/grid/data_source_grid.go +++ b/internal/service/cloudbroker/grid/data_source_grid.go @@ -50,7 +50,7 @@ func flattenGrid(d *schema.ResourceData, grid *Grid) { } func dataSourceGridRead(ctx context.Context, d *schema.ResourceData, m interface{}) diag.Diagnostics { - grid, err := utilityGridCheckPresence(d, m) + grid, err := utilityGridCheckPresence(ctx, d, m) if err != nil { return diag.FromErr(err) } diff --git a/internal/service/cloudbroker/grid/data_source_grid_list.go b/internal/service/cloudbroker/grid/data_source_grid_list.go index 4521c90..476a739 100644 --- a/internal/service/cloudbroker/grid/data_source_grid_list.go +++ b/internal/service/cloudbroker/grid/data_source_grid_list.go @@ -58,7 +58,7 @@ func flattenGridList(gl GridList) []map[string]interface{} { } func dataSourceGridListRead(ctx context.Context, d *schema.ResourceData, m interface{}) diag.Diagnostics { - gridList, err := utilityGridListCheckPresence(d, m) + gridList, err := utilityGridListCheckPresence(ctx, d, m) if err != nil { return diag.FromErr(err) } diff --git a/internal/service/cloudbroker/grid/utility_grid.go b/internal/service/cloudbroker/grid/utility_grid.go index ef30e99..8b7698e 100644 --- a/internal/service/cloudbroker/grid/utility_grid.go +++ b/internal/service/cloudbroker/grid/utility_grid.go @@ -32,6 +32,7 @@ Documentation: https://github.com/rudecs/terraform-provider-decort/wiki package grid import ( + "context" "encoding/json" "errors" "net/url" @@ -43,7 +44,7 @@ import ( "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" ) -func utilityGridCheckPresence(d *schema.ResourceData, m interface{}) (*Grid, error) { +func utilityGridCheckPresence(ctx context.Context, d *schema.ResourceData, m interface{}) (*Grid, error) { grid := &Grid{} c := m.(*controller.ControllerCfg) urlValues := &url.Values{} @@ -55,7 +56,7 @@ func utilityGridCheckPresence(d *schema.ResourceData, m interface{}) (*Grid, err } log.Debugf("utilityGridCheckPresence: load grid") - gridRaw, err := c.DecortAPICall("POST", GridGetAPI, urlValues) + gridRaw, err := c.DecortAPICall(ctx, "POST", GridGetAPI, urlValues) if err != nil { return nil, err } diff --git a/internal/service/cloudbroker/grid/utility_grid_list.go b/internal/service/cloudbroker/grid/utility_grid_list.go index c679411..a81e06c 100644 --- a/internal/service/cloudbroker/grid/utility_grid_list.go +++ b/internal/service/cloudbroker/grid/utility_grid_list.go @@ -32,6 +32,7 @@ Documentation: https://github.com/rudecs/terraform-provider-decort/wiki package grid import ( + "context" "encoding/json" "net/url" "strconv" @@ -42,7 +43,7 @@ import ( "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" ) -func utilityGridListCheckPresence(d *schema.ResourceData, m interface{}) (GridList, error) { +func utilityGridListCheckPresence(ctx context.Context, d *schema.ResourceData, m interface{}) (GridList, error) { gridList := GridList{} c := m.(*controller.ControllerCfg) urlValues := &url.Values{} @@ -55,7 +56,7 @@ func utilityGridListCheckPresence(d *schema.ResourceData, m interface{}) (GridLi } log.Debugf("utilityGridListCheckPresence: load grid list") - gridListRaw, err := c.DecortAPICall("POST", GridListGetAPI, urlValues) + gridListRaw, err := c.DecortAPICall(ctx, "POST", GridListGetAPI, urlValues) if err != nil { return nil, err } diff --git a/internal/service/cloudbroker/image/data_source_image.go b/internal/service/cloudbroker/image/data_source_image.go index fe0ee4b..8b0b92c 100644 --- a/internal/service/cloudbroker/image/data_source_image.go +++ b/internal/service/cloudbroker/image/data_source_image.go @@ -83,7 +83,7 @@ func flattenImage(d *schema.ResourceData, image *Image) { } func dataSourceImageRead(ctx context.Context, d *schema.ResourceData, m interface{}) diag.Diagnostics { - image, err := utilityImageCheckPresence(d, m) + image, err := utilityImageCheckPresence(ctx, d, m) if err != nil { return diag.FromErr(err) diff --git a/internal/service/cloudbroker/image/data_source_image_list.go b/internal/service/cloudbroker/image/data_source_image_list.go index 1108d23..5e7f7ae 100644 --- a/internal/service/cloudbroker/image/data_source_image_list.go +++ b/internal/service/cloudbroker/image/data_source_image_list.go @@ -89,7 +89,7 @@ func flattenImageList(il ImageList) []map[string]interface{} { } func dataSourceImageListRead(ctx context.Context, d *schema.ResourceData, m interface{}) diag.Diagnostics { - imageList, err := utilityImageListCheckPresence(d, m) + imageList, err := utilityImageListCheckPresence(ctx, d, m) if err != nil { return diag.FromErr(err) } diff --git a/internal/service/cloudbroker/image/data_source_image_list_stacks.go b/internal/service/cloudbroker/image/data_source_image_list_stacks.go index 2a47dd5..c672748 100644 --- a/internal/service/cloudbroker/image/data_source_image_list_stacks.go +++ b/internal/service/cloudbroker/image/data_source_image_list_stacks.go @@ -67,7 +67,7 @@ func flattenImageListStacks(_ *schema.ResourceData, stack ImageListStacks) []map } func dataSourceImageListStacksRead(ctx context.Context, d *schema.ResourceData, m interface{}) diag.Diagnostics { - imageListStacks, err := utilityImageListStacksCheckPresence(d, m) + imageListStacks, err := utilityImageListStacksCheckPresence(ctx, d, m) if err != nil { return diag.FromErr(err) } diff --git a/internal/service/cloudbroker/image/resource_cdrom_image.go b/internal/service/cloudbroker/image/resource_cdrom_image.go index af794eb..8b0068c 100644 --- a/internal/service/cloudbroker/image/resource_cdrom_image.go +++ b/internal/service/cloudbroker/image/resource_cdrom_image.go @@ -90,7 +90,7 @@ func resourceCDROMImageCreate(ctx context.Context, d *schema.ResourceData, m int urlValues.Add("architecture", architecture.(string)) } - imageId, err := c.DecortAPICall("POST", imageCreateCDROMAPI, urlValues) + imageId, err := c.DecortAPICall(ctx, "POST", imageCreateCDROMAPI, urlValues) if err != nil { return diag.FromErr(err) } @@ -98,7 +98,7 @@ func resourceCDROMImageCreate(ctx context.Context, d *schema.ResourceData, m int d.SetId(imageId) d.Set("image_id", imageId) - image, err := utilityImageCheckPresence(d, m) + image, err := utilityImageCheckPresence(ctx, d, m) if err != nil { return diag.FromErr(err) } @@ -118,7 +118,7 @@ func resourceCDROMImageCreate(ctx context.Context, d *schema.ResourceData, m int func resourceCDROMImageDelete(ctx context.Context, d *schema.ResourceData, m interface{}) diag.Diagnostics { log.Debugf("resourceCDROMImageDelete: called for %s, id: %s", d.Get("name").(string), d.Id()) - image, err := utilityImageCheckPresence(d, m) + image, err := utilityImageCheckPresence(ctx, d, m) if image == nil { if err != nil { return diag.FromErr(err) @@ -134,7 +134,7 @@ func resourceCDROMImageDelete(ctx context.Context, d *schema.ResourceData, m int urlValues.Add("permanently", strconv.FormatBool(permanently.(bool))) } - _, err = c.DecortAPICall("POST", imageDeleteCDROMAPI, urlValues) + _, err = c.DecortAPICall(ctx, "POST", imageDeleteCDROMAPI, urlValues) if err != nil { return diag.FromErr(err) } @@ -379,7 +379,6 @@ func ResourceCDROMImage() *schema.Resource { ReadContext: resourceImageRead, UpdateContext: resourceImageEdit, DeleteContext: resourceCDROMImageDelete, - Exists: resourceImageExists, Importer: &schema.ResourceImporter{ State: schema.ImportStatePassthrough, diff --git a/internal/service/cloudbroker/image/resource_delete_images.go b/internal/service/cloudbroker/image/resource_delete_images.go index 5548285..233191a 100644 --- a/internal/service/cloudbroker/image/resource_delete_images.go +++ b/internal/service/cloudbroker/image/resource_delete_images.go @@ -74,7 +74,7 @@ func resourceDeleteListImages(ctx context.Context, d *schema.ResourceData, m int urlValues.Add("permanently", strconv.FormatBool(d.Get("permanently").(bool))) urlValues.Add("imageIds", temp) - _, err := c.DecortAPICall("POST", imageDeleteImagesAPI, urlValues) + _, err := c.DecortAPICall(ctx, "POST", imageDeleteImagesAPI, urlValues) if err != nil { return diag.FromErr(err) } diff --git a/internal/service/cloudbroker/image/resource_image.go b/internal/service/cloudbroker/image/resource_image.go index 464e687..b578709 100644 --- a/internal/service/cloudbroker/image/resource_image.go +++ b/internal/service/cloudbroker/image/resource_image.go @@ -103,7 +103,7 @@ func resourceImageCreate(ctx context.Context, d *schema.ResourceData, m interfac } else { api = imageSyncCreateAPI } - imageId, err := c.DecortAPICall("POST", api, urlValues) + imageId, err := c.DecortAPICall(ctx, "POST", api, urlValues) if err != nil { return diag.FromErr(err) } @@ -111,7 +111,7 @@ func resourceImageCreate(ctx context.Context, d *schema.ResourceData, m interfac d.SetId(imageId) d.Set("image_id", imageId) - image, err := utilityImageCheckPresence(d, m) + image, err := utilityImageCheckPresence(ctx, d, m) if err != nil { return diag.FromErr(err) } @@ -131,7 +131,7 @@ func resourceImageCreate(ctx context.Context, d *schema.ResourceData, m interfac func resourceImageRead(ctx context.Context, d *schema.ResourceData, m interface{}) diag.Diagnostics { log.Debugf("resourceImageRead: called for %s id: %s", d.Get("name").(string), d.Id()) - image, err := utilityImageCheckPresence(d, m) + image, err := utilityImageCheckPresence(ctx, d, m) if image == nil { d.SetId("") return diag.FromErr(err) @@ -182,7 +182,7 @@ func resourceImageRead(ctx context.Context, d *schema.ResourceData, m interface{ func resourceImageDelete(ctx context.Context, d *schema.ResourceData, m interface{}) diag.Diagnostics { log.Debugf("resourceImageDelete: called for %s, id: %s", d.Get("name").(string), d.Id()) - image, err := utilityImageCheckPresence(d, m) + image, err := utilityImageCheckPresence(ctx, d, m) if image == nil { if err != nil { return diag.FromErr(err) @@ -202,7 +202,7 @@ func resourceImageDelete(ctx context.Context, d *schema.ResourceData, m interfac urlValues.Add("permanently", strconv.FormatBool(permanently.(bool))) } - _, err = c.DecortAPICall("POST", imageDeleteAPI, urlValues) + _, err = c.DecortAPICall(ctx, "POST", imageDeleteAPI, urlValues) if err != nil { return diag.FromErr(err) } @@ -211,10 +211,10 @@ func resourceImageDelete(ctx context.Context, d *schema.ResourceData, m interfac return nil } -func resourceImageExists(d *schema.ResourceData, m interface{}) (bool, error) { +func resourceImageExists(ctx context.Context, d *schema.ResourceData, m interface{}) (bool, error) { log.Debugf("resourceImageExists: called for %s, id: %s", d.Get("name").(string), d.Id()) - image, err := utilityImageCheckPresence(d, m) + image, err := utilityImageCheckPresence(ctx, d, m) if image == nil { if err != nil { return false, err @@ -225,13 +225,13 @@ func resourceImageExists(d *schema.ResourceData, m interface{}) (bool, error) { return true, nil } -func resourceImageEditName(d *schema.ResourceData, m interface{}) error { +func resourceImageEditName(ctx context.Context, d *schema.ResourceData, m interface{}) error { log.Debugf("resourceImageEditName: called for %s, id: %s", d.Get("name").(string), d.Id()) c := m.(*controller.ControllerCfg) urlValues := &url.Values{} urlValues.Add("imageId", strconv.Itoa(d.Get("image_id").(int))) urlValues.Add("name", d.Get("name").(string)) - _, err := c.DecortAPICall("POST", imageEditNameAPI, urlValues) + _, err := c.DecortAPICall(ctx, "POST", imageEditNameAPI, urlValues) if err != nil { return err } @@ -245,7 +245,7 @@ func resourceImageEdit(ctx context.Context, d *schema.ResourceData, m interface{ urlValues := &url.Values{} if d.HasChange("enabled") { - err := resourceImageChangeEnabled(d, m) + err := resourceImageChangeEnabled(ctx, d, m) if err != nil { return diag.FromErr(err) } @@ -253,7 +253,7 @@ func resourceImageEdit(ctx context.Context, d *schema.ResourceData, m interface{ } if d.HasChange("name") { - err := resourceImageEditName(d, m) + err := resourceImageEditName(ctx, d, m) if err != nil { return diag.FromErr(err) } @@ -261,14 +261,14 @@ func resourceImageEdit(ctx context.Context, d *schema.ResourceData, m interface{ } if d.HasChange("shared_with") { - err := resourceImageShare(d, m) + err := resourceImageShare(ctx, d, m) if err != nil { return diag.FromErr(err) } urlValues = &url.Values{} } if d.HasChange("computeci_id") { - err := resourceImageChangeComputeci(d, m) + err := resourceImageChangeComputeci(ctx, d, m) if err != nil { return diag.FromErr(err) } @@ -276,7 +276,7 @@ func resourceImageEdit(ctx context.Context, d *schema.ResourceData, m interface{ } if d.HasChange("enabled_stacks") { - err := resourceImageUpdateNodes(d, m) + err := resourceImageUpdateNodes(ctx, d, m) if err != nil { return diag.FromErr(err) } @@ -284,7 +284,7 @@ func resourceImageEdit(ctx context.Context, d *schema.ResourceData, m interface{ } if d.HasChange("link_to") { - err := resourceImageLink(d, m) + err := resourceImageLink(ctx, d, m) if err != nil { return diag.FromErr(err) } @@ -302,7 +302,7 @@ func resourceImageEdit(ctx context.Context, d *schema.ResourceData, m interface{ urlValues.Add("bootable", strconv.FormatBool(d.Get("bootable").(bool))) urlValues.Add("hotresize", strconv.FormatBool(d.Get("hot_resize").(bool))) - _, err := c.DecortAPICall("POST", imageEditAPI, urlValues) + _, err := c.DecortAPICall(ctx, "POST", imageEditAPI, urlValues) if err != nil { return diag.FromErr(err) } @@ -311,7 +311,7 @@ func resourceImageEdit(ctx context.Context, d *schema.ResourceData, m interface{ return nil } -func resourceImageChangeEnabled(d *schema.ResourceData, m interface{}) error { +func resourceImageChangeEnabled(ctx context.Context, d *schema.ResourceData, m interface{}) error { var api string c := m.(*controller.ControllerCfg) @@ -322,7 +322,7 @@ func resourceImageChangeEnabled(d *schema.ResourceData, m interface{}) error { } else { api = imageDisableAPI } - resp, err := c.DecortAPICall("POST", api, urlValues) + resp, err := c.DecortAPICall(ctx, "POST", api, urlValues) if err != nil { return err } @@ -336,13 +336,13 @@ func resourceImageChangeEnabled(d *schema.ResourceData, m interface{}) error { return nil } -func resourceImageLink(d *schema.ResourceData, m interface{}) error { +func resourceImageLink(ctx context.Context, d *schema.ResourceData, m interface{}) error { log.Debugf("resourceVirtualImageLink: called for %s, id: %s", d.Get("name").(string), d.Id()) c := m.(*controller.ControllerCfg) urlValues := &url.Values{} urlValues.Add("imageId", strconv.Itoa(d.Get("image_id").(int))) urlValues.Add("targetId", strconv.Itoa(d.Get("link_to").(int))) - _, err := c.DecortAPICall("POST", imageLinkAPI, urlValues) + _, err := c.DecortAPICall(ctx, "POST", imageLinkAPI, urlValues) if err != nil { return err } @@ -350,7 +350,7 @@ func resourceImageLink(d *schema.ResourceData, m interface{}) error { return nil } -func resourceImageShare(d *schema.ResourceData, m interface{}) error { +func resourceImageShare(ctx context.Context, d *schema.ResourceData, m interface{}) error { log.Debugf("resourceImageShare: called for %s, id: %s", d.Get("name").(string), d.Id()) c := m.(*controller.ControllerCfg) urlValues := &url.Values{} @@ -369,7 +369,7 @@ func resourceImageShare(d *schema.ResourceData, m interface{}) error { } temp = "[" + temp + "]" urlValues.Add("accounts", temp) - _, err := c.DecortAPICall("POST", imageShareAPI, urlValues) + _, err := c.DecortAPICall(ctx, "POST", imageShareAPI, urlValues) if err != nil { return err } @@ -377,7 +377,7 @@ func resourceImageShare(d *schema.ResourceData, m interface{}) error { return nil } -func resourceImageChangeComputeci(d *schema.ResourceData, m interface{}) error { +func resourceImageChangeComputeci(ctx context.Context, d *schema.ResourceData, m interface{}) error { c := m.(*controller.ControllerCfg) urlValues := &url.Values{} @@ -393,7 +393,7 @@ func resourceImageChangeComputeci(d *schema.ResourceData, m interface{}) error { api = imageComputeciSetAPI } - _, err := c.DecortAPICall("POST", api, urlValues) + _, err := c.DecortAPICall(ctx, "POST", api, urlValues) if err != nil { return err } @@ -401,7 +401,7 @@ func resourceImageChangeComputeci(d *schema.ResourceData, m interface{}) error { return nil } -func resourceImageUpdateNodes(d *schema.ResourceData, m interface{}) error { +func resourceImageUpdateNodes(ctx context.Context, d *schema.ResourceData, m interface{}) error { log.Debugf("resourceImageUpdateNodes: called for %s, id: %s", d.Get("name").(string), d.Id()) c := m.(*controller.ControllerCfg) urlValues := &url.Values{} @@ -418,7 +418,7 @@ func resourceImageUpdateNodes(d *schema.ResourceData, m interface{}) error { } temp = "[" + temp + "]" urlValues.Add("enabledStacks", temp) - _, err := c.DecortAPICall("POST", imageUpdateNodesAPI, urlValues) + _, err := c.DecortAPICall(ctx, "POST", imageUpdateNodesAPI, urlValues) if err != nil { return err } @@ -677,7 +677,6 @@ func ResourceImage() *schema.Resource { ReadContext: resourceImageRead, UpdateContext: resourceImageEdit, DeleteContext: resourceImageDelete, - Exists: resourceImageExists, Importer: &schema.ResourceImporter{ State: schema.ImportStatePassthrough, diff --git a/internal/service/cloudbroker/image/resource_virtual_image.go b/internal/service/cloudbroker/image/resource_virtual_image.go index f778367..ec540d7 100644 --- a/internal/service/cloudbroker/image/resource_virtual_image.go +++ b/internal/service/cloudbroker/image/resource_virtual_image.go @@ -51,7 +51,7 @@ func resourceVirtualImageCreate(ctx context.Context, d *schema.ResourceData, m i urlValues.Add("name", d.Get("name").(string)) urlValues.Add("targetId", strconv.Itoa(d.Get("target_id").(int))) - imageId, err := c.DecortAPICall("POST", imageCreateVirtualAPI, urlValues) + imageId, err := c.DecortAPICall(ctx, "POST", imageCreateVirtualAPI, urlValues) if err != nil { return diag.FromErr(err) } @@ -59,7 +59,7 @@ func resourceVirtualImageCreate(ctx context.Context, d *schema.ResourceData, m i d.SetId(imageId) d.Set("image_id", imageId) - image, err := utilityImageCheckPresence(d, m) + image, err := utilityImageCheckPresence(ctx, d, m) if err != nil { return diag.FromErr(err) } @@ -326,7 +326,6 @@ func ResourceVirtualImage() *schema.Resource { ReadContext: resourceImageRead, UpdateContext: resourceImageEdit, DeleteContext: resourceImageDelete, - Exists: resourceImageExists, Importer: &schema.ResourceImporter{ State: schema.ImportStatePassthrough, diff --git a/internal/service/cloudbroker/image/utility_image.go b/internal/service/cloudbroker/image/utility_image.go index 10c30ed..04981da 100644 --- a/internal/service/cloudbroker/image/utility_image.go +++ b/internal/service/cloudbroker/image/utility_image.go @@ -32,6 +32,7 @@ Documentation: https://github.com/rudecs/terraform-provider-decort/wiki package image import ( + "context" "encoding/json" "errors" "fmt" @@ -42,7 +43,7 @@ import ( "github.com/rudecs/terraform-provider-decort/internal/controller" ) -func utilityImageCheckPresence(d *schema.ResourceData, m interface{}) (*Image, error) { +func utilityImageCheckPresence(ctx context.Context, d *schema.ResourceData, m interface{}) (*Image, error) { c := m.(*controller.ControllerCfg) urlValues := &url.Values{} @@ -52,7 +53,7 @@ func utilityImageCheckPresence(d *schema.ResourceData, m interface{}) (*Image, e urlValues.Add("imageId", d.Id()) } - resp, err := c.DecortAPICall("POST", imageGetAPI, urlValues) + resp, err := c.DecortAPICall(ctx, "POST", imageGetAPI, urlValues) if err != nil { return nil, err } diff --git a/internal/service/cloudbroker/image/utility_image_list.go b/internal/service/cloudbroker/image/utility_image_list.go index dffabdf..42adce0 100644 --- a/internal/service/cloudbroker/image/utility_image_list.go +++ b/internal/service/cloudbroker/image/utility_image_list.go @@ -32,6 +32,7 @@ Documentation: https://github.com/rudecs/terraform-provider-decort/wiki package image import ( + "context" "encoding/json" "net/url" "strconv" @@ -42,7 +43,7 @@ import ( "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" ) -func utilityImageListCheckPresence(d *schema.ResourceData, m interface{}) (ImageList, error) { +func utilityImageListCheckPresence(ctx context.Context, d *schema.ResourceData, m interface{}) (ImageList, error) { imageList := ImageList{} c := m.(*controller.ControllerCfg) urlValues := &url.Values{} @@ -62,7 +63,7 @@ func utilityImageListCheckPresence(d *schema.ResourceData, m interface{}) (Image } log.Debugf("utilityImageListCheckPresence: load image list") - imageListRaw, err := c.DecortAPICall("POST", imageListGetAPI, urlValues) + imageListRaw, err := c.DecortAPICall(ctx, "POST", imageListGetAPI, urlValues) if err != nil { return nil, err } diff --git a/internal/service/cloudbroker/image/utility_image_list_stacks.go b/internal/service/cloudbroker/image/utility_image_list_stacks.go index 8062078..3b5a51a 100644 --- a/internal/service/cloudbroker/image/utility_image_list_stacks.go +++ b/internal/service/cloudbroker/image/utility_image_list_stacks.go @@ -32,6 +32,7 @@ Documentation: https://github.com/rudecs/terraform-provider-decort/wiki package image import ( + "context" "encoding/json" "net/url" "strconv" @@ -42,7 +43,7 @@ import ( "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" ) -func utilityImageListStacksCheckPresence(d *schema.ResourceData, m interface{}) (ImageListStacks, error) { +func utilityImageListStacksCheckPresence(ctx context.Context, d *schema.ResourceData, m interface{}) (ImageListStacks, error) { imageListStacks := ImageListStacks{} c := m.(*controller.ControllerCfg) urlValues := &url.Values{} @@ -50,7 +51,7 @@ func utilityImageListStacksCheckPresence(d *schema.ResourceData, m interface{}) urlValues.Add("imageId", strconv.Itoa(d.Get("image_id").(int))) log.Debugf("utilityImageListStacksCheckPresence: load image list") - imageListRaw, err := c.DecortAPICall("POST", imageListStacksApi, urlValues) + imageListRaw, err := c.DecortAPICall(ctx, "POST", imageListStacksApi, urlValues) if err != nil { return nil, err } diff --git a/internal/service/cloudbroker/pcidevice/data_source_pcidevice.go b/internal/service/cloudbroker/pcidevice/data_source_pcidevice.go index 880ff91..90a9ac3 100644 --- a/internal/service/cloudbroker/pcidevice/data_source_pcidevice.go +++ b/internal/service/cloudbroker/pcidevice/data_source_pcidevice.go @@ -42,7 +42,7 @@ import ( ) func dataSourcePcideviceRead(ctx context.Context, d *schema.ResourceData, m interface{}) diag.Diagnostics { - pcidevice, err := utilityPcideviceCheckPresence(d, m) + pcidevice, err := utilityPcideviceCheckPresence(ctx, d, m) if err != nil { return diag.FromErr(err) } diff --git a/internal/service/cloudbroker/pcidevice/data_source_pcidevice_list.go b/internal/service/cloudbroker/pcidevice/data_source_pcidevice_list.go index b570cbf..ce9baef 100644 --- a/internal/service/cloudbroker/pcidevice/data_source_pcidevice_list.go +++ b/internal/service/cloudbroker/pcidevice/data_source_pcidevice_list.go @@ -64,7 +64,7 @@ func flattenPcideviceList(pl PcideviceList) []map[string]interface{} { } func dataSourcePcideviceListRead(ctx context.Context, d *schema.ResourceData, m interface{}) diag.Diagnostics { - pcideviceList, err := utilityPcideviceListCheckPresence(d, m) + pcideviceList, err := utilityPcideviceListCheckPresence(ctx, d, m) if err != nil { return diag.FromErr(err) } diff --git a/internal/service/cloudbroker/pcidevice/resource_pcidevice.go b/internal/service/cloudbroker/pcidevice/resource_pcidevice.go index 63408a2..dbf033c 100644 --- a/internal/service/cloudbroker/pcidevice/resource_pcidevice.go +++ b/internal/service/cloudbroker/pcidevice/resource_pcidevice.go @@ -48,7 +48,7 @@ func resourcePcideviceCreate(ctx context.Context, d *schema.ResourceData, m inte log.Debugf("resourcePcideviceCreate: called for pcidevice %s", d.Get("name").(string)) if deviceId, ok := d.GetOk("device_id"); ok { - if exists, err := resourcePcideviceExists(d, m); exists { + if exists, err := resourcePcideviceExists(ctx, d, m); exists { if err != nil { return diag.FromErr(err) } @@ -74,7 +74,7 @@ func resourcePcideviceCreate(ctx context.Context, d *schema.ResourceData, m inte urlValues.Add("description", description.(string)) } - pcideviceId, err := c.DecortAPICall("POST", pcideviceCreateAPI, urlValues) + pcideviceId, err := c.DecortAPICall(ctx, "POST", pcideviceCreateAPI, urlValues) if err != nil { return diag.FromErr(err) } @@ -91,7 +91,7 @@ func resourcePcideviceCreate(ctx context.Context, d *schema.ResourceData, m inte } func resourcePcideviceRead(ctx context.Context, d *schema.ResourceData, m interface{}) diag.Diagnostics { - pcidevice, err := utilityPcideviceCheckPresence(d, m) + pcidevice, err := utilityPcideviceCheckPresence(ctx, d, m) if err != nil { return diag.FromErr(err) } @@ -121,7 +121,7 @@ func resourcePcideviceDelete(ctx context.Context, d *schema.ResourceData, m inte urlValues.Add("deviceId", d.Id()) urlValues.Add("force", strconv.FormatBool(d.Get("force").(bool))) - _, err := c.DecortAPICall("POST", pcideviceDeleteAPI, urlValues) + _, err := c.DecortAPICall(ctx, "POST", pcideviceDeleteAPI, urlValues) if err != nil { return diag.FromErr(err) } @@ -131,8 +131,8 @@ func resourcePcideviceDelete(ctx context.Context, d *schema.ResourceData, m inte return nil } -func resourcePcideviceExists(d *schema.ResourceData, m interface{}) (bool, error) { - pcidevice, err := utilityPcideviceCheckPresence(d, m) +func resourcePcideviceExists(ctx context.Context, d *schema.ResourceData, m interface{}) (bool, error) { + pcidevice, err := utilityPcideviceCheckPresence(ctx, d, m) if err != nil { return false, err } @@ -158,7 +158,7 @@ func resourcePcideviceEdit(ctx context.Context, d *schema.ResourceData, m interf api = pcideviceDisableAPI } - _, err := c.DecortAPICall("POST", api, urlValues) + _, err := c.DecortAPICall(ctx, "POST", api, urlValues) if err != nil { return diag.FromErr(err) } @@ -255,7 +255,6 @@ func ResourcePcidevice() *schema.Resource { ReadContext: resourcePcideviceRead, UpdateContext: resourcePcideviceEdit, DeleteContext: resourcePcideviceDelete, - Exists: resourcePcideviceExists, Importer: &schema.ResourceImporter{ State: schema.ImportStatePassthrough, diff --git a/internal/service/cloudbroker/pcidevice/utility_pcidevice.go b/internal/service/cloudbroker/pcidevice/utility_pcidevice.go index fb4ffcd..9b22947 100644 --- a/internal/service/cloudbroker/pcidevice/utility_pcidevice.go +++ b/internal/service/cloudbroker/pcidevice/utility_pcidevice.go @@ -32,13 +32,14 @@ Documentation: https://github.com/rudecs/terraform-provider-decort/wiki package pcidevice import ( + "context" "strconv" "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" ) -func utilityPcideviceCheckPresence(d *schema.ResourceData, m interface{}) (*Pcidevice, error) { - pcideviceList, err := utilityPcideviceListCheckPresence(d, m) +func utilityPcideviceCheckPresence(ctx context.Context, d *schema.ResourceData, m interface{}) (*Pcidevice, error) { + pcideviceList, err := utilityPcideviceListCheckPresence(ctx, d, m) if err != nil { return nil, err } diff --git a/internal/service/cloudbroker/pcidevice/utility_pcidevice_list.go b/internal/service/cloudbroker/pcidevice/utility_pcidevice_list.go index 1dd503d..ada9adc 100644 --- a/internal/service/cloudbroker/pcidevice/utility_pcidevice_list.go +++ b/internal/service/cloudbroker/pcidevice/utility_pcidevice_list.go @@ -32,6 +32,7 @@ Documentation: https://github.com/rudecs/terraform-provider-decort/wiki package pcidevice import ( + "context" "encoding/json" "net/url" @@ -39,12 +40,12 @@ import ( "github.com/rudecs/terraform-provider-decort/internal/controller" ) -func utilityPcideviceListCheckPresence(_ *schema.ResourceData, m interface{}) (PcideviceList, error) { +func utilityPcideviceListCheckPresence(ctx context.Context, d *schema.ResourceData, m interface{}) (PcideviceList, error) { pcideviceList := PcideviceList{} c := m.(*controller.ControllerCfg) urlValues := &url.Values{} - pcideviceListRaw, err := c.DecortAPICall("POST", pcideviceListAPI, urlValues) + pcideviceListRaw, err := c.DecortAPICall(ctx, "POST", pcideviceListAPI, urlValues) if err != nil { return nil, err } diff --git a/internal/service/cloudbroker/sep/data_source_sep.go b/internal/service/cloudbroker/sep/data_source_sep.go index 76d3ea8..80a187a 100644 --- a/internal/service/cloudbroker/sep/data_source_sep.go +++ b/internal/service/cloudbroker/sep/data_source_sep.go @@ -43,7 +43,7 @@ import ( ) func dataSourceSepRead(ctx context.Context, d *schema.ResourceData, m interface{}) diag.Diagnostics { - desSep, err := utilitySepCheckPresence(d, m) + desSep, err := utilitySepCheckPresence(ctx, d, m) if err != nil { return diag.FromErr(err) } diff --git a/internal/service/cloudbroker/sep/data_source_sep_config.go b/internal/service/cloudbroker/sep/data_source_sep_config.go index 2d8d4ed..def1007 100644 --- a/internal/service/cloudbroker/sep/data_source_sep_config.go +++ b/internal/service/cloudbroker/sep/data_source_sep_config.go @@ -42,7 +42,7 @@ import ( ) func dataSourceSepConfigRead(ctx context.Context, d *schema.ResourceData, m interface{}) diag.Diagnostics { - sepConfig, err := utilitySepConfigCheckPresence(d, m) + sepConfig, err := utilitySepConfigCheckPresence(ctx, d, m) if err != nil { return diag.FromErr(err) } diff --git a/internal/service/cloudbroker/sep/data_source_sep_consumption.go b/internal/service/cloudbroker/sep/data_source_sep_consumption.go index c4aa957..1b3406b 100644 --- a/internal/service/cloudbroker/sep/data_source_sep_consumption.go +++ b/internal/service/cloudbroker/sep/data_source_sep_consumption.go @@ -41,7 +41,7 @@ import ( ) func dataSourceSepConsumptionRead(ctx context.Context, d *schema.ResourceData, m interface{}) diag.Diagnostics { - sepCons, err := utilitySepConsumptionCheckPresence(d, m) + sepCons, err := utilitySepConsumptionCheckPresence(ctx, d, m) if err != nil { return diag.FromErr(err) } diff --git a/internal/service/cloudbroker/sep/data_source_sep_disk_list.go b/internal/service/cloudbroker/sep/data_source_sep_disk_list.go index 8e0fe92..4df4366 100644 --- a/internal/service/cloudbroker/sep/data_source_sep_disk_list.go +++ b/internal/service/cloudbroker/sep/data_source_sep_disk_list.go @@ -41,7 +41,7 @@ import ( ) func dataSourceSepDiskListRead(ctx context.Context, d *schema.ResourceData, m interface{}) diag.Diagnostics { - sepDiskList, err := utilitySepDiskListCheckPresence(d, m) + sepDiskList, err := utilitySepDiskListCheckPresence(ctx, d, m) if err != nil { return diag.FromErr(err) } diff --git a/internal/service/cloudbroker/sep/data_source_sep_list.go b/internal/service/cloudbroker/sep/data_source_sep_list.go index fe9bd5d..c8b7e41 100644 --- a/internal/service/cloudbroker/sep/data_source_sep_list.go +++ b/internal/service/cloudbroker/sep/data_source_sep_list.go @@ -69,7 +69,7 @@ func flattenSepList(sl SepList) []map[string]interface{} { } func dataSourceSepListRead(ctx context.Context, d *schema.ResourceData, m interface{}) diag.Diagnostics { - sepList, err := utilitySepListCheckPresence(d, m) + sepList, err := utilitySepListCheckPresence(ctx, d, m) if err != nil { return diag.FromErr(err) } diff --git a/internal/service/cloudbroker/sep/data_source_sep_pool.go b/internal/service/cloudbroker/sep/data_source_sep_pool.go index 92238e8..d045d14 100644 --- a/internal/service/cloudbroker/sep/data_source_sep_pool.go +++ b/internal/service/cloudbroker/sep/data_source_sep_pool.go @@ -42,7 +42,7 @@ import ( ) func dataSourceSepPoolRead(ctx context.Context, d *schema.ResourceData, m interface{}) diag.Diagnostics { - sepPool, err := utilitySepPoolCheckPresence(d, m) + sepPool, err := utilitySepPoolCheckPresence(ctx, d, m) if err != nil { return diag.FromErr(err) } diff --git a/internal/service/cloudbroker/sep/resource_sep.go b/internal/service/cloudbroker/sep/resource_sep.go index 95c341f..25b54cf 100644 --- a/internal/service/cloudbroker/sep/resource_sep.go +++ b/internal/service/cloudbroker/sep/resource_sep.go @@ -51,7 +51,7 @@ func resourceSepCreate(ctx context.Context, d *schema.ResourceData, m interface{ log.Debugf("resourceSepCreate: called for sep %s", d.Get("name").(string)) if sepId, ok := d.GetOk("sep_id"); ok { - if exists, err := resourceSepExists(d, m); exists { + if exists, err := resourceSepExists(ctx, d, m); exists { if err != nil { return diag.FromErr(err) } @@ -109,7 +109,7 @@ func resourceSepCreate(ctx context.Context, d *schema.ResourceData, m interface{ temp = "[" + temp + "]" urlValues.Add("provider_nids", temp) - sepId, err := c.DecortAPICall("POST", sepCreateAPI, urlValues) + sepId, err := c.DecortAPICall(ctx, "POST", sepCreateAPI, urlValues) if err != nil { return diag.FromErr(err) } @@ -131,7 +131,7 @@ func resourceSepCreate(ctx context.Context, d *schema.ResourceData, m interface{ func resourceSepRead(ctx context.Context, d *schema.ResourceData, m interface{}) diag.Diagnostics { log.Debugf("resourceSepRead: called for %s id: %d", d.Get("name").(string), d.Get("sep_id").(int)) - sep, err := utilitySepCheckPresence(d, m) + sep, err := utilitySepCheckPresence(ctx, d, m) if sep == nil { d.SetId("") return diag.FromErr(err) @@ -159,7 +159,7 @@ func resourceSepRead(ctx context.Context, d *schema.ResourceData, m interface{}) func resourceSepDelete(ctx context.Context, d *schema.ResourceData, m interface{}) diag.Diagnostics { log.Debugf("resourceSepDelete: called for %s, id: %d", d.Get("name").(string), d.Get("sep_id").(int)) - sepDes, err := utilitySepCheckPresence(d, m) + sepDes, err := utilitySepCheckPresence(ctx, d, m) if sepDes == nil { if err != nil { return diag.FromErr(err) @@ -171,7 +171,7 @@ func resourceSepDelete(ctx context.Context, d *schema.ResourceData, m interface{ urlValues := &url.Values{} urlValues.Add("sep_id", strconv.Itoa(d.Get("sep_id").(int))) - _, err = c.DecortAPICall("POST", sepDeleteAPI, urlValues) + _, err = c.DecortAPICall(ctx, "POST", sepDeleteAPI, urlValues) if err != nil { return diag.FromErr(err) } @@ -180,10 +180,10 @@ func resourceSepDelete(ctx context.Context, d *schema.ResourceData, m interface{ return nil } -func resourceSepExists(d *schema.ResourceData, m interface{}) (bool, error) { +func resourceSepExists(ctx context.Context, d *schema.ResourceData, m interface{}) (bool, error) { log.Debugf("resourceSepExists: called for %s, id: %d", d.Get("name").(string), d.Get("sep_id").(int)) - sepDes, err := utilitySepCheckPresence(d, m) + sepDes, err := utilitySepCheckPresence(ctx, d, m) if sepDes == nil { if err != nil { return false, err @@ -204,7 +204,7 @@ func resourceSepEdit(ctx context.Context, d *schema.ResourceData, m interface{}) if decommission { urlValues.Add("sep_id", strconv.Itoa(d.Get("sep_id").(int))) urlValues.Add("clear_physically", strconv.FormatBool(d.Get("clear_physically").(bool))) - _, err := c.DecortAPICall("POST", sepDecommissionAPI, urlValues) + _, err := c.DecortAPICall(ctx, "POST", sepDecommissionAPI, urlValues) if err != nil { return diag.FromErr(err) } @@ -216,7 +216,7 @@ func resourceSepEdit(ctx context.Context, d *schema.ResourceData, m interface{}) updCapacityLimit := d.Get("upd_capacity_limit").(bool) if updCapacityLimit { urlValues.Add("sep_id", strconv.Itoa(d.Get("sep_id").(int))) - _, err := c.DecortAPICall("POST", sepUpdateCapacityLimitAPI, urlValues) + _, err := c.DecortAPICall(ctx, "POST", sepUpdateCapacityLimitAPI, urlValues) if err != nil { return diag.FromErr(err) } @@ -227,11 +227,11 @@ func resourceSepEdit(ctx context.Context, d *schema.ResourceData, m interface{}) if d.HasChange("config") { urlValues.Add("sep_id", strconv.Itoa(d.Get("sep_id").(int))) urlValues.Add("config", d.Get("config").(string)) - _, err := c.DecortAPICall("POST", sepConfigValidateAPI, urlValues) + _, err := c.DecortAPICall(ctx, "POST", sepConfigValidateAPI, urlValues) if err != nil { return diag.FromErr(err) } - _, err = c.DecortAPICall("POST", sepConfigInsertAPI, urlValues) + _, err = c.DecortAPICall(ctx, "POST", sepConfigInsertAPI, urlValues) if err != nil { return diag.FromErr(err) } @@ -247,7 +247,7 @@ func resourceSepEdit(ctx context.Context, d *schema.ResourceData, m interface{}) urlValues.Add("field_value", field["field_value"].(string)) urlValues.Add("field_type", field["field_type"].(string)) - _, err := c.DecortAPICall("POST", sepConfigFieldEditAPI, urlValues) + _, err := c.DecortAPICall(ctx, "POST", sepConfigFieldEditAPI, urlValues) if err != nil { return diag.FromErr(err) } @@ -255,7 +255,7 @@ func resourceSepEdit(ctx context.Context, d *schema.ResourceData, m interface{}) urlValues = &url.Values{} if d.HasChange("enable") { - err := resourceSepChangeEnabled(d, m) + err := resourceSepChangeEnabled(ctx, d, m) if err != nil { return diag.FromErr(err) } @@ -263,7 +263,7 @@ func resourceSepEdit(ctx context.Context, d *schema.ResourceData, m interface{}) urlValues = &url.Values{} if d.HasChange("consumed_by") { - err := resourceSepUpdateNodes(d, m) + err := resourceSepUpdateNodes(ctx, d, m) if err != nil { return diag.FromErr(err) } @@ -271,7 +271,7 @@ func resourceSepEdit(ctx context.Context, d *schema.ResourceData, m interface{}) urlValues = &url.Values{} if d.HasChange("provided_by") { - err := resourceSepUpdateProviders(d, m) + err := resourceSepUpdateProviders(ctx, d, m) if err != nil { return diag.FromErr(err) } @@ -285,7 +285,7 @@ func resourceSepEdit(ctx context.Context, d *schema.ResourceData, m interface{}) return nil } -func resourceSepChangeEnabled(d *schema.ResourceData, m interface{}) error { +func resourceSepChangeEnabled(ctx context.Context, d *schema.ResourceData, m interface{}) error { var api string c := m.(*controller.ControllerCfg) @@ -296,7 +296,7 @@ func resourceSepChangeEnabled(d *schema.ResourceData, m interface{}) error { } else { api = sepDisableAPI } - resp, err := c.DecortAPICall("POST", api, urlValues) + resp, err := c.DecortAPICall(ctx, "POST", api, urlValues) if err != nil { return err } @@ -310,7 +310,7 @@ func resourceSepChangeEnabled(d *schema.ResourceData, m interface{}) error { return nil } -func resourceSepUpdateNodes(d *schema.ResourceData, m interface{}) error { +func resourceSepUpdateNodes(ctx context.Context, d *schema.ResourceData, m interface{}) error { log.Debugf("resourceSepUpdateNodes: called for %s, id: %d", d.Get("name").(string), d.Get("sep_id").(int)) c := m.(*controller.ControllerCfg) urlValues := &url.Values{} @@ -345,7 +345,7 @@ func resourceSepUpdateNodes(d *schema.ResourceData, m interface{}) error { } temp = "[" + temp + "]" urlValues.Add("consumer_nids", temp) - _, err := c.DecortAPICall("POST", api, urlValues) + _, err := c.DecortAPICall(ctx, "POST", api, urlValues) if err != nil { return err } @@ -362,7 +362,7 @@ func findElInt(sl []interface{}, el interface{}) bool { return false } -func resourceSepUpdateProviders(d *schema.ResourceData, m interface{}) error { +func resourceSepUpdateProviders(ctx context.Context, d *schema.ResourceData, m interface{}) error { log.Debugf("resourceSepUpdateProviders: called for %s, id: %d", d.Get("name").(string), d.Get("sep_id").(int)) c := m.(*controller.ControllerCfg) urlValues := &url.Values{} @@ -379,7 +379,7 @@ func resourceSepUpdateProviders(d *schema.ResourceData, m interface{}) error { } temp = "[" + temp + "]" urlValues.Add("provider_nids", temp) - _, err := c.DecortAPICall("POST", sepAddProviderNodesAPI, urlValues) + _, err := c.DecortAPICall(ctx, "POST", sepAddProviderNodesAPI, urlValues) if err != nil { return err } @@ -524,7 +524,6 @@ func ResourceSep() *schema.Resource { ReadContext: resourceSepRead, UpdateContext: resourceSepEdit, DeleteContext: resourceSepDelete, - Exists: resourceSepExists, Importer: &schema.ResourceImporter{ State: schema.ImportStatePassthrough, diff --git a/internal/service/cloudbroker/sep/resource_sep_config.go b/internal/service/cloudbroker/sep/resource_sep_config.go index dca075f..f48b51d 100644 --- a/internal/service/cloudbroker/sep/resource_sep_config.go +++ b/internal/service/cloudbroker/sep/resource_sep_config.go @@ -49,7 +49,7 @@ func resourceSepConfigCreate(ctx context.Context, d *schema.ResourceData, m inte log.Debugf("resourceSepConfigCreate: called for sep id %d", d.Get("sep_id").(int)) if _, ok := d.GetOk("sep_id"); ok { - if exists, err := resourceSepConfigExists(d, m); exists { + if exists, err := resourceSepConfigExists(ctx, d, m); exists { if err != nil { return diag.FromErr(err) } @@ -71,7 +71,7 @@ func resourceSepConfigCreate(ctx context.Context, d *schema.ResourceData, m inte func resourceSepConfigRead(ctx context.Context, d *schema.ResourceData, m interface{}) diag.Diagnostics { log.Debugf("resourceSepConfigRead: called for sep id: %d", d.Get("sep_id").(int)) - sepConfig, err := utilitySepConfigCheckPresence(d, m) + sepConfig, err := utilitySepConfigCheckPresence(ctx, d, m) if sepConfig == nil { d.SetId("") return diag.FromErr(err) @@ -86,10 +86,10 @@ func resourceSepConfigDelete(ctx context.Context, d *schema.ResourceData, m inte return nil } -func resourceSepConfigExists(d *schema.ResourceData, m interface{}) (bool, error) { +func resourceSepConfigExists(ctx context.Context, d *schema.ResourceData, m interface{}) (bool, error) { log.Debugf("resourceSepConfigExists: called for sep id: %d", d.Get("sep_id").(int)) - sepDesConfig, err := utilitySepConfigCheckPresence(d, m) + sepDesConfig, err := utilitySepConfigCheckPresence(ctx, d, m) if sepDesConfig == nil { if err != nil { return false, err @@ -108,11 +108,11 @@ func resourceSepConfigEdit(ctx context.Context, d *schema.ResourceData, m interf if d.HasChange("config") { urlValues.Add("sep_id", strconv.Itoa(d.Get("sep_id").(int))) urlValues.Add("config", d.Get("config").(string)) - _, err := c.DecortAPICall("POST", sepConfigValidateAPI, urlValues) + _, err := c.DecortAPICall(ctx, "POST", sepConfigValidateAPI, urlValues) if err != nil { return diag.FromErr(err) } - _, err = c.DecortAPICall("POST", sepConfigInsertAPI, urlValues) + _, err = c.DecortAPICall(ctx, "POST", sepConfigInsertAPI, urlValues) if err != nil { return diag.FromErr(err) } @@ -128,7 +128,7 @@ func resourceSepConfigEdit(ctx context.Context, d *schema.ResourceData, m interf urlValues.Add("field_value", field["field_value"].(string)) urlValues.Add("field_type", field["field_type"].(string)) - _, err := c.DecortAPICall("POST", sepConfigFieldEditAPI, urlValues) + _, err := c.DecortAPICall(ctx, "POST", sepConfigFieldEditAPI, urlValues) if err != nil { return diag.FromErr(err) } @@ -186,7 +186,6 @@ func ResourceSepConfig() *schema.Resource { ReadContext: resourceSepConfigRead, UpdateContext: resourceSepConfigEdit, DeleteContext: resourceSepConfigDelete, - Exists: resourceSepConfigExists, Importer: &schema.ResourceImporter{ State: schema.ImportStatePassthrough, diff --git a/internal/service/cloudbroker/sep/utility_sep.go b/internal/service/cloudbroker/sep/utility_sep.go index a8f3f9d..724fcdf 100644 --- a/internal/service/cloudbroker/sep/utility_sep.go +++ b/internal/service/cloudbroker/sep/utility_sep.go @@ -32,6 +32,7 @@ Documentation: https://github.com/rudecs/terraform-provider-decort/wiki package sep import ( + "context" "encoding/json" "net/url" "strconv" @@ -42,7 +43,7 @@ import ( "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" ) -func utilitySepCheckPresence(d *schema.ResourceData, m interface{}) (*Sep, error) { +func utilitySepCheckPresence(ctx context.Context, d *schema.ResourceData, m interface{}) (*Sep, error) { c := m.(*controller.ControllerCfg) urlValues := &url.Values{} @@ -55,7 +56,7 @@ func utilitySepCheckPresence(d *schema.ResourceData, m interface{}) (*Sep, error } log.Debugf("utilitySepCheckPresence: load sep") - sepRaw, err := c.DecortAPICall("POST", sepGetAPI, urlValues) + sepRaw, err := c.DecortAPICall(ctx, "POST", sepGetAPI, urlValues) if err != nil { return nil, err } diff --git a/internal/service/cloudbroker/sep/utility_sep_config.go b/internal/service/cloudbroker/sep/utility_sep_config.go index d63f19f..e4e247c 100644 --- a/internal/service/cloudbroker/sep/utility_sep_config.go +++ b/internal/service/cloudbroker/sep/utility_sep_config.go @@ -32,6 +32,7 @@ Documentation: https://github.com/rudecs/terraform-provider-decort/wiki package sep import ( + "context" "encoding/json" "net/url" "strconv" @@ -42,7 +43,7 @@ import ( "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" ) -func utilitySepConfigCheckPresence(d *schema.ResourceData, m interface{}) (SepConfig, error) { +func utilitySepConfigCheckPresence(ctx context.Context, d *schema.ResourceData, m interface{}) (SepConfig, error) { c := m.(*controller.ControllerCfg) urlValues := &url.Values{} @@ -51,7 +52,7 @@ func utilitySepConfigCheckPresence(d *schema.ResourceData, m interface{}) (SepCo urlValues.Add("sep_id", strconv.Itoa(d.Get("sep_id").(int))) log.Debugf("utilitySepConfigCheckPresence: load sep config") - sepConfigRaw, err := c.DecortAPICall("POST", sepGetConfigAPI, urlValues) + sepConfigRaw, err := c.DecortAPICall(ctx, "POST", sepGetConfigAPI, urlValues) if err != nil { return nil, err } diff --git a/internal/service/cloudbroker/sep/utility_sep_consumption.go b/internal/service/cloudbroker/sep/utility_sep_consumption.go index 5ce0d8e..88b0985 100644 --- a/internal/service/cloudbroker/sep/utility_sep_consumption.go +++ b/internal/service/cloudbroker/sep/utility_sep_consumption.go @@ -32,6 +32,7 @@ Documentation: https://github.com/rudecs/terraform-provider-decort/wiki package sep import ( + "context" "encoding/json" "net/url" "strconv" @@ -40,7 +41,7 @@ import ( "github.com/rudecs/terraform-provider-decort/internal/controller" ) -func utilitySepConsumptionCheckPresence(d *schema.ResourceData, m interface{}) (*SepConsumption, error) { +func utilitySepConsumptionCheckPresence(ctx context.Context, d *schema.ResourceData, m interface{}) (*SepConsumption, error) { c := m.(*controller.ControllerCfg) urlValues := &url.Values{} @@ -48,7 +49,7 @@ func utilitySepConsumptionCheckPresence(d *schema.ResourceData, m interface{}) ( urlValues.Add("sep_id", strconv.Itoa(d.Get("sep_id").(int))) - sepConsRaw, err := c.DecortAPICall("POST", sepConsumptionAPI, urlValues) + sepConsRaw, err := c.DecortAPICall(ctx, "POST", sepConsumptionAPI, urlValues) if err != nil { return nil, err } diff --git a/internal/service/cloudbroker/sep/utility_sep_disk_list.go b/internal/service/cloudbroker/sep/utility_sep_disk_list.go index 2a2676a..47b0aa8 100644 --- a/internal/service/cloudbroker/sep/utility_sep_disk_list.go +++ b/internal/service/cloudbroker/sep/utility_sep_disk_list.go @@ -32,6 +32,7 @@ Documentation: https://github.com/rudecs/terraform-provider-decort/wiki package sep import ( + "context" "encoding/json" "net/url" "strconv" @@ -42,7 +43,7 @@ import ( "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" ) -func utilitySepDiskListCheckPresence(d *schema.ResourceData, m interface{}) ([]int, error) { +func utilitySepDiskListCheckPresence(ctx context.Context, d *schema.ResourceData, m interface{}) ([]int, error) { c := m.(*controller.ControllerCfg) urlValues := &url.Values{} @@ -55,7 +56,7 @@ func utilitySepDiskListCheckPresence(d *schema.ResourceData, m interface{}) ([]i } log.Debugf("utilitySepDiskListCheckPresence: load sep") - sepDiskListRaw, err := c.DecortAPICall("POST", sepDiskListAPI, urlValues) + sepDiskListRaw, err := c.DecortAPICall(ctx, "POST", sepDiskListAPI, urlValues) if err != nil { return nil, err } diff --git a/internal/service/cloudbroker/sep/utility_sep_list.go b/internal/service/cloudbroker/sep/utility_sep_list.go index ab1fd2f..96dbe0e 100644 --- a/internal/service/cloudbroker/sep/utility_sep_list.go +++ b/internal/service/cloudbroker/sep/utility_sep_list.go @@ -32,6 +32,7 @@ Documentation: https://github.com/rudecs/terraform-provider-decort/wiki package sep import ( + "context" "encoding/json" "net/url" "strconv" @@ -42,7 +43,7 @@ import ( "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" ) -func utilitySepListCheckPresence(d *schema.ResourceData, m interface{}) (SepList, error) { +func utilitySepListCheckPresence(ctx context.Context, d *schema.ResourceData, m interface{}) (SepList, error) { sepList := SepList{} c := m.(*controller.ControllerCfg) urlValues := &url.Values{} @@ -55,7 +56,7 @@ func utilitySepListCheckPresence(d *schema.ResourceData, m interface{}) (SepList } log.Debugf("utilitySepListCheckPresence: load image list") - sepListRaw, err := c.DecortAPICall("POST", sepListAPI, urlValues) + sepListRaw, err := c.DecortAPICall(ctx, "POST", sepListAPI, urlValues) if err != nil { return nil, err } diff --git a/internal/service/cloudbroker/sep/utility_sep_pool.go b/internal/service/cloudbroker/sep/utility_sep_pool.go index a9064fc..4270569 100644 --- a/internal/service/cloudbroker/sep/utility_sep_pool.go +++ b/internal/service/cloudbroker/sep/utility_sep_pool.go @@ -32,6 +32,7 @@ Documentation: https://github.com/rudecs/terraform-provider-decort/wiki package sep import ( + "context" "encoding/json" "net/url" "strconv" @@ -42,7 +43,7 @@ import ( "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" ) -func utilitySepPoolCheckPresence(d *schema.ResourceData, m interface{}) (SepPool, error) { +func utilitySepPoolCheckPresence(ctx context.Context, d *schema.ResourceData, m interface{}) (SepPool, error) { c := m.(*controller.ControllerCfg) urlValues := &url.Values{} @@ -52,7 +53,7 @@ func utilitySepPoolCheckPresence(d *schema.ResourceData, m interface{}) (SepPool urlValues.Add("pool_name", d.Get("pool_name").(string)) log.Debugf("utilitySepDesPoolCheckPresence: load sep") - sepPoolRaw, err := c.DecortAPICall("POST", sepGetPoolAPI, urlValues) + sepPoolRaw, err := c.DecortAPICall(ctx, "POST", sepGetPoolAPI, urlValues) if err != nil { return nil, err } From 48cada2cf3044ab95519933946c481e2fc6dfe05 Mon Sep 17 00:00:00 2001 From: stSolo Date: Thu, 7 Jul 2022 18:46:39 +0300 Subject: [PATCH 38/51] Add locations --- README.md | 3 +- README_EN.md | 3 +- internal/provider/data_sources_map.go | 10 +- internal/provider/provider.go | 16 +- .../cloudapi/account/data_source_account.go | 6 - .../account/data_source_account_rg_list.go | 5 - .../cloudapi/account/resource_account.go | 5 - .../cloudapi/extnet/data_source_extnet.go | 2 - .../cloudapi/kvmvm/data_source_compute.go | 3 +- .../cloudapi/kvmvm/network_subresource.go | 4 +- .../cloudapi/kvmvm/resource_compute.go | 4 +- internal/service/cloudapi/locations/api.go | 23 +++ .../locations/data_source_locations_list.go | 155 ++++++++++++++++++ .../locations/data_source_locations_url.go | 81 +++++++++ internal/service/cloudapi/locations/models.go | 33 ++++ .../locations/utility_location_url.go | 61 +++++++ .../locations/utility_locations_list.go | 70 ++++++++ .../service/cloudapi/rg/data_source_rg.go | 1 - .../cloudapi/rg/data_source_rg_list.go | 1 - .../sep/data_source_sep_consumption.go | 1 - internal/statefuncs/statefuncs.go | 30 ++++ samples/README.md | 2 + samples/{ => cloudapi}/data_account/main.tf | 0 .../data_account_audits_list/main.tf | 0 .../data_account_computes_list/main.tf | 0 .../data_account_consumed_units/main.tf | 0 .../main.tf | 0 .../data_account_deleted_list/main.tf | 0 .../data_account_disks_list/main.tf | 0 .../data_account_flipgroups_list/main.tf | 0 .../{ => cloudapi}/data_account_list/main.tf | 0 .../data_account_reserved_units/main.tf | 0 .../data_account_rg_list/main.tf | 0 .../data_account_templates_list/main.tf | 0 .../data_account_vins_list/main.tf | 0 samples/{ => cloudapi}/data_bservice/main.tf | 0 .../data_bservice_deleted_list/main.tf | 0 .../data_bservice_group/main.tf | 0 .../{ => cloudapi}/data_bservice_list/main.tf | 0 .../data_bservice_snapshot_list/main.tf | 0 samples/{ => cloudapi}/data_disk_list/main.tf | 0 samples/{ => cloudapi}/data_extnet/main.tf | 0 .../data_extnet_computes_list/main.tf | 0 .../data_extnet_default/main.tf | 0 .../{ => cloudapi}/data_extnet_list/main.tf | 0 samples/cloudapi/data_location_url/main.tf | 0 samples/cloudapi/data_locations_list/main.tf | 45 +++++ samples/{ => cloudapi}/data_rg_list/main.tf | 0 .../{ => cloudapi}/data_snapshot_list/main.tf | 0 samples/{ => cloudapi}/data_vgpu/main.tf | 0 samples/{ => cloudapi}/data_vins_list/main.tf | 0 .../{ => cloudapi}/resource_account/main.tf | 0 .../{ => cloudapi}/resource_bservice/main.tf | 0 .../resource_bservice_group/main.tf | 0 samples/{ => cloudapi}/resource_k8s/main.tf | 0 .../{ => cloudapi}/resource_k8s_wg/main.tf | 0 .../{ => cloudapi}/resource_snapshot/main.tf | 0 samples/{ => cloudbroker}/data_grid/main.tf | 0 .../{ => cloudbroker}/data_grid_list/main.tf | 0 samples/{ => cloudbroker}/data_image/main.tf | 0 .../{ => cloudbroker}/data_image_list/main.tf | 0 .../data_image_list_stacks/main.tf | 0 .../{ => cloudbroker}/data_pcidevice/main.tf | 0 .../data_pcidevice_list/main.tf | 0 samples/{ => cloudbroker}/data_sep/main.tf | 0 .../{ => cloudbroker}/data_sep_config/main.tf | 0 .../data_sep_consumption/main.tf | 0 .../data_sep_disk_list/main.tf | 0 .../{ => cloudbroker}/data_sep_list/main.tf | 0 .../{ => cloudbroker}/data_sep_pool/main.tf | 0 .../resource_delete_images/main.tf | 0 .../{ => cloudbroker}/resource_image/main.tf | 0 .../resource_image_cdrom/main.tf | 0 .../resource_pcidevice/main.tf | 0 .../{ => cloudbroker}/resource_sep/main.tf | 0 .../resource_sep_config/main.tf | 0 .../resource_virtual_image/main.tf | 0 77 files changed, 520 insertions(+), 44 deletions(-) create mode 100644 internal/service/cloudapi/locations/api.go create mode 100644 internal/service/cloudapi/locations/data_source_locations_list.go create mode 100644 internal/service/cloudapi/locations/data_source_locations_url.go create mode 100644 internal/service/cloudapi/locations/models.go create mode 100644 internal/service/cloudapi/locations/utility_location_url.go create mode 100644 internal/service/cloudapi/locations/utility_locations_list.go create mode 100644 internal/statefuncs/statefuncs.go rename samples/{ => cloudapi}/data_account/main.tf (100%) rename samples/{ => cloudapi}/data_account_audits_list/main.tf (100%) rename samples/{ => cloudapi}/data_account_computes_list/main.tf (100%) rename samples/{ => cloudapi}/data_account_consumed_units/main.tf (100%) rename samples/{ => cloudapi}/data_account_consumed_units_by_type/main.tf (100%) rename samples/{ => cloudapi}/data_account_deleted_list/main.tf (100%) rename samples/{ => cloudapi}/data_account_disks_list/main.tf (100%) rename samples/{ => cloudapi}/data_account_flipgroups_list/main.tf (100%) rename samples/{ => cloudapi}/data_account_list/main.tf (100%) rename samples/{ => cloudapi}/data_account_reserved_units/main.tf (100%) rename samples/{ => cloudapi}/data_account_rg_list/main.tf (100%) rename samples/{ => cloudapi}/data_account_templates_list/main.tf (100%) rename samples/{ => cloudapi}/data_account_vins_list/main.tf (100%) rename samples/{ => cloudapi}/data_bservice/main.tf (100%) rename samples/{ => cloudapi}/data_bservice_deleted_list/main.tf (100%) rename samples/{ => cloudapi}/data_bservice_group/main.tf (100%) rename samples/{ => cloudapi}/data_bservice_list/main.tf (100%) rename samples/{ => cloudapi}/data_bservice_snapshot_list/main.tf (100%) rename samples/{ => cloudapi}/data_disk_list/main.tf (100%) rename samples/{ => cloudapi}/data_extnet/main.tf (100%) rename samples/{ => cloudapi}/data_extnet_computes_list/main.tf (100%) rename samples/{ => cloudapi}/data_extnet_default/main.tf (100%) rename samples/{ => cloudapi}/data_extnet_list/main.tf (100%) create mode 100644 samples/cloudapi/data_location_url/main.tf create mode 100644 samples/cloudapi/data_locations_list/main.tf rename samples/{ => cloudapi}/data_rg_list/main.tf (100%) rename samples/{ => cloudapi}/data_snapshot_list/main.tf (100%) rename samples/{ => cloudapi}/data_vgpu/main.tf (100%) rename samples/{ => cloudapi}/data_vins_list/main.tf (100%) rename samples/{ => cloudapi}/resource_account/main.tf (100%) rename samples/{ => cloudapi}/resource_bservice/main.tf (100%) rename samples/{ => cloudapi}/resource_bservice_group/main.tf (100%) rename samples/{ => cloudapi}/resource_k8s/main.tf (100%) rename samples/{ => cloudapi}/resource_k8s_wg/main.tf (100%) rename samples/{ => cloudapi}/resource_snapshot/main.tf (100%) rename samples/{ => cloudbroker}/data_grid/main.tf (100%) rename samples/{ => cloudbroker}/data_grid_list/main.tf (100%) rename samples/{ => cloudbroker}/data_image/main.tf (100%) rename samples/{ => cloudbroker}/data_image_list/main.tf (100%) rename samples/{ => cloudbroker}/data_image_list_stacks/main.tf (100%) rename samples/{ => cloudbroker}/data_pcidevice/main.tf (100%) rename samples/{ => cloudbroker}/data_pcidevice_list/main.tf (100%) rename samples/{ => cloudbroker}/data_sep/main.tf (100%) rename samples/{ => cloudbroker}/data_sep_config/main.tf (100%) rename samples/{ => cloudbroker}/data_sep_consumption/main.tf (100%) rename samples/{ => cloudbroker}/data_sep_disk_list/main.tf (100%) rename samples/{ => cloudbroker}/data_sep_list/main.tf (100%) rename samples/{ => cloudbroker}/data_sep_pool/main.tf (100%) rename samples/{ => cloudbroker}/resource_delete_images/main.tf (100%) rename samples/{ => cloudbroker}/resource_image/main.tf (100%) rename samples/{ => cloudbroker}/resource_image_cdrom/main.tf (100%) rename samples/{ => cloudbroker}/resource_pcidevice/main.tf (100%) rename samples/{ => cloudbroker}/resource_sep/main.tf (100%) rename samples/{ => cloudbroker}/resource_sep_config/main.tf (100%) rename samples/{ => cloudbroker}/resource_virtual_image/main.tf (100%) diff --git a/README.md b/README.md index 36687f1..566daaa 100644 --- a/README.md +++ b/README.md @@ -20,7 +20,8 @@ Terraform provider для платформы Digital Energy Cloud Orchestration - Работа с sep, - Работа с vgpu, - Работа с bservice, -- Работа с extnets. +- Работа с extnets, +- Работа с locations. Вики проекта: https://github.com/rudecs/terraform-provider-decort/wiki diff --git a/README_EN.md b/README_EN.md index 396d151..d942b38 100644 --- a/README_EN.md +++ b/README_EN.md @@ -19,7 +19,8 @@ NOTE: provider rc-1.25 is designed for DECORT API 3.7.x. For older API versions - Work with sep, - Work with vgpu, - Work with bservice, -- Work with extnets. +- Work with extnets, +- Work with locations. This provider supports Import operations on pre-existing resources. diff --git a/internal/provider/data_sources_map.go b/internal/provider/data_sources_map.go index 70d715a..5897525 100644 --- a/internal/provider/data_sources_map.go +++ b/internal/provider/data_sources_map.go @@ -25,6 +25,8 @@ import ( "github.com/rudecs/terraform-provider-decort/internal/service/cloudapi/bservice" "github.com/rudecs/terraform-provider-decort/internal/service/cloudapi/disks" "github.com/rudecs/terraform-provider-decort/internal/service/cloudapi/extnet" + "github.com/rudecs/terraform-provider-decort/internal/service/cloudapi/kvmvm" + "github.com/rudecs/terraform-provider-decort/internal/service/cloudapi/locations" "github.com/rudecs/terraform-provider-decort/internal/service/cloudapi/rg" "github.com/rudecs/terraform-provider-decort/internal/service/cloudapi/snapshot" "github.com/rudecs/terraform-provider-decort/internal/service/cloudapi/vgpu" @@ -37,9 +39,9 @@ import ( func NewDataSourcesMap() map[string]*schema.Resource { return map[string]*schema.Resource{ - "decort_account": account.DataSourceAccount(), - "decort_resgroup": rg.DataSourceResgroup(), - // "decort_kvmvm": dataSourceCompute(), + "decort_account": account.DataSourceAccount(), + "decort_resgroup": rg.DataSourceResgroup(), + "decort_kvmvm": kvmvm.DataSourceCompute(), "decort_image": image.DataSourceImage(), "decort_disk": disks.DataSourceDisk(), "decort_vins": vins.DataSourceVins(), @@ -81,6 +83,8 @@ func NewDataSourcesMap() map[string]*schema.Resource { "decort_extnet": extnet.DataSourceExtnet(), "decort_extnet_default": extnet.DataSourceExtnetDefault(), "decort_vins_list": vins.DataSourceVinsList(), + "decort_locations_list": locations.DataSourceLocationsList(), + "decort_location_url": locations.DataSourceLocationUrl(), // "decort_pfw": dataSourcePfw(), } diff --git a/internal/provider/provider.go b/internal/provider/provider.go index c6c76f1..39fe2c3 100644 --- a/internal/provider/provider.go +++ b/internal/provider/provider.go @@ -21,7 +21,6 @@ package provider import ( "fmt" - "strings" "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" "github.com/hashicorp/terraform-plugin-sdk/v2/helper/validation" @@ -29,6 +28,7 @@ import ( "github.com/rudecs/terraform-provider-decort/internal/controller" "github.com/rudecs/terraform-provider-decort/internal/location" + "github.com/rudecs/terraform-provider-decort/internal/statefuncs" ) func Provider() *schema.Provider { @@ -37,7 +37,7 @@ func Provider() *schema.Provider { "authenticator": { Type: schema.TypeString, Required: true, - StateFunc: StateFuncToLower, + StateFunc: statefuncs.StateFuncToLower, ValidateFunc: validation.StringInSlice([]string{"oauth2", "legacy", "jwt"}, true), // ignore case while validating Description: "Authentication mode to use when connecting to DECORT cloud API. Should be one of 'oauth2', 'legacy' or 'jwt'.", }, @@ -45,7 +45,7 @@ func Provider() *schema.Provider { "oauth2_url": { Type: schema.TypeString, Optional: true, - StateFunc: StateFuncToLower, + StateFunc: statefuncs.StateFuncToLower, DefaultFunc: schema.EnvDefaultFunc("DECORT_OAUTH2_URL", nil), Description: "OAuth2 application URL in 'oauth2' authentication mode.", }, @@ -54,7 +54,7 @@ func Provider() *schema.Provider { Type: schema.TypeString, Required: true, ForceNew: true, - StateFunc: StateFuncToLower, + StateFunc: statefuncs.StateFuncToLower, Description: "URL of DECORT Cloud controller to use. API calls will be directed to this URL.", }, @@ -109,14 +109,6 @@ func Provider() *schema.Provider { } } -func StateFuncToLower(argval interface{}) string { - return strings.ToLower(argval.(string)) -} - -func StateFuncToUpper(argval interface{}) string { - return strings.ToUpper(argval.(string)) -} - func providerConfigure(d *schema.ResourceData) (interface{}, error) { decsController, err := controller.ControllerConfigure(d) if err != nil { diff --git a/internal/service/cloudapi/account/data_source_account.go b/internal/service/cloudapi/account/data_source_account.go index f3b2c6e..233ac18 100644 --- a/internal/service/cloudapi/account/data_source_account.go +++ b/internal/service/cloudapi/account/data_source_account.go @@ -168,13 +168,11 @@ func dataSourceAccountSchemaMake() map[string]*schema.Schema { "resources": { Type: schema.TypeList, Computed: true, - MaxItems: 1, Elem: &schema.Resource{ Schema: map[string]*schema.Schema{ "current": { Type: schema.TypeList, Computed: true, - MaxItems: 1, Elem: &schema.Resource{ Schema: map[string]*schema.Schema{ "cpu": { @@ -207,7 +205,6 @@ func dataSourceAccountSchemaMake() map[string]*schema.Schema { "reserved": { Type: schema.TypeList, Computed: true, - MaxItems: 1, Elem: &schema.Resource{ Schema: map[string]*schema.Schema{ "cpu": { @@ -330,7 +327,6 @@ func dataSourceAccountSchemaMake() map[string]*schema.Schema { "resource_limits": { Type: schema.TypeList, Computed: true, - MaxItems: 1, Elem: &schema.Resource{ Schema: map[string]*schema.Schema{ "cu_c": { @@ -390,7 +386,6 @@ func dataSourceAccountSchemaMake() map[string]*schema.Schema { "computes": { Type: schema.TypeList, Computed: true, - MaxItems: 1, Elem: &schema.Resource{ Schema: map[string]*schema.Schema{ "started": { @@ -407,7 +402,6 @@ func dataSourceAccountSchemaMake() map[string]*schema.Schema { "machines": { Type: schema.TypeList, Computed: true, - MaxItems: 1, Elem: &schema.Resource{ Schema: map[string]*schema.Schema{ "halted": { diff --git a/internal/service/cloudapi/account/data_source_account_rg_list.go b/internal/service/cloudapi/account/data_source_account_rg_list.go index c9b94d4..42fa18e 100644 --- a/internal/service/cloudapi/account/data_source_account_rg_list.go +++ b/internal/service/cloudapi/account/data_source_account_rg_list.go @@ -113,7 +113,6 @@ func dataSourceAccountRGListSchemaMake() map[string]*schema.Schema { Schema: map[string]*schema.Schema{ "computes": { Type: schema.TypeList, - MaxItems: 1, Computed: true, Elem: &schema.Resource{ Schema: map[string]*schema.Schema{ @@ -131,13 +130,11 @@ func dataSourceAccountRGListSchemaMake() map[string]*schema.Schema { "resources": { Type: schema.TypeList, Computed: true, - MaxItems: 1, Elem: &schema.Resource{ Schema: map[string]*schema.Schema{ "consumed": { Type: schema.TypeList, Computed: true, - MaxItems: 1, Elem: &schema.Resource{ Schema: map[string]*schema.Schema{ "cpu": { @@ -171,7 +168,6 @@ func dataSourceAccountRGListSchemaMake() map[string]*schema.Schema { "limits": { Type: schema.TypeList, Computed: true, - MaxItems: 1, Elem: &schema.Resource{ Schema: map[string]*schema.Schema{ "cpu": { @@ -204,7 +200,6 @@ func dataSourceAccountRGListSchemaMake() map[string]*schema.Schema { "reserved": { Type: schema.TypeList, Computed: true, - MaxItems: 1, Elem: &schema.Resource{ Schema: map[string]*schema.Schema{ "cpu": { diff --git a/internal/service/cloudapi/account/resource_account.go b/internal/service/cloudapi/account/resource_account.go index 5aa57f7..3ad2939 100644 --- a/internal/service/cloudapi/account/resource_account.go +++ b/internal/service/cloudapi/account/resource_account.go @@ -559,13 +559,11 @@ func resourceAccountSchemaMake() map[string]*schema.Schema { "resources": { Type: schema.TypeList, Computed: true, - MaxItems: 1, Elem: &schema.Resource{ Schema: map[string]*schema.Schema{ "current": { Type: schema.TypeList, Computed: true, - MaxItems: 1, Elem: &schema.Resource{ Schema: map[string]*schema.Schema{ "cpu": { @@ -598,7 +596,6 @@ func resourceAccountSchemaMake() map[string]*schema.Schema { "reserved": { Type: schema.TypeList, Computed: true, - MaxItems: 1, Elem: &schema.Resource{ Schema: map[string]*schema.Schema{ "cpu": { @@ -740,7 +737,6 @@ func resourceAccountSchemaMake() map[string]*schema.Schema { "computes": { Type: schema.TypeList, Computed: true, - MaxItems: 1, Elem: &schema.Resource{ Schema: map[string]*schema.Schema{ "started": { @@ -757,7 +753,6 @@ func resourceAccountSchemaMake() map[string]*schema.Schema { "machines": { Type: schema.TypeList, Computed: true, - MaxItems: 1, Elem: &schema.Resource{ Schema: map[string]*schema.Schema{ "halted": { diff --git a/internal/service/cloudapi/extnet/data_source_extnet.go b/internal/service/cloudapi/extnet/data_source_extnet.go index 9744b3c..02de7cf 100644 --- a/internal/service/cloudapi/extnet/data_source_extnet.go +++ b/internal/service/cloudapi/extnet/data_source_extnet.go @@ -156,7 +156,6 @@ func dataSourceExtnetSchemaMake() map[string]*schema.Schema { }, "default_qos": { Type: schema.TypeList, - MaxItems: 1, Computed: true, Elem: &schema.Resource{ Schema: map[string]*schema.Schema{ @@ -302,7 +301,6 @@ func dataSourceExtnetSchemaMake() map[string]*schema.Schema { }, "vnfs": { Type: schema.TypeList, - MaxItems: 1, Computed: true, Elem: &schema.Resource{ Schema: map[string]*schema.Schema{ diff --git a/internal/service/cloudapi/kvmvm/data_source_compute.go b/internal/service/cloudapi/kvmvm/data_source_compute.go index 7738409..2ad51d1 100644 --- a/internal/service/cloudapi/kvmvm/data_source_compute.go +++ b/internal/service/cloudapi/kvmvm/data_source_compute.go @@ -207,7 +207,7 @@ func dataSourceComputeRead(ctx context.Context, d *schema.ResourceData, m interf return diag.FromErr(flattenCompute(d, compFacts)) } -func dataSourceCompute() *schema.Resource { +func DataSourceCompute() *schema.Resource { return &schema.Resource{ SchemaVersion: 1, @@ -302,7 +302,6 @@ func dataSourceCompute() *schema.Resource { "extra_disks": { Type: schema.TypeSet, Computed: true, - MaxItems: constants.MaxExtraDisksPerCompute, Elem: &schema.Schema{ Type: schema.TypeInt, }, diff --git a/internal/service/cloudapi/kvmvm/network_subresource.go b/internal/service/cloudapi/kvmvm/network_subresource.go index 4a0663f..9bc94b4 100644 --- a/internal/service/cloudapi/kvmvm/network_subresource.go +++ b/internal/service/cloudapi/kvmvm/network_subresource.go @@ -35,7 +35,7 @@ import ( "bytes" "hash/fnv" - "github.com/rudecs/terraform-provider-decort/internal/provider" + "github.com/rudecs/terraform-provider-decort/internal/statefuncs" log "github.com/sirupsen/logrus" "sort" @@ -125,7 +125,7 @@ func networkSubresourceSchemaMake() map[string]*schema.Schema { "net_type": { Type: schema.TypeString, Required: true, - StateFunc: provider.StateFuncToUpper, + StateFunc: statefuncs.StateFuncToUpper, ValidateFunc: validation.StringInSlice([]string{"EXTNET", "VINS"}, false), // observe case while validating Description: "Type of the network for this connection, either EXTNET or VINS.", }, diff --git a/internal/service/cloudapi/kvmvm/resource_compute.go b/internal/service/cloudapi/kvmvm/resource_compute.go index 75dde35..941c16d 100644 --- a/internal/service/cloudapi/kvmvm/resource_compute.go +++ b/internal/service/cloudapi/kvmvm/resource_compute.go @@ -40,7 +40,7 @@ import ( "github.com/rudecs/terraform-provider-decort/internal/constants" "github.com/rudecs/terraform-provider-decort/internal/controller" - "github.com/rudecs/terraform-provider-decort/internal/provider" + "github.com/rudecs/terraform-provider-decort/internal/statefuncs" log "github.com/sirupsen/logrus" "github.com/hashicorp/terraform-plugin-sdk/v2/diag" @@ -394,7 +394,7 @@ func ResourceCompute() *schema.Resource { Type: schema.TypeString, Required: true, ForceNew: true, - StateFunc: provider.StateFuncToUpper, + StateFunc: statefuncs.StateFuncToUpper, ValidateFunc: validation.StringInSlice([]string{"KVM_X86", "KVM_PPC"}, false), // observe case while validating Description: "Hardware architecture of this compute instance.", }, diff --git a/internal/service/cloudapi/locations/api.go b/internal/service/cloudapi/locations/api.go new file mode 100644 index 0000000..7d26c35 --- /dev/null +++ b/internal/service/cloudapi/locations/api.go @@ -0,0 +1,23 @@ +package locations + +/* +Copyright (c) 2019-2022 Digital Energy Cloud Solutions LLC. All Rights Reserved. +Authors: +Petr Krutov, +Stanislav Solovev, + +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. +*/ + +const locationsListAPI = "/restmachine/cloudapi/locations/list" +const locationURLAPI = "/restmachine/cloudapi/locations/getUrl" diff --git a/internal/service/cloudapi/locations/data_source_locations_list.go b/internal/service/cloudapi/locations/data_source_locations_list.go new file mode 100644 index 0000000..3129015 --- /dev/null +++ b/internal/service/cloudapi/locations/data_source_locations_list.go @@ -0,0 +1,155 @@ +/* +Copyright (c) 2019-2022 Digital Energy Cloud Solutions LLC. All Rights Reserved. +Authors: +Petr Krutov, +Stanislav Solovev, + +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. +*/ + +/* +Terraform DECORT provider - manage resources provided by DECORT (Digital Energy Cloud +Orchestration Technology) with Terraform by Hashicorp. + +Source code: https://github.com/rudecs/terraform-provider-decort + +Please see README.md to learn where to place source code so that it +builds seamlessly. + +Documentation: https://github.com/rudecs/terraform-provider-decort/wiki +*/ + +package locations + +import ( + "context" + + "github.com/google/uuid" + "github.com/hashicorp/terraform-plugin-sdk/v2/diag" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" + "github.com/rudecs/terraform-provider-decort/internal/constants" + "github.com/rudecs/terraform-provider-decort/internal/flattens" +) + +func flattenLocationsList(ll LocationsList) []map[string]interface{} { + res := make([]map[string]interface{}, 0) + for _, l := range ll { + temp := map[string]interface{}{ + "ckey": l.CKey, + "meta": flattens.FlattenMeta(l.Meta), + "flag": l.Flag, + "gid": l.GridID, + "guid": l.Guid, + "id": l.Id, + "location_code": l.LocationCode, + "name": l.Name, + } + res = append(res, temp) + } + return res + +} + +func dataSourceLocationsListRead(ctx context.Context, d *schema.ResourceData, m interface{}) diag.Diagnostics { + locations, err := utilityLocationsListCheckPresence(ctx, d, m) + if err != nil { + + return diag.FromErr(err) + } + + id := uuid.New() + d.SetId(id.String()) + + d.Set("items", flattenLocationsList(locations)) + + return nil +} + +func dataSourceLocationsListSchemaMake() map[string]*schema.Schema { + return map[string]*schema.Schema{ + "page": { + Type: schema.TypeInt, + Optional: true, + Description: "page number", + }, + "size": { + Type: schema.TypeInt, + Optional: true, + Description: "page size", + }, + "items": { + Type: schema.TypeList, + Computed: true, + Description: "Locations list", + Elem: &schema.Resource{ + Schema: map[string]*schema.Schema{ + "ckey": { + Type: schema.TypeString, + Computed: true, + }, + "meta": { + Type: schema.TypeList, + Computed: true, + Elem: &schema.Schema{ + Type: schema.TypeString, + }, + }, + "flag": { + Type: schema.TypeString, + Computed: true, + }, + "gid": { + Type: schema.TypeInt, + Computed: true, + Description: "Grid id", + }, + "guid": { + Type: schema.TypeInt, + Computed: true, + Description: "location id", + }, + "id": { + Type: schema.TypeInt, + Computed: true, + Description: "location id", + }, + "location_code": { + Type: schema.TypeString, + Computed: true, + Description: "Location code", + }, + "name": { + Type: schema.TypeString, + Computed: true, + Description: "Location name", + }, + }, + }, + }, + } +} + +func DataSourceLocationsList() *schema.Resource { + return &schema.Resource{ + SchemaVersion: 1, + + ReadContext: dataSourceLocationsListRead, + + Timeouts: &schema.ResourceTimeout{ + Read: &constants.Timeout30s, + Default: &constants.Timeout60s, + }, + + Schema: dataSourceLocationsListSchemaMake(), + } +} diff --git a/internal/service/cloudapi/locations/data_source_locations_url.go b/internal/service/cloudapi/locations/data_source_locations_url.go new file mode 100644 index 0000000..b06d55b --- /dev/null +++ b/internal/service/cloudapi/locations/data_source_locations_url.go @@ -0,0 +1,81 @@ +/* +Copyright (c) 2019-2022 Digital Energy Cloud Solutions LLC. All Rights Reserved. +Authors: +Petr Krutov, +Stanislav Solovev, + +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. +*/ + +/* +Terraform DECORT provider - manage resources provided by DECORT (Digital Energy Cloud +Orchestration Technology) with Terraform by Hashicorp. + +Source code: https://github.com/rudecs/terraform-provider-decort + +Please see README.md to learn where to place source code so that it +builds seamlessly. + +Documentation: https://github.com/rudecs/terraform-provider-decort/wiki +*/ + +package locations + +import ( + "context" + + "github.com/google/uuid" + "github.com/hashicorp/terraform-plugin-sdk/v2/diag" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" + "github.com/rudecs/terraform-provider-decort/internal/constants" +) + +func dataSourceLocationUrlRead(ctx context.Context, d *schema.ResourceData, m interface{}) diag.Diagnostics { + url, err := utilityLocationUrlCheckPresence(ctx, d, m) + if err != nil { + + return diag.FromErr(err) + } + + id := uuid.New() + d.SetId(id.String()) + + d.Set("url", url) + + return nil +} + +func dataSourceLocationUrlSchemaMake() map[string]*schema.Schema { + return map[string]*schema.Schema{ + "url": { + Type: schema.TypeString, + Computed: true, + Description: "Location url", + }, + } +} + +func DataSourceLocationUrl() *schema.Resource { + return &schema.Resource{ + SchemaVersion: 1, + + ReadContext: dataSourceLocationUrlRead, + + Timeouts: &schema.ResourceTimeout{ + Read: &constants.Timeout30s, + Default: &constants.Timeout60s, + }, + + Schema: dataSourceLocationUrlSchemaMake(), + } +} diff --git a/internal/service/cloudapi/locations/models.go b/internal/service/cloudapi/locations/models.go new file mode 100644 index 0000000..a65104f --- /dev/null +++ b/internal/service/cloudapi/locations/models.go @@ -0,0 +1,33 @@ +/* +Copyright (c) 2019-2022 Digital Energy Cloud Solutions LLC. All Rights Reserved. +Authors: +Petr Krutov, +Stanislav Solovev, + +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. +*/ + +package locations + +type Location struct { + GridID int `json:"gid"` + Id int `json:"id"` + Guid int `json:"guid"` + LocationCode string `json:"locationCode"` + Name string `json:"name"` + Flag string `json:"flag"` + Meta []interface{} `json:"_meta"` + CKey string `json:"_ckey"` +} + +type LocationsList []Location diff --git a/internal/service/cloudapi/locations/utility_location_url.go b/internal/service/cloudapi/locations/utility_location_url.go new file mode 100644 index 0000000..9ebc215 --- /dev/null +++ b/internal/service/cloudapi/locations/utility_location_url.go @@ -0,0 +1,61 @@ +/* +Copyright (c) 2019-2022 Digital Energy Cloud Solutions LLC. All Rights Reserved. +Authors: +Petr Krutov, +Stanislav Solovev, + +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. +*/ + +/* +Terraform DECORT provider - manage resources provided by DECORT (Digital Energy Cloud +Orchestration Technology) with Terraform by Hashicorp. + +Source code: https://github.com/rudecs/terraform-provider-decort + +Please see README.md to learn where to place source code so that it +builds seamlessly. + +Documentation: https://github.com/rudecs/terraform-provider-decort/wiki +*/ + +package locations + +import ( + "context" + "encoding/json" + "net/url" + + "github.com/rudecs/terraform-provider-decort/internal/controller" + log "github.com/sirupsen/logrus" + + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" +) + +func utilityLocationUrlCheckPresence(ctx context.Context, d *schema.ResourceData, m interface{}) (string, error) { + c := m.(*controller.ControllerCfg) + + log.Debugf("utilityLocationUrlCheckPresence: load locations list") + locationUrl, err := c.DecortAPICall(ctx, "POST", locationURLAPI, &url.Values{}) + if err != nil { + return "", err + } + + location := new(string) + err = json.Unmarshal([]byte(locationUrl), location) + if err != nil { + return "", nil + } + + return *location, nil +} diff --git a/internal/service/cloudapi/locations/utility_locations_list.go b/internal/service/cloudapi/locations/utility_locations_list.go new file mode 100644 index 0000000..3454980 --- /dev/null +++ b/internal/service/cloudapi/locations/utility_locations_list.go @@ -0,0 +1,70 @@ +/* +Copyright (c) 2019-2022 Digital Energy Cloud Solutions LLC. All Rights Reserved. +Authors: +Petr Krutov, +Stanislav Solovev, + +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. +*/ + +/* +Terraform DECORT provider - manage resources provided by DECORT (Digital Energy Cloud +Orchestration Technology) with Terraform by Hashicorp. + +Source code: https://github.com/rudecs/terraform-provider-decort + +Please see README.md to learn where to place source code so that it +builds seamlessly. + +Documentation: https://github.com/rudecs/terraform-provider-decort/wiki +*/ + +package locations + +import ( + "context" + "encoding/json" + "net/url" + "strconv" + + "github.com/rudecs/terraform-provider-decort/internal/controller" + log "github.com/sirupsen/logrus" + + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" +) + +func utilityLocationsListCheckPresence(ctx context.Context, d *schema.ResourceData, m interface{}) (LocationsList, error) { + locationsList := LocationsList{} + c := m.(*controller.ControllerCfg) + urlValues := &url.Values{} + + if page, ok := d.GetOk("page"); ok { + urlValues.Add("page", strconv.Itoa(page.(int))) + } + if size, ok := d.GetOk("size"); ok { + urlValues.Add("size", strconv.Itoa(size.(int))) + } + + log.Debugf("utilityLocationsListCheckPresence: load locations list") + locationsListRaw, err := c.DecortAPICall(ctx, "POST", locationsListAPI, urlValues) + if err != nil { + return nil, err + } + + err = json.Unmarshal([]byte(locationsListRaw), &locationsList) + if err != nil { + return nil, err + } + + return locationsList, nil +} diff --git a/internal/service/cloudapi/rg/data_source_rg.go b/internal/service/cloudapi/rg/data_source_rg.go index 09d42ec..3afdb69 100644 --- a/internal/service/cloudapi/rg/data_source_rg.go +++ b/internal/service/cloudapi/rg/data_source_rg.go @@ -147,7 +147,6 @@ func DataSourceResgroup() *schema.Resource { "quota": { Type: schema.TypeList, Computed: true, - MaxItems: 1, Elem: &schema.Resource{ Schema: quotaRgSubresourceSchemaMake(), // this is a dictionary }, diff --git a/internal/service/cloudapi/rg/data_source_rg_list.go b/internal/service/cloudapi/rg/data_source_rg_list.go index b33c5ea..dfbb888 100644 --- a/internal/service/cloudapi/rg/data_source_rg_list.go +++ b/internal/service/cloudapi/rg/data_source_rg_list.go @@ -242,7 +242,6 @@ func dataSourceRgListSchemaMake() map[string]*schema.Schema { "resource_limits": { Type: schema.TypeList, Computed: true, - MaxItems: 1, Elem: &schema.Resource{ Schema: map[string]*schema.Schema{ "cu_c": { diff --git a/internal/service/cloudbroker/sep/data_source_sep_consumption.go b/internal/service/cloudbroker/sep/data_source_sep_consumption.go index 1b3406b..73e6d4e 100644 --- a/internal/service/cloudbroker/sep/data_source_sep_consumption.go +++ b/internal/service/cloudbroker/sep/data_source_sep_consumption.go @@ -141,7 +141,6 @@ func dataSourceSepConsumptionSchemaMake() map[string]*schema.Schema { "total": { Type: schema.TypeList, Computed: true, - MaxItems: 1, Elem: &schema.Resource{ Schema: map[string]*schema.Schema{ "capacity_limit": { diff --git a/internal/statefuncs/statefuncs.go b/internal/statefuncs/statefuncs.go new file mode 100644 index 0000000..44c17af --- /dev/null +++ b/internal/statefuncs/statefuncs.go @@ -0,0 +1,30 @@ +/* +Copyright (c) 2019-2022 Digital Energy Cloud Solutions LLC. All Rights Reserved. +Authors: +Petr Krutov, +Stanislav Solovev, + +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. +*/ + +package statefuncs + +import "strings" + +func StateFuncToLower(argval interface{}) string { + return strings.ToLower(argval.(string)) +} + +func StateFuncToUpper(argval interface{}) string { + return strings.ToUpper(argval.(string)) +} diff --git a/samples/README.md b/samples/README.md index 1797fa0..d77ed3e 100644 --- a/samples/README.md +++ b/samples/README.md @@ -42,6 +42,8 @@ - extnet - extnet_computes_list - vins_list + - locations_list + - location_url - resources: - image - virtual_image diff --git a/samples/data_account/main.tf b/samples/cloudapi/data_account/main.tf similarity index 100% rename from samples/data_account/main.tf rename to samples/cloudapi/data_account/main.tf diff --git a/samples/data_account_audits_list/main.tf b/samples/cloudapi/data_account_audits_list/main.tf similarity index 100% rename from samples/data_account_audits_list/main.tf rename to samples/cloudapi/data_account_audits_list/main.tf diff --git a/samples/data_account_computes_list/main.tf b/samples/cloudapi/data_account_computes_list/main.tf similarity index 100% rename from samples/data_account_computes_list/main.tf rename to samples/cloudapi/data_account_computes_list/main.tf diff --git a/samples/data_account_consumed_units/main.tf b/samples/cloudapi/data_account_consumed_units/main.tf similarity index 100% rename from samples/data_account_consumed_units/main.tf rename to samples/cloudapi/data_account_consumed_units/main.tf diff --git a/samples/data_account_consumed_units_by_type/main.tf b/samples/cloudapi/data_account_consumed_units_by_type/main.tf similarity index 100% rename from samples/data_account_consumed_units_by_type/main.tf rename to samples/cloudapi/data_account_consumed_units_by_type/main.tf diff --git a/samples/data_account_deleted_list/main.tf b/samples/cloudapi/data_account_deleted_list/main.tf similarity index 100% rename from samples/data_account_deleted_list/main.tf rename to samples/cloudapi/data_account_deleted_list/main.tf diff --git a/samples/data_account_disks_list/main.tf b/samples/cloudapi/data_account_disks_list/main.tf similarity index 100% rename from samples/data_account_disks_list/main.tf rename to samples/cloudapi/data_account_disks_list/main.tf diff --git a/samples/data_account_flipgroups_list/main.tf b/samples/cloudapi/data_account_flipgroups_list/main.tf similarity index 100% rename from samples/data_account_flipgroups_list/main.tf rename to samples/cloudapi/data_account_flipgroups_list/main.tf diff --git a/samples/data_account_list/main.tf b/samples/cloudapi/data_account_list/main.tf similarity index 100% rename from samples/data_account_list/main.tf rename to samples/cloudapi/data_account_list/main.tf diff --git a/samples/data_account_reserved_units/main.tf b/samples/cloudapi/data_account_reserved_units/main.tf similarity index 100% rename from samples/data_account_reserved_units/main.tf rename to samples/cloudapi/data_account_reserved_units/main.tf diff --git a/samples/data_account_rg_list/main.tf b/samples/cloudapi/data_account_rg_list/main.tf similarity index 100% rename from samples/data_account_rg_list/main.tf rename to samples/cloudapi/data_account_rg_list/main.tf diff --git a/samples/data_account_templates_list/main.tf b/samples/cloudapi/data_account_templates_list/main.tf similarity index 100% rename from samples/data_account_templates_list/main.tf rename to samples/cloudapi/data_account_templates_list/main.tf diff --git a/samples/data_account_vins_list/main.tf b/samples/cloudapi/data_account_vins_list/main.tf similarity index 100% rename from samples/data_account_vins_list/main.tf rename to samples/cloudapi/data_account_vins_list/main.tf diff --git a/samples/data_bservice/main.tf b/samples/cloudapi/data_bservice/main.tf similarity index 100% rename from samples/data_bservice/main.tf rename to samples/cloudapi/data_bservice/main.tf diff --git a/samples/data_bservice_deleted_list/main.tf b/samples/cloudapi/data_bservice_deleted_list/main.tf similarity index 100% rename from samples/data_bservice_deleted_list/main.tf rename to samples/cloudapi/data_bservice_deleted_list/main.tf diff --git a/samples/data_bservice_group/main.tf b/samples/cloudapi/data_bservice_group/main.tf similarity index 100% rename from samples/data_bservice_group/main.tf rename to samples/cloudapi/data_bservice_group/main.tf diff --git a/samples/data_bservice_list/main.tf b/samples/cloudapi/data_bservice_list/main.tf similarity index 100% rename from samples/data_bservice_list/main.tf rename to samples/cloudapi/data_bservice_list/main.tf diff --git a/samples/data_bservice_snapshot_list/main.tf b/samples/cloudapi/data_bservice_snapshot_list/main.tf similarity index 100% rename from samples/data_bservice_snapshot_list/main.tf rename to samples/cloudapi/data_bservice_snapshot_list/main.tf diff --git a/samples/data_disk_list/main.tf b/samples/cloudapi/data_disk_list/main.tf similarity index 100% rename from samples/data_disk_list/main.tf rename to samples/cloudapi/data_disk_list/main.tf diff --git a/samples/data_extnet/main.tf b/samples/cloudapi/data_extnet/main.tf similarity index 100% rename from samples/data_extnet/main.tf rename to samples/cloudapi/data_extnet/main.tf diff --git a/samples/data_extnet_computes_list/main.tf b/samples/cloudapi/data_extnet_computes_list/main.tf similarity index 100% rename from samples/data_extnet_computes_list/main.tf rename to samples/cloudapi/data_extnet_computes_list/main.tf diff --git a/samples/data_extnet_default/main.tf b/samples/cloudapi/data_extnet_default/main.tf similarity index 100% rename from samples/data_extnet_default/main.tf rename to samples/cloudapi/data_extnet_default/main.tf diff --git a/samples/data_extnet_list/main.tf b/samples/cloudapi/data_extnet_list/main.tf similarity index 100% rename from samples/data_extnet_list/main.tf rename to samples/cloudapi/data_extnet_list/main.tf diff --git a/samples/cloudapi/data_location_url/main.tf b/samples/cloudapi/data_location_url/main.tf new file mode 100644 index 0000000..e69de29 diff --git a/samples/cloudapi/data_locations_list/main.tf b/samples/cloudapi/data_locations_list/main.tf new file mode 100644 index 0000000..45c1fca --- /dev/null +++ b/samples/cloudapi/data_locations_list/main.tf @@ -0,0 +1,45 @@ +/* +Пример использования +Получение информации о доступных локациях +Ресурс позволяет: +Используется для получения информации о grid_id для создания ресурсов +*/ +#Расскомментируйте этот код, +#и внесите необходимые правки в версию и путь, +#чтобы работать с установленным вручную (не через hashicorp provider registry) провайдером + +/* +terraform { + required_providers { + decort = { + version = "1.1" + source = "digitalenergy.online/decort/decort" + } + } +} +*/ + +provider "decort" { + authenticator = "oauth2" + #controller_url = + controller_url = "https://ds1.digitalenergy.online" + #oauth2_url = + oauth2_url = "https://sso.digitalenergy.online" + allow_unverified_ssl = true +} + +data "decort_locations_list" "ll" { + #кол-во страниц для вывода + #опицональный параметр + #тип - число + #page = 1 + + #размер страницы + #опицональный параметр + #тип - число + #size = 1 +} + +output "test" { + value = data.decort_locations_list.ll +} diff --git a/samples/data_rg_list/main.tf b/samples/cloudapi/data_rg_list/main.tf similarity index 100% rename from samples/data_rg_list/main.tf rename to samples/cloudapi/data_rg_list/main.tf diff --git a/samples/data_snapshot_list/main.tf b/samples/cloudapi/data_snapshot_list/main.tf similarity index 100% rename from samples/data_snapshot_list/main.tf rename to samples/cloudapi/data_snapshot_list/main.tf diff --git a/samples/data_vgpu/main.tf b/samples/cloudapi/data_vgpu/main.tf similarity index 100% rename from samples/data_vgpu/main.tf rename to samples/cloudapi/data_vgpu/main.tf diff --git a/samples/data_vins_list/main.tf b/samples/cloudapi/data_vins_list/main.tf similarity index 100% rename from samples/data_vins_list/main.tf rename to samples/cloudapi/data_vins_list/main.tf diff --git a/samples/resource_account/main.tf b/samples/cloudapi/resource_account/main.tf similarity index 100% rename from samples/resource_account/main.tf rename to samples/cloudapi/resource_account/main.tf diff --git a/samples/resource_bservice/main.tf b/samples/cloudapi/resource_bservice/main.tf similarity index 100% rename from samples/resource_bservice/main.tf rename to samples/cloudapi/resource_bservice/main.tf diff --git a/samples/resource_bservice_group/main.tf b/samples/cloudapi/resource_bservice_group/main.tf similarity index 100% rename from samples/resource_bservice_group/main.tf rename to samples/cloudapi/resource_bservice_group/main.tf diff --git a/samples/resource_k8s/main.tf b/samples/cloudapi/resource_k8s/main.tf similarity index 100% rename from samples/resource_k8s/main.tf rename to samples/cloudapi/resource_k8s/main.tf diff --git a/samples/resource_k8s_wg/main.tf b/samples/cloudapi/resource_k8s_wg/main.tf similarity index 100% rename from samples/resource_k8s_wg/main.tf rename to samples/cloudapi/resource_k8s_wg/main.tf diff --git a/samples/resource_snapshot/main.tf b/samples/cloudapi/resource_snapshot/main.tf similarity index 100% rename from samples/resource_snapshot/main.tf rename to samples/cloudapi/resource_snapshot/main.tf diff --git a/samples/data_grid/main.tf b/samples/cloudbroker/data_grid/main.tf similarity index 100% rename from samples/data_grid/main.tf rename to samples/cloudbroker/data_grid/main.tf diff --git a/samples/data_grid_list/main.tf b/samples/cloudbroker/data_grid_list/main.tf similarity index 100% rename from samples/data_grid_list/main.tf rename to samples/cloudbroker/data_grid_list/main.tf diff --git a/samples/data_image/main.tf b/samples/cloudbroker/data_image/main.tf similarity index 100% rename from samples/data_image/main.tf rename to samples/cloudbroker/data_image/main.tf diff --git a/samples/data_image_list/main.tf b/samples/cloudbroker/data_image_list/main.tf similarity index 100% rename from samples/data_image_list/main.tf rename to samples/cloudbroker/data_image_list/main.tf diff --git a/samples/data_image_list_stacks/main.tf b/samples/cloudbroker/data_image_list_stacks/main.tf similarity index 100% rename from samples/data_image_list_stacks/main.tf rename to samples/cloudbroker/data_image_list_stacks/main.tf diff --git a/samples/data_pcidevice/main.tf b/samples/cloudbroker/data_pcidevice/main.tf similarity index 100% rename from samples/data_pcidevice/main.tf rename to samples/cloudbroker/data_pcidevice/main.tf diff --git a/samples/data_pcidevice_list/main.tf b/samples/cloudbroker/data_pcidevice_list/main.tf similarity index 100% rename from samples/data_pcidevice_list/main.tf rename to samples/cloudbroker/data_pcidevice_list/main.tf diff --git a/samples/data_sep/main.tf b/samples/cloudbroker/data_sep/main.tf similarity index 100% rename from samples/data_sep/main.tf rename to samples/cloudbroker/data_sep/main.tf diff --git a/samples/data_sep_config/main.tf b/samples/cloudbroker/data_sep_config/main.tf similarity index 100% rename from samples/data_sep_config/main.tf rename to samples/cloudbroker/data_sep_config/main.tf diff --git a/samples/data_sep_consumption/main.tf b/samples/cloudbroker/data_sep_consumption/main.tf similarity index 100% rename from samples/data_sep_consumption/main.tf rename to samples/cloudbroker/data_sep_consumption/main.tf diff --git a/samples/data_sep_disk_list/main.tf b/samples/cloudbroker/data_sep_disk_list/main.tf similarity index 100% rename from samples/data_sep_disk_list/main.tf rename to samples/cloudbroker/data_sep_disk_list/main.tf diff --git a/samples/data_sep_list/main.tf b/samples/cloudbroker/data_sep_list/main.tf similarity index 100% rename from samples/data_sep_list/main.tf rename to samples/cloudbroker/data_sep_list/main.tf diff --git a/samples/data_sep_pool/main.tf b/samples/cloudbroker/data_sep_pool/main.tf similarity index 100% rename from samples/data_sep_pool/main.tf rename to samples/cloudbroker/data_sep_pool/main.tf diff --git a/samples/resource_delete_images/main.tf b/samples/cloudbroker/resource_delete_images/main.tf similarity index 100% rename from samples/resource_delete_images/main.tf rename to samples/cloudbroker/resource_delete_images/main.tf diff --git a/samples/resource_image/main.tf b/samples/cloudbroker/resource_image/main.tf similarity index 100% rename from samples/resource_image/main.tf rename to samples/cloudbroker/resource_image/main.tf diff --git a/samples/resource_image_cdrom/main.tf b/samples/cloudbroker/resource_image_cdrom/main.tf similarity index 100% rename from samples/resource_image_cdrom/main.tf rename to samples/cloudbroker/resource_image_cdrom/main.tf diff --git a/samples/resource_pcidevice/main.tf b/samples/cloudbroker/resource_pcidevice/main.tf similarity index 100% rename from samples/resource_pcidevice/main.tf rename to samples/cloudbroker/resource_pcidevice/main.tf diff --git a/samples/resource_sep/main.tf b/samples/cloudbroker/resource_sep/main.tf similarity index 100% rename from samples/resource_sep/main.tf rename to samples/cloudbroker/resource_sep/main.tf diff --git a/samples/resource_sep_config/main.tf b/samples/cloudbroker/resource_sep_config/main.tf similarity index 100% rename from samples/resource_sep_config/main.tf rename to samples/cloudbroker/resource_sep_config/main.tf diff --git a/samples/resource_virtual_image/main.tf b/samples/cloudbroker/resource_virtual_image/main.tf similarity index 100% rename from samples/resource_virtual_image/main.tf rename to samples/cloudbroker/resource_virtual_image/main.tf From c422910bbec8daa5185b03168ecdc68f9b82b790 Mon Sep 17 00:00:00 2001 From: stSolo Date: Fri, 8 Jul 2022 15:08:52 +0300 Subject: [PATCH 39/51] Add env flag DECORT_ADMIN_MODE --- Makefile | 2 +- .../{ => cloudapi}/data_sources_map.go | 20 +------ .../provider/{ => cloudapi}/resource_map.go | 17 ++---- .../provider/cloudbroker/data_sources_map.go | 50 +++++++++++++++++ .../provider/cloudbroker/resources_map.go | 39 +++++++++++++ internal/provider/provider.go | 4 +- internal/provider/select_schema.go | 55 +++++++++++++++++++ 7 files changed, 152 insertions(+), 35 deletions(-) rename internal/provider/{ => cloudapi}/data_sources_map.go (74%) rename internal/provider/{ => cloudapi}/resource_map.go (73%) create mode 100644 internal/provider/cloudbroker/data_sources_map.go create mode 100644 internal/provider/cloudbroker/resources_map.go create mode 100644 internal/provider/select_schema.go diff --git a/Makefile b/Makefile index abc8d7e..459f7fc 100644 --- a/Makefile +++ b/Makefile @@ -5,7 +5,7 @@ NAME=terraform-provider-decort #BINARY=terraform-provider-${NAME} BINARY=${NAME}.exe MAINPATH = ./cmd/decort/ -VERSION=0.2 +VERSION=1.1 #OS_ARCH=darwin_amd64 OS_ARCH=windows_amd64 diff --git a/internal/provider/data_sources_map.go b/internal/provider/cloudapi/data_sources_map.go similarity index 74% rename from internal/provider/data_sources_map.go rename to internal/provider/cloudapi/data_sources_map.go index 5897525..cd9217b 100644 --- a/internal/provider/data_sources_map.go +++ b/internal/provider/cloudapi/data_sources_map.go @@ -17,7 +17,7 @@ See the License for the specific language governing permissions and limitations under the License. */ -package provider +package cloudapi import ( "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" @@ -31,10 +31,6 @@ import ( "github.com/rudecs/terraform-provider-decort/internal/service/cloudapi/snapshot" "github.com/rudecs/terraform-provider-decort/internal/service/cloudapi/vgpu" "github.com/rudecs/terraform-provider-decort/internal/service/cloudapi/vins" - "github.com/rudecs/terraform-provider-decort/internal/service/cloudbroker/grid" - "github.com/rudecs/terraform-provider-decort/internal/service/cloudbroker/image" - "github.com/rudecs/terraform-provider-decort/internal/service/cloudbroker/pcidevice" - "github.com/rudecs/terraform-provider-decort/internal/service/cloudbroker/sep" ) func NewDataSourcesMap() map[string]*schema.Resource { @@ -42,23 +38,9 @@ func NewDataSourcesMap() map[string]*schema.Resource { "decort_account": account.DataSourceAccount(), "decort_resgroup": rg.DataSourceResgroup(), "decort_kvmvm": kvmvm.DataSourceCompute(), - "decort_image": image.DataSourceImage(), - "decort_disk": disks.DataSourceDisk(), "decort_vins": vins.DataSourceVins(), - "decort_grid": grid.DataSourceGrid(), - "decort_grid_list": grid.DataSourceGridList(), - "decort_image_list": image.DataSourceImageList(), - "decort_image_list_stacks": image.DataSourceImageListStacks(), "decort_snapshot_list": snapshot.DataSourceSnapshotList(), "decort_vgpu": vgpu.DataSourceVGPU(), - "decort_pcidevice": pcidevice.DataSourcePcidevice(), - "decort_pcidevice_list": pcidevice.DataSourcePcideviceList(), - "decort_sep_list": sep.DataSourceSepList(), - "decort_sep": sep.DataSourceSep(), - "decort_sep_consumption": sep.DataSourceSepConsumption(), - "decort_sep_disk_list": sep.DataSourceSepDiskList(), - "decort_sep_config": sep.DataSourceSepConfig(), - "decort_sep_pool": sep.DataSourceSepPool(), "decort_disk_list": disks.DataSourceDiskList(), "decort_rg_list": rg.DataSourceRgList(), "decort_account_list": account.DataSourceAccountList(), diff --git a/internal/provider/resource_map.go b/internal/provider/cloudapi/resource_map.go similarity index 73% rename from internal/provider/resource_map.go rename to internal/provider/cloudapi/resource_map.go index 1c03347..fd5c27b 100644 --- a/internal/provider/resource_map.go +++ b/internal/provider/cloudapi/resource_map.go @@ -17,7 +17,7 @@ See the License for the specific language governing permissions and limitations under the License. */ -package provider +package cloudapi import ( "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" @@ -25,32 +25,23 @@ import ( "github.com/rudecs/terraform-provider-decort/internal/service/cloudapi/bservice" "github.com/rudecs/terraform-provider-decort/internal/service/cloudapi/disks" "github.com/rudecs/terraform-provider-decort/internal/service/cloudapi/k8s" + "github.com/rudecs/terraform-provider-decort/internal/service/cloudapi/kvmvm" "github.com/rudecs/terraform-provider-decort/internal/service/cloudapi/pfw" "github.com/rudecs/terraform-provider-decort/internal/service/cloudapi/rg" "github.com/rudecs/terraform-provider-decort/internal/service/cloudapi/snapshot" "github.com/rudecs/terraform-provider-decort/internal/service/cloudapi/vins" - "github.com/rudecs/terraform-provider-decort/internal/service/cloudbroker/image" - "github.com/rudecs/terraform-provider-decort/internal/service/cloudbroker/pcidevice" - "github.com/rudecs/terraform-provider-decort/internal/service/cloudbroker/sep" ) func NewRersourcesMap() map[string]*schema.Resource { return map[string]*schema.Resource{ - "decort_resgroup": rg.ResourceResgroup(), - // "decort_kvmvm": resourceCompute(), + "decort_resgroup": rg.ResourceResgroup(), + "decort_kvmvm": kvmvm.ResourceCompute(), "decort_disk": disks.ResourceDisk(), "decort_vins": vins.ResourceVins(), "decort_pfw": pfw.ResourcePfw(), "decort_k8s": k8s.ResourceK8s(), "decort_k8s_wg": k8s.ResourceK8sWg(), - "decort_image": image.ResourceImage(), - "decort_virtual_image": image.ResourceVirtualImage(), - "decort_cdrom_image": image.ResourceCDROMImage(), - "decort_delete_images": image.ResourceDeleteImages(), "decort_snapshot": snapshot.ResourceSnapshot(), - "decort_pcidevice": pcidevice.ResourcePcidevice(), - "decort_sep": sep.ResourceSep(), - "decort_sep_config": sep.ResourceSepConfig(), "decort_account": account.ResourceAccount(), "decort_bservice": bservice.ResourceBasicService(), "decort_bservice_group": bservice.ResourceBasicServiceGroup(), diff --git a/internal/provider/cloudbroker/data_sources_map.go b/internal/provider/cloudbroker/data_sources_map.go new file mode 100644 index 0000000..fb633f8 --- /dev/null +++ b/internal/provider/cloudbroker/data_sources_map.go @@ -0,0 +1,50 @@ +/* +Copyright (c) 2019-2022 Digital Energy Cloud Solutions LLC. All Rights Reserved. +Authors: +Petr Krutov, +Stanislav Solovev, + +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. +*/ + +package cloudbroker + +import ( + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" + "github.com/rudecs/terraform-provider-decort/internal/service/cloudapi/disks" + "github.com/rudecs/terraform-provider-decort/internal/service/cloudbroker/grid" + "github.com/rudecs/terraform-provider-decort/internal/service/cloudbroker/image" + "github.com/rudecs/terraform-provider-decort/internal/service/cloudbroker/pcidevice" + "github.com/rudecs/terraform-provider-decort/internal/service/cloudbroker/sep" +) + +func NewDataSourcesMap() map[string]*schema.Resource { + return map[string]*schema.Resource{ + "decort_image": image.DataSourceImage(), + "decort_disk": disks.DataSourceDisk(), + "decort_grid": grid.DataSourceGrid(), + "decort_grid_list": grid.DataSourceGridList(), + "decort_image_list": image.DataSourceImageList(), + "decort_image_list_stacks": image.DataSourceImageListStacks(), + "decort_pcidevice": pcidevice.DataSourcePcidevice(), + "decort_pcidevice_list": pcidevice.DataSourcePcideviceList(), + "decort_sep_list": sep.DataSourceSepList(), + "decort_sep": sep.DataSourceSep(), + "decort_sep_consumption": sep.DataSourceSepConsumption(), + "decort_sep_disk_list": sep.DataSourceSepDiskList(), + "decort_sep_config": sep.DataSourceSepConfig(), + "decort_sep_pool": sep.DataSourceSepPool(), + // "decort_pfw": dataSourcePfw(), + } + +} diff --git a/internal/provider/cloudbroker/resources_map.go b/internal/provider/cloudbroker/resources_map.go new file mode 100644 index 0000000..49ead88 --- /dev/null +++ b/internal/provider/cloudbroker/resources_map.go @@ -0,0 +1,39 @@ +/* +Copyright (c) 2019-2022 Digital Energy Cloud Solutions LLC. All Rights Reserved. +Authors: +Petr Krutov, +Stanislav Solovev, + +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. +*/ + +package cloudbroker + +import ( + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" + "github.com/rudecs/terraform-provider-decort/internal/service/cloudbroker/image" + "github.com/rudecs/terraform-provider-decort/internal/service/cloudbroker/pcidevice" + "github.com/rudecs/terraform-provider-decort/internal/service/cloudbroker/sep" +) + +func NewRersourcesMap() map[string]*schema.Resource { + return map[string]*schema.Resource{ + "decort_image": image.ResourceImage(), + "decort_virtual_image": image.ResourceVirtualImage(), + "decort_cdrom_image": image.ResourceCDROMImage(), + "decort_delete_images": image.ResourceDeleteImages(), + "decort_pcidevice": pcidevice.ResourcePcidevice(), + "decort_sep": sep.ResourceSep(), + "decort_sep_config": sep.ResourceSepConfig(), + } +} diff --git a/internal/provider/provider.go b/internal/provider/provider.go index 39fe2c3..f004704 100644 --- a/internal/provider/provider.go +++ b/internal/provider/provider.go @@ -101,9 +101,9 @@ func Provider() *schema.Provider { }, }, - ResourcesMap: NewRersourcesMap(), + ResourcesMap: selectSchema(false), - DataSourcesMap: NewDataSourcesMap(), + DataSourcesMap: selectSchema(true), ConfigureFunc: providerConfigure, } diff --git a/internal/provider/select_schema.go b/internal/provider/select_schema.go new file mode 100644 index 0000000..ce70df9 --- /dev/null +++ b/internal/provider/select_schema.go @@ -0,0 +1,55 @@ +/* +Copyright (c) 2019-2022 Digital Energy Cloud Solutions LLC. All Rights Reserved. +Authors: +Petr Krutov, +Stanislav Solovev, + +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. +*/ + +package provider + +import ( + "os" + "strconv" + + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" + ca "github.com/rudecs/terraform-provider-decort/internal/provider/cloudapi" + cb "github.com/rudecs/terraform-provider-decort/internal/provider/cloudbroker" +) + +func selectSchema(isDatasource bool) map[string]*schema.Resource { + adminMode, err := strconv.ParseBool(os.Getenv("DECORT_ADMIN_MODE")) + if err != nil { + adminMode = false + } + if isDatasource { + return selectDataSourceSchema(adminMode) + } + return selectResourceSchema(adminMode) + +} + +func selectDataSourceSchema(adminMode bool) map[string]*schema.Resource { + if adminMode { + return cb.NewDataSourcesMap() + } + return ca.NewDataSourcesMap() +} + +func selectResourceSchema(adminMode bool) map[string]*schema.Resource { + if adminMode { + return cb.NewRersourcesMap() + } + return ca.NewRersourcesMap() +} From fc32db30b62c68c81689ffa1aae2ded467141f25 Mon Sep 17 00:00:00 2001 From: stSolo Date: Fri, 8 Jul 2022 15:35:43 +0300 Subject: [PATCH 40/51] Add patch for compute sep_id and pool --- .../cloudapi/kvmvm/data_source_compute.go | 36 ++++++++++++++----- .../cloudapi/kvmvm/resource_compute.go | 28 +++++++++++++-- 2 files changed, 54 insertions(+), 10 deletions(-) diff --git a/internal/service/cloudapi/kvmvm/data_source_compute.go b/internal/service/cloudapi/kvmvm/data_source_compute.go index 2ad51d1..a852eeb 100644 --- a/internal/service/cloudapi/kvmvm/data_source_compute.go +++ b/internal/service/cloudapi/kvmvm/data_source_compute.go @@ -34,6 +34,7 @@ package kvmvm import ( "context" "encoding/json" + "errors" "fmt" // "net/url" @@ -43,6 +44,7 @@ import ( "github.com/hashicorp/terraform-plugin-sdk/v2/diag" "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" + // "github.com/hashicorp/terraform-plugin-sdk/helper/validation" ) // Parse list of all disks from API compute/get into a list of "extra disks" attached to this compute @@ -105,6 +107,16 @@ func parseBootDiskId(disks []DiskRecord) uint { return 0 } +func findBootDisk(disks []DiskRecord) (*DiskRecord, error) { + for _, d := range disks { + if d.Type == "B" { + return &d, nil + } + } + + return nil, errors.New("boot disk not found") +} + // Parse the list of interfaces from compute/get response into a list of networks // attached to this compute func parseComputeInterfacesToNetworks(ifaces []InterfaceRecord) []interface{} { @@ -131,7 +143,7 @@ func parseComputeInterfacesToNetworks(ifaces []InterfaceRecord) []interface{} { return result } -func flattenCompute(d *schema.ResourceData, compFacts string) error { +func flattenCompute(d *schema.ResourceData, compFacts string) diag.Diagnostics { // This function expects that compFacts string contains response from API compute/get, // i.e. detailed information about compute instance. // @@ -141,7 +153,7 @@ func flattenCompute(d *schema.ResourceData, compFacts string) error { log.Debugf("flattenCompute: ready to unmarshal string %s", compFacts) err := json.Unmarshal([]byte(compFacts), &model) if err != nil { - return err + return diag.FromErr(err) } log.Debugf("flattenCompute: ID %d, RG ID %d", model.ID, model.RgID) @@ -157,8 +169,6 @@ func flattenCompute(d *schema.ResourceData, compFacts string) error { d.Set("cpu", model.Cpu) d.Set("ram", model.Ram) // d.Set("boot_disk_size", model.BootDiskSize) - bootdiskSize key in API compute/get is always zero, so we set boot_disk_size in another way - d.Set("boot_disk_size", parseBootDiskSize(model.Disks)) - d.Set("boot_disk_id", parseBootDiskId(model.Disks)) // we may need boot disk ID in resize operations d.Set("image_id", model.ImageID) d.Set("description", model.Desc) d.Set("cloud_init", "applied") // NOTE: for existing compute we hard-code this value as an indicator for DiffSuppress fucntion @@ -171,24 +181,34 @@ func flattenCompute(d *schema.ResourceData, compFacts string) error { d.Set("started", false) } + bootDisk, err := findBootDisk(model.Disks) + if err != nil { + return diag.FromErr(err) + } + + d.Set("boot_disk_size", bootDisk.SizeMax) + d.Set("boot_disk_id", bootDisk.ID) // we may need boot disk ID in resize operations + d.Set("sep_id", bootDisk.SepID) + d.Set("pool", bootDisk.Pool) + if len(model.Disks) > 0 { log.Debugf("flattenCompute: calling parseComputeDisksToExtraDisks for %d disks", len(model.Disks)) if err = d.Set("extra_disks", parseComputeDisksToExtraDisks(model.Disks)); err != nil { - return err + return diag.FromErr(err) } } if len(model.Interfaces) > 0 { log.Debugf("flattenCompute: calling parseComputeInterfacesToNetworks for %d interfaces", len(model.Interfaces)) if err = d.Set("network", parseComputeInterfacesToNetworks(model.Interfaces)); err != nil { - return err + return diag.FromErr(err) } } if len(model.OsUsers) > 0 { log.Debugf("flattenCompute: calling parseOsUsers for %d logins", len(model.OsUsers)) if err = d.Set("os_users", parseOsUsers(model.OsUsers)); err != nil { - return err + return diag.FromErr(err) } } @@ -204,7 +224,7 @@ func dataSourceComputeRead(ctx context.Context, d *schema.ResourceData, m interf return diag.FromErr(err) } - return diag.FromErr(flattenCompute(d, compFacts)) + return flattenCompute(d, compFacts) } func DataSourceCompute() *schema.Resource { diff --git a/internal/service/cloudapi/kvmvm/resource_compute.go b/internal/service/cloudapi/kvmvm/resource_compute.go index 941c16d..f50dcf4 100644 --- a/internal/service/cloudapi/kvmvm/resource_compute.go +++ b/internal/service/cloudapi/kvmvm/resource_compute.go @@ -85,6 +85,14 @@ func resourceComputeCreate(ctx context.Context, d *schema.ResourceData, m interf urlValues.Add("desc", argVal.(string)) } + if sepID, ok := d.GetOk("sep_id"); ok { + urlValues.Add("sepId", strconv.Itoa(sepID.(int))) + } + + if pool, ok := d.GetOk("pool"); ok { + urlValues.Add("pool", pool.(string)) + } + /* sshKeysVal, sshKeysSet := d.GetOk("ssh_keys") if sshKeysSet { @@ -178,8 +186,8 @@ func resourceComputeRead(ctx context.Context, d *schema.ResourceData, m interfac return nil } - if err = flattenCompute(d, compFacts); err != nil { - return diag.FromErr(err) + if diagnostic := flattenCompute(d, compFacts); diagnostic != nil { + return diagnostic } log.Debugf("resourceComputeRead: after flattenCompute: Compute ID %s, name %q, RG ID %d", @@ -427,6 +435,22 @@ func ResourceCompute() *schema.Resource { Description: "This compute instance boot disk size in GB. Make sure it is large enough to accomodate selected OS image.", }, + "sep_id": { + Type: schema.TypeInt, + Optional: true, + Computed: true, + ForceNew: true, + Description: "ID of SEP to create bootDisk on. Uses image's sepId if not set.", + }, + + "pool": { + Type: schema.TypeString, + Optional: true, + Computed: true, + ForceNew: true, + Description: "Pool to use if sepId is set, can be also empty if needed to be chosen by system.", + }, + "extra_disks": { Type: schema.TypeSet, Optional: true, From 5b4c1f4324f4fdde7747b2654dd87ed8c2f5cb55 Mon Sep 17 00:00:00 2001 From: stSolo Date: Fri, 8 Jul 2022 15:47:09 +0300 Subject: [PATCH 41/51] Add patch for compute sep_id and pool --- .../cloudapi/kvmvm/data_source_compute.go | 18 +++++++++++------- .../service/cloudapi/kvmvm/resource_compute.go | 4 ++-- 2 files changed, 13 insertions(+), 9 deletions(-) diff --git a/internal/service/cloudapi/kvmvm/data_source_compute.go b/internal/service/cloudapi/kvmvm/data_source_compute.go index a852eeb..4622b2b 100644 --- a/internal/service/cloudapi/kvmvm/data_source_compute.go +++ b/internal/service/cloudapi/kvmvm/data_source_compute.go @@ -143,7 +143,7 @@ func parseComputeInterfacesToNetworks(ifaces []InterfaceRecord) []interface{} { return result } -func flattenCompute(d *schema.ResourceData, compFacts string) diag.Diagnostics { +func flattenCompute(d *schema.ResourceData, compFacts string) error { // This function expects that compFacts string contains response from API compute/get, // i.e. detailed information about compute instance. // @@ -153,7 +153,7 @@ func flattenCompute(d *schema.ResourceData, compFacts string) diag.Diagnostics { log.Debugf("flattenCompute: ready to unmarshal string %s", compFacts) err := json.Unmarshal([]byte(compFacts), &model) if err != nil { - return diag.FromErr(err) + return err } log.Debugf("flattenCompute: ID %d, RG ID %d", model.ID, model.RgID) @@ -183,7 +183,7 @@ func flattenCompute(d *schema.ResourceData, compFacts string) diag.Diagnostics { bootDisk, err := findBootDisk(model.Disks) if err != nil { - return diag.FromErr(err) + return err } d.Set("boot_disk_size", bootDisk.SizeMax) @@ -194,21 +194,21 @@ func flattenCompute(d *schema.ResourceData, compFacts string) diag.Diagnostics { if len(model.Disks) > 0 { log.Debugf("flattenCompute: calling parseComputeDisksToExtraDisks for %d disks", len(model.Disks)) if err = d.Set("extra_disks", parseComputeDisksToExtraDisks(model.Disks)); err != nil { - return diag.FromErr(err) + return err } } if len(model.Interfaces) > 0 { log.Debugf("flattenCompute: calling parseComputeInterfacesToNetworks for %d interfaces", len(model.Interfaces)) if err = d.Set("network", parseComputeInterfacesToNetworks(model.Interfaces)); err != nil { - return diag.FromErr(err) + return err } } if len(model.OsUsers) > 0 { log.Debugf("flattenCompute: calling parseOsUsers for %d logins", len(model.OsUsers)) if err = d.Set("os_users", parseOsUsers(model.OsUsers)); err != nil { - return diag.FromErr(err) + return err } } @@ -224,7 +224,11 @@ func dataSourceComputeRead(ctx context.Context, d *schema.ResourceData, m interf return diag.FromErr(err) } - return flattenCompute(d, compFacts) + if err = flattenCompute(d, compFacts); err != nil { + return diag.FromErr(err) + } + + return nil } func DataSourceCompute() *schema.Resource { diff --git a/internal/service/cloudapi/kvmvm/resource_compute.go b/internal/service/cloudapi/kvmvm/resource_compute.go index f50dcf4..2d6c2a3 100644 --- a/internal/service/cloudapi/kvmvm/resource_compute.go +++ b/internal/service/cloudapi/kvmvm/resource_compute.go @@ -186,8 +186,8 @@ func resourceComputeRead(ctx context.Context, d *schema.ResourceData, m interfac return nil } - if diagnostic := flattenCompute(d, compFacts); diagnostic != nil { - return diagnostic + if err = flattenCompute(d, compFacts); err != nil { + return diag.FromErr(err) } log.Debugf("resourceComputeRead: after flattenCompute: Compute ID %s, name %q, RG ID %d", From 0bdd7c3c329464d9108444b1636ae0ddd76d7fb4 Mon Sep 17 00:00:00 2001 From: kjubybot Date: Wed, 20 Jul 2022 11:28:00 +0300 Subject: [PATCH 42/51] fixed boot disk reading for computes without one --- .../service/cloudapi/kvmvm/data_source_compute.go | 13 +++++-------- 1 file changed, 5 insertions(+), 8 deletions(-) diff --git a/internal/service/cloudapi/kvmvm/data_source_compute.go b/internal/service/cloudapi/kvmvm/data_source_compute.go index 4622b2b..652191c 100644 --- a/internal/service/cloudapi/kvmvm/data_source_compute.go +++ b/internal/service/cloudapi/kvmvm/data_source_compute.go @@ -34,7 +34,6 @@ package kvmvm import ( "context" "encoding/json" - "errors" "fmt" // "net/url" @@ -107,14 +106,15 @@ func parseBootDiskId(disks []DiskRecord) uint { return 0 } -func findBootDisk(disks []DiskRecord) (*DiskRecord, error) { +func findBootDisk(disks []DiskRecord) *DiskRecord { for _, d := range disks { if d.Type == "B" { - return &d, nil + return &d } } - return nil, errors.New("boot disk not found") + // some computes don't have a boot disk, so... + return &DiskRecord{} } // Parse the list of interfaces from compute/get response into a list of networks @@ -181,10 +181,7 @@ func flattenCompute(d *schema.ResourceData, compFacts string) error { d.Set("started", false) } - bootDisk, err := findBootDisk(model.Disks) - if err != nil { - return err - } + bootDisk := findBootDisk(model.Disks) d.Set("boot_disk_size", bootDisk.SizeMax) d.Set("boot_disk_id", bootDisk.ID) // we may need boot disk ID in resize operations From 28ceebecf8bcd0bfa8257d0883ecc5dfb19ce6e8 Mon Sep 17 00:00:00 2001 From: stSolo Date: Wed, 20 Jul 2022 17:14:00 +0300 Subject: [PATCH 43/51] Add files --- README.md | 10 +- README_EN.md | 11 +- internal/controller/controller.go | 3 + .../provider/cloudapi/data_sources_map.go | 4 + internal/provider/cloudapi/resource_map.go | 3 + .../provider/cloudbroker/data_sources_map.go | 41 +- .../provider/cloudbroker/resources_map.go | 17 + internal/provider/provider.go | 13 +- .../account/data_source_account_list.go | 151 ----- .../cloudapi/account/resource_account.go | 55 +- .../cloudapi/bservice/resource_bservice.go | 22 - .../bservice/resource_bservice_group.go | 24 - internal/service/cloudapi/disks/api.go | 14 +- .../cloudapi/disks/data_source_disk.go | 420 ++++++++---- .../cloudapi/disks/data_source_disk_list.go | 96 ++- internal/service/cloudapi/disks/models.go | 28 +- .../service/cloudapi/disks/resource_disk.go | 608 ++++++++++++----- .../service/cloudapi/disks/utility_disk.go | 100 +-- .../cloudapi/disks/utility_disk_list.go | 8 +- internal/service/cloudapi/image/api.go | 40 ++ .../cloudapi/image/data_source_image.go | 123 ++++ .../cloudapi/image/data_source_image_list.go | 126 ++++ .../cloudapi/image/image_ds_subresource.go | 208 ++++++ .../cloudapi/image/image_item_subresource.go | 132 ++++ .../cloudapi/image/image_rs_subresource.go | 158 +++++ .../image/image_virtual_rs_subresource.go | 66 ++ internal/service/cloudapi/image/models.go | 148 ++++ .../service/cloudapi/image/resource_image.go | 259 +++++++ .../cloudapi/image/resource_image_virtual.go | 132 ++++ .../service/cloudapi/image/utility_image.go | 75 ++ .../cloudapi/image/utility_image_list.go | 74 ++ .../account/account_audit_ds_subresource.go | 59 ++ .../account/account_compute_ds_subresource.go | 119 ++++ .../account/account_disk_ds_subresource.go | 63 ++ .../service/cloudbroker/account/account_ds.go | 262 +++++++ .../account/account_fg_ds_subresource.go | 123 ++++ .../account/account_item_ds_subresource.go | 189 ++++++ .../account/account_rg_ds_subresource.go | 205 ++++++ .../service/cloudbroker/account/account_rs.go | 320 +++++++++ .../account/account_vins_ds_subresource.go | 107 +++ internal/service/cloudbroker/account/api.go | 54 ++ .../account/data_source_account.go | 108 +++ .../data_source_account_audits_list.go | 104 +++ .../data_source_account_computes_list.go | 119 ++++ .../data_source_account_deleted_list.go | 69 ++ .../account/data_source_account_disks_list.go | 104 +++ .../data_source_account_flipgroups_list.go | 120 ++++ .../account/data_source_account_list.go | 167 +++++ .../account/data_source_account_rg_list.go | 157 +++++ .../account/data_source_account_vins_list.go | 116 ++++ .../service/cloudbroker/account/models.go | 219 ++++++ .../cloudbroker/account/resource_account.go | 485 +++++++++++++ .../cloudbroker/account/utility_account.go | 69 ++ .../account/utility_account_audits_list.go | 65 ++ .../account/utility_account_computes_list.go | 65 ++ .../account/utility_account_deleted_list.go | 70 ++ .../account/utility_account_disks_list.go | 65 ++ .../account/utility_account_flip_groups.go | 65 ++ .../account/utility_account_list.go | 70 ++ .../account/utility_account_rg_list.go | 65 ++ .../account/utility_account_vins_list.go | 65 ++ internal/service/cloudbroker/disks/api.go | 41 ++ .../cloudbroker/disks/data_source_disk.go | 389 +++++++++++ .../disks/data_source_disk_list.go | 473 +++++++++++++ internal/service/cloudbroker/disks/models.go | 111 +++ .../cloudbroker/disks/resource_disk.go | 638 ++++++++++++++++++ .../service/cloudbroker/disks/utility_disk.go | 70 ++ .../cloudbroker/disks/utility_disk_list.go | 77 +++ internal/service/cloudbroker/k8s/api.go | 49 ++ internal/service/cloudbroker/k8s/models.go | 131 ++++ .../cloudbroker/k8s/node_subresource.go | 105 +++ .../service/cloudbroker/k8s/resource_k8s.go | 403 +++++++++++ .../cloudbroker/k8s/resource_k8s_wg.go | 258 +++++++ .../service/cloudbroker/k8s/utility_k8s.go | 63 ++ .../service/cloudbroker/k8s/utility_k8s_wg.go | 75 ++ internal/service/cloudbroker/kvmvm/api.go | 46 ++ .../cloudbroker/kvmvm/data_source_compute.go | 385 +++++++++++ internal/service/cloudbroker/kvmvm/models.go | 190 ++++++ .../cloudbroker/kvmvm/network_subresource.go | 154 +++++ .../cloudbroker/kvmvm/osusers_subresource.go | 86 +++ .../cloudbroker/kvmvm/resource_compute.go | 542 +++++++++++++++ .../cloudbroker/kvmvm/utility_compute.go | 310 +++++++++ .../pcidevice/resource_pcidevice.go | 16 - internal/service/cloudbroker/pfw/api.go | 36 + internal/service/cloudbroker/pfw/models.go | 45 ++ .../service/cloudbroker/pfw/resource_pfw.go | 211 ++++++ .../service/cloudbroker/pfw/utility_pfw.go | 77 +++ internal/service/cloudbroker/rg/api.go | 39 ++ .../service/cloudbroker/rg/data_source_rg.go | 196 ++++++ .../cloudbroker/rg/data_source_rg_list.go | 324 +++++++++ internal/service/cloudbroker/rg/models.go | 149 ++++ .../cloudbroker/rg/quota_subresource.go | 137 ++++ .../service/cloudbroker/rg/resource_rg.go | 442 ++++++++++++ internal/service/cloudbroker/rg/utility_rg.go | 139 ++++ .../service/cloudbroker/rg/utility_rg_list.go | 74 ++ .../service/cloudbroker/sep/resource_sep.go | 20 - internal/service/cloudbroker/snapshot/api.go | 37 + .../snapshot/data_source_snapshot_list.go | 131 ++++ .../service/cloudbroker/snapshot/models.go | 41 ++ .../cloudbroker/snapshot/resource_snapshot.go | 206 ++++++ .../cloudbroker/snapshot/utility_snapshot.go | 63 ++ .../snapshot/utility_snapshot_list.go | 65 ++ internal/service/cloudbroker/vins/api.go | 44 ++ .../cloudbroker/vins/data_source_vins.go | 181 +++++ .../cloudbroker/vins/data_source_vins_list.go | 189 ++++++ internal/service/cloudbroker/vins/models.go | 94 +++ .../service/cloudbroker/vins/resource_vins.go | 323 +++++++++ .../service/cloudbroker/vins/utility_vins.go | 153 +++++ .../cloudbroker/vins/utility_vins_list.go | 73 ++ samples/README.md | 146 ++-- samples/cloudapi/data_disk/main.tf | 35 + samples/cloudapi/data_image/main.tf | 43 ++ samples/cloudapi/data_image_list/main.tf | 52 ++ samples/cloudapi/resource_disk/main.tf | 56 ++ .../data_account_audits_list/main.tf | 40 ++ .../data_account_computes_list/main.tf | 39 ++ .../data_account_deleted_list/main.tf | 45 ++ .../data_account_disks_list/main.tf | 39 ++ .../data_account_flipgroups_list/main.tf | 38 ++ samples/cloudbroker/data_account_list/main.tf | 44 ++ .../cloudbroker/data_account_rg_list/main.tf | 37 + .../data_account_vins_list/main.tf | 39 ++ samples/cloudbroker/data_disk/main.tf | 35 + samples/cloudbroker/data_disk_list/main.tf | 54 ++ samples/cloudbroker/resource_disk/main.tf | 56 ++ 125 files changed, 15213 insertions(+), 723 deletions(-) create mode 100644 internal/service/cloudapi/image/api.go create mode 100644 internal/service/cloudapi/image/data_source_image.go create mode 100644 internal/service/cloudapi/image/data_source_image_list.go create mode 100644 internal/service/cloudapi/image/image_ds_subresource.go create mode 100644 internal/service/cloudapi/image/image_item_subresource.go create mode 100644 internal/service/cloudapi/image/image_rs_subresource.go create mode 100644 internal/service/cloudapi/image/image_virtual_rs_subresource.go create mode 100644 internal/service/cloudapi/image/models.go create mode 100644 internal/service/cloudapi/image/resource_image.go create mode 100644 internal/service/cloudapi/image/resource_image_virtual.go create mode 100644 internal/service/cloudapi/image/utility_image.go create mode 100644 internal/service/cloudapi/image/utility_image_list.go create mode 100644 internal/service/cloudbroker/account/account_audit_ds_subresource.go create mode 100644 internal/service/cloudbroker/account/account_compute_ds_subresource.go create mode 100644 internal/service/cloudbroker/account/account_disk_ds_subresource.go create mode 100644 internal/service/cloudbroker/account/account_ds.go create mode 100644 internal/service/cloudbroker/account/account_fg_ds_subresource.go create mode 100644 internal/service/cloudbroker/account/account_item_ds_subresource.go create mode 100644 internal/service/cloudbroker/account/account_rg_ds_subresource.go create mode 100644 internal/service/cloudbroker/account/account_rs.go create mode 100644 internal/service/cloudbroker/account/account_vins_ds_subresource.go create mode 100644 internal/service/cloudbroker/account/api.go create mode 100644 internal/service/cloudbroker/account/data_source_account.go create mode 100644 internal/service/cloudbroker/account/data_source_account_audits_list.go create mode 100644 internal/service/cloudbroker/account/data_source_account_computes_list.go create mode 100644 internal/service/cloudbroker/account/data_source_account_deleted_list.go create mode 100644 internal/service/cloudbroker/account/data_source_account_disks_list.go create mode 100644 internal/service/cloudbroker/account/data_source_account_flipgroups_list.go create mode 100644 internal/service/cloudbroker/account/data_source_account_list.go create mode 100644 internal/service/cloudbroker/account/data_source_account_rg_list.go create mode 100644 internal/service/cloudbroker/account/data_source_account_vins_list.go create mode 100644 internal/service/cloudbroker/account/models.go create mode 100644 internal/service/cloudbroker/account/resource_account.go create mode 100644 internal/service/cloudbroker/account/utility_account.go create mode 100644 internal/service/cloudbroker/account/utility_account_audits_list.go create mode 100644 internal/service/cloudbroker/account/utility_account_computes_list.go create mode 100644 internal/service/cloudbroker/account/utility_account_deleted_list.go create mode 100644 internal/service/cloudbroker/account/utility_account_disks_list.go create mode 100644 internal/service/cloudbroker/account/utility_account_flip_groups.go create mode 100644 internal/service/cloudbroker/account/utility_account_list.go create mode 100644 internal/service/cloudbroker/account/utility_account_rg_list.go create mode 100644 internal/service/cloudbroker/account/utility_account_vins_list.go create mode 100644 internal/service/cloudbroker/disks/api.go create mode 100644 internal/service/cloudbroker/disks/data_source_disk.go create mode 100644 internal/service/cloudbroker/disks/data_source_disk_list.go create mode 100644 internal/service/cloudbroker/disks/models.go create mode 100644 internal/service/cloudbroker/disks/resource_disk.go create mode 100644 internal/service/cloudbroker/disks/utility_disk.go create mode 100644 internal/service/cloudbroker/disks/utility_disk_list.go create mode 100644 internal/service/cloudbroker/k8s/api.go create mode 100644 internal/service/cloudbroker/k8s/models.go create mode 100644 internal/service/cloudbroker/k8s/node_subresource.go create mode 100644 internal/service/cloudbroker/k8s/resource_k8s.go create mode 100644 internal/service/cloudbroker/k8s/resource_k8s_wg.go create mode 100644 internal/service/cloudbroker/k8s/utility_k8s.go create mode 100644 internal/service/cloudbroker/k8s/utility_k8s_wg.go create mode 100644 internal/service/cloudbroker/kvmvm/api.go create mode 100644 internal/service/cloudbroker/kvmvm/data_source_compute.go create mode 100644 internal/service/cloudbroker/kvmvm/models.go create mode 100644 internal/service/cloudbroker/kvmvm/network_subresource.go create mode 100644 internal/service/cloudbroker/kvmvm/osusers_subresource.go create mode 100644 internal/service/cloudbroker/kvmvm/resource_compute.go create mode 100644 internal/service/cloudbroker/kvmvm/utility_compute.go create mode 100644 internal/service/cloudbroker/pfw/api.go create mode 100644 internal/service/cloudbroker/pfw/models.go create mode 100644 internal/service/cloudbroker/pfw/resource_pfw.go create mode 100644 internal/service/cloudbroker/pfw/utility_pfw.go create mode 100644 internal/service/cloudbroker/rg/api.go create mode 100644 internal/service/cloudbroker/rg/data_source_rg.go create mode 100644 internal/service/cloudbroker/rg/data_source_rg_list.go create mode 100644 internal/service/cloudbroker/rg/models.go create mode 100644 internal/service/cloudbroker/rg/quota_subresource.go create mode 100644 internal/service/cloudbroker/rg/resource_rg.go create mode 100644 internal/service/cloudbroker/rg/utility_rg.go create mode 100644 internal/service/cloudbroker/rg/utility_rg_list.go create mode 100644 internal/service/cloudbroker/snapshot/api.go create mode 100644 internal/service/cloudbroker/snapshot/data_source_snapshot_list.go create mode 100644 internal/service/cloudbroker/snapshot/models.go create mode 100644 internal/service/cloudbroker/snapshot/resource_snapshot.go create mode 100644 internal/service/cloudbroker/snapshot/utility_snapshot.go create mode 100644 internal/service/cloudbroker/snapshot/utility_snapshot_list.go create mode 100644 internal/service/cloudbroker/vins/api.go create mode 100644 internal/service/cloudbroker/vins/data_source_vins.go create mode 100644 internal/service/cloudbroker/vins/data_source_vins_list.go create mode 100644 internal/service/cloudbroker/vins/models.go create mode 100644 internal/service/cloudbroker/vins/resource_vins.go create mode 100644 internal/service/cloudbroker/vins/utility_vins.go create mode 100644 internal/service/cloudbroker/vins/utility_vins_list.go create mode 100644 samples/cloudapi/data_disk/main.tf create mode 100644 samples/cloudapi/data_image/main.tf create mode 100644 samples/cloudapi/data_image_list/main.tf create mode 100644 samples/cloudapi/resource_disk/main.tf create mode 100644 samples/cloudbroker/data_account_audits_list/main.tf create mode 100644 samples/cloudbroker/data_account_computes_list/main.tf create mode 100644 samples/cloudbroker/data_account_deleted_list/main.tf create mode 100644 samples/cloudbroker/data_account_disks_list/main.tf create mode 100644 samples/cloudbroker/data_account_flipgroups_list/main.tf create mode 100644 samples/cloudbroker/data_account_list/main.tf create mode 100644 samples/cloudbroker/data_account_rg_list/main.tf create mode 100644 samples/cloudbroker/data_account_vins_list/main.tf create mode 100644 samples/cloudbroker/data_disk/main.tf create mode 100644 samples/cloudbroker/data_disk_list/main.tf create mode 100644 samples/cloudbroker/resource_disk/main.tf diff --git a/README.md b/README.md index 566daaa..cbfa5b6 100644 --- a/README.md +++ b/README.md @@ -1,11 +1,19 @@ # terraform-provider-decort Terraform provider для платформы Digital Energy Cloud Orchestration Technology (DECORT) -Внимание: провайдер версии rc-1.25 разработан для DECORT API 3.7.x. +Внимание: провайдер версии 3.x разработан для DECORT API 3.8.x. Для более старых версий можно использовать: +- DECORT API 3.7.x - версия провайдера rc-1.25 - DECORT API 3.6.x - версия провайдера rc-1.10 - DECORT API до 3.6.0 - terraform DECS provider (https://github.com/rudecs/terraform-provider-decs) +## Режимы работы +Провайдер позволяет работать в двух режимах: +- Режим пользователя, +- Режим администратора. +Для переключения между режимами используйте флаг DECORT_ADMIN_MODE. +Вики проекта: https://github.com/rudecs/terraform-provider-decort/wiki + ## Возможности провайдера - Работа с Compute instances, - Работа с disks, diff --git a/README_EN.md b/README_EN.md index d942b38..4a23869 100644 --- a/README_EN.md +++ b/README_EN.md @@ -1,10 +1,19 @@ # terraform-provider-decort Terraform provider for Digital Energy Cloud Orchestration Technology (DECORT) platform -NOTE: provider rc-1.25 is designed for DECORT API 3.7.x. For older API versions please use: +NOTE: provider 3.x is designed for DECORT API 3.8.x. For older API versions please use: +- DECORT API 3.7.x versions - provider verion rc-1.25 - DECORT API 3.6.x versions - provider version rc-1.10 - DECORT API versions prior to 3.6.0 - Terraform DECS provider (https://github.com/rudecs/terraform-provider-decs) +## Working modes +The provider support two working modes: +- User mode, +- Administator mode. +Use flag DECORT_ADMIN_MODE for swithcing beetwen modes. +See user guide at https://github.com/rudecs/terraform-provider-decort/wiki + + ## Features - Work with Compute instances, - Work with disks, diff --git a/internal/controller/controller.go b/internal/controller/controller.go index ca9d3e3..a2024cd 100644 --- a/internal/controller/controller.go +++ b/internal/controller/controller.go @@ -362,6 +362,9 @@ func (config *ControllerCfg) DecortAPICall(ctx context.Context, method string, a if err != nil { return "", err } + + req = req.WithContext(ctx) + req.Header.Set("Content-Type", "application/x-www-form-urlencoded") req.Header.Set("Content-Length", strconv.Itoa(len(params_str))) req.Header.Set("Accept", "application/json") diff --git a/internal/provider/cloudapi/data_sources_map.go b/internal/provider/cloudapi/data_sources_map.go index cd9217b..e1103a1 100644 --- a/internal/provider/cloudapi/data_sources_map.go +++ b/internal/provider/cloudapi/data_sources_map.go @@ -25,6 +25,7 @@ import ( "github.com/rudecs/terraform-provider-decort/internal/service/cloudapi/bservice" "github.com/rudecs/terraform-provider-decort/internal/service/cloudapi/disks" "github.com/rudecs/terraform-provider-decort/internal/service/cloudapi/extnet" + "github.com/rudecs/terraform-provider-decort/internal/service/cloudapi/image" "github.com/rudecs/terraform-provider-decort/internal/service/cloudapi/kvmvm" "github.com/rudecs/terraform-provider-decort/internal/service/cloudapi/locations" "github.com/rudecs/terraform-provider-decort/internal/service/cloudapi/rg" @@ -41,6 +42,7 @@ func NewDataSourcesMap() map[string]*schema.Resource { "decort_vins": vins.DataSourceVins(), "decort_snapshot_list": snapshot.DataSourceSnapshotList(), "decort_vgpu": vgpu.DataSourceVGPU(), + "decort_disk": disks.DataSourceDisk(), "decort_disk_list": disks.DataSourceDiskList(), "decort_rg_list": rg.DataSourceRgList(), "decort_account_list": account.DataSourceAccountList(), @@ -67,6 +69,8 @@ func NewDataSourcesMap() map[string]*schema.Resource { "decort_vins_list": vins.DataSourceVinsList(), "decort_locations_list": locations.DataSourceLocationsList(), "decort_location_url": locations.DataSourceLocationUrl(), + "decort_image_list": image.DataSourceImageList(), + "decort_image": image.DataSourceImage(), // "decort_pfw": dataSourcePfw(), } diff --git a/internal/provider/cloudapi/resource_map.go b/internal/provider/cloudapi/resource_map.go index fd5c27b..844bd76 100644 --- a/internal/provider/cloudapi/resource_map.go +++ b/internal/provider/cloudapi/resource_map.go @@ -24,6 +24,7 @@ import ( "github.com/rudecs/terraform-provider-decort/internal/service/cloudapi/account" "github.com/rudecs/terraform-provider-decort/internal/service/cloudapi/bservice" "github.com/rudecs/terraform-provider-decort/internal/service/cloudapi/disks" + "github.com/rudecs/terraform-provider-decort/internal/service/cloudapi/image" "github.com/rudecs/terraform-provider-decort/internal/service/cloudapi/k8s" "github.com/rudecs/terraform-provider-decort/internal/service/cloudapi/kvmvm" "github.com/rudecs/terraform-provider-decort/internal/service/cloudapi/pfw" @@ -45,5 +46,7 @@ func NewRersourcesMap() map[string]*schema.Resource { "decort_account": account.ResourceAccount(), "decort_bservice": bservice.ResourceBasicService(), "decort_bservice_group": bservice.ResourceBasicServiceGroup(), + "decort_image": image.ResourceImage(), + "decort_image_virtual": image.ResourceImageVirtual(), } } diff --git a/internal/provider/cloudbroker/data_sources_map.go b/internal/provider/cloudbroker/data_sources_map.go index fb633f8..82e74d5 100644 --- a/internal/provider/cloudbroker/data_sources_map.go +++ b/internal/provider/cloudbroker/data_sources_map.go @@ -21,7 +21,8 @@ package cloudbroker import ( "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" - "github.com/rudecs/terraform-provider-decort/internal/service/cloudapi/disks" + "github.com/rudecs/terraform-provider-decort/internal/service/cloudbroker/account" + "github.com/rudecs/terraform-provider-decort/internal/service/cloudbroker/disks" "github.com/rudecs/terraform-provider-decort/internal/service/cloudbroker/grid" "github.com/rudecs/terraform-provider-decort/internal/service/cloudbroker/image" "github.com/rudecs/terraform-provider-decort/internal/service/cloudbroker/pcidevice" @@ -30,20 +31,30 @@ import ( func NewDataSourcesMap() map[string]*schema.Resource { return map[string]*schema.Resource{ - "decort_image": image.DataSourceImage(), - "decort_disk": disks.DataSourceDisk(), - "decort_grid": grid.DataSourceGrid(), - "decort_grid_list": grid.DataSourceGridList(), - "decort_image_list": image.DataSourceImageList(), - "decort_image_list_stacks": image.DataSourceImageListStacks(), - "decort_pcidevice": pcidevice.DataSourcePcidevice(), - "decort_pcidevice_list": pcidevice.DataSourcePcideviceList(), - "decort_sep_list": sep.DataSourceSepList(), - "decort_sep": sep.DataSourceSep(), - "decort_sep_consumption": sep.DataSourceSepConsumption(), - "decort_sep_disk_list": sep.DataSourceSepDiskList(), - "decort_sep_config": sep.DataSourceSepConfig(), - "decort_sep_pool": sep.DataSourceSepPool(), + "decort_account": account.DataSourceAccount(), + "decort_account_list": account.DataSourceAccountList(), + "decort_account_computes_list": account.DataSourceAccountComputesList(), + "decort_account_deleted_list": account.DataSourceAccountDeletedList(), + "decort_account_disks_list": account.DataSourceAccountDisksList(), + "decort_account_flipgroups_list": account.DataSourceAccountFlipGroupsList(), + "decort_account_rg_list": account.DataSourceAccountRGList(), + "decort_account_vins_list": account.DataSourceAccountVinsList(), + "decort_account_audits_list": account.DataSourceAccountAuditsList(), + "decort_disk": disks.DataSourceDisk(), + "decort_disk_list": disks.DataSourceDiskList(), + "decort_image": image.DataSourceImage(), + "decort_grid": grid.DataSourceGrid(), + "decort_grid_list": grid.DataSourceGridList(), + "decort_image_list": image.DataSourceImageList(), + "decort_image_list_stacks": image.DataSourceImageListStacks(), + "decort_pcidevice": pcidevice.DataSourcePcidevice(), + "decort_pcidevice_list": pcidevice.DataSourcePcideviceList(), + "decort_sep_list": sep.DataSourceSepList(), + "decort_sep": sep.DataSourceSep(), + "decort_sep_consumption": sep.DataSourceSepConsumption(), + "decort_sep_disk_list": sep.DataSourceSepDiskList(), + "decort_sep_config": sep.DataSourceSepConfig(), + "decort_sep_pool": sep.DataSourceSepPool(), // "decort_pfw": dataSourcePfw(), } diff --git a/internal/provider/cloudbroker/resources_map.go b/internal/provider/cloudbroker/resources_map.go index 49ead88..89b1281 100644 --- a/internal/provider/cloudbroker/resources_map.go +++ b/internal/provider/cloudbroker/resources_map.go @@ -21,13 +21,23 @@ package cloudbroker import ( "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" + "github.com/rudecs/terraform-provider-decort/internal/service/cloudbroker/account" + "github.com/rudecs/terraform-provider-decort/internal/service/cloudbroker/disks" "github.com/rudecs/terraform-provider-decort/internal/service/cloudbroker/image" + "github.com/rudecs/terraform-provider-decort/internal/service/cloudbroker/k8s" + "github.com/rudecs/terraform-provider-decort/internal/service/cloudbroker/kvmvm" "github.com/rudecs/terraform-provider-decort/internal/service/cloudbroker/pcidevice" + "github.com/rudecs/terraform-provider-decort/internal/service/cloudbroker/pfw" + "github.com/rudecs/terraform-provider-decort/internal/service/cloudbroker/rg" "github.com/rudecs/terraform-provider-decort/internal/service/cloudbroker/sep" + "github.com/rudecs/terraform-provider-decort/internal/service/cloudbroker/snapshot" + "github.com/rudecs/terraform-provider-decort/internal/service/cloudbroker/vins" ) func NewRersourcesMap() map[string]*schema.Resource { return map[string]*schema.Resource{ + "decort_account": account.ResourceAccount(), + "decort_disk": disks.ResourceDisk(), "decort_image": image.ResourceImage(), "decort_virtual_image": image.ResourceVirtualImage(), "decort_cdrom_image": image.ResourceCDROMImage(), @@ -35,5 +45,12 @@ func NewRersourcesMap() map[string]*schema.Resource { "decort_pcidevice": pcidevice.ResourcePcidevice(), "decort_sep": sep.ResourceSep(), "decort_sep_config": sep.ResourceSepConfig(), + "decort_resgroup": rg.ResourceResgroup(), + "decort_kvmvm": kvmvm.ResourceCompute(), + "decort_vins": vins.ResourceVins(), + "decort_pfw": pfw.ResourcePfw(), + "decort_k8s": k8s.ResourceK8s(), + "decort_k8s_wg": k8s.ResourceK8sWg(), + "decort_snapshot": snapshot.ResourceSnapshot(), } } diff --git a/internal/provider/provider.go b/internal/provider/provider.go index f004704..09c45e0 100644 --- a/internal/provider/provider.go +++ b/internal/provider/provider.go @@ -22,6 +22,7 @@ package provider import ( "fmt" + "github.com/hashicorp/terraform-plugin-sdk/v2/diag" "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" "github.com/hashicorp/terraform-plugin-sdk/v2/helper/validation" "golang.org/x/net/context" @@ -105,24 +106,22 @@ func Provider() *schema.Provider { DataSourcesMap: selectSchema(true), - ConfigureFunc: providerConfigure, + ConfigureContextFunc: providerConfigure, } } -func providerConfigure(d *schema.ResourceData) (interface{}, error) { +func providerConfigure(ctx context.Context, d *schema.ResourceData) (interface{}, diag.Diagnostics) { decsController, err := controller.ControllerConfigure(d) if err != nil { - return nil, err + return nil, diag.FromErr(err) } - ctx := context.Background() - gridId, err := location.UtilityLocationGetDefaultGridID(ctx, decsController) if err != nil { - return nil, err + return nil, diag.FromErr(err) } if gridId == 0 { - return nil, fmt.Errorf("providerConfigure: invalid default Grid ID = 0") + return nil, diag.FromErr(fmt.Errorf("providerConfigure: invalid default Grid ID = 0")) } return decsController, nil diff --git a/internal/service/cloudapi/account/data_source_account_list.go b/internal/service/cloudapi/account/data_source_account_list.go index d5370df..f7cbc85 100644 --- a/internal/service/cloudapi/account/data_source_account_list.go +++ b/internal/service/cloudapi/account/data_source_account_list.go @@ -73,51 +73,6 @@ func flattenRgAcl(rgAcls []AccountAclRecord) []map[string]interface{} { return res } -/*uncomment for cloudbroker -func flattenAccountList(al AccountList) []map[string]interface{} { - res := make([]map[string]interface{}, 0) - for _, acc := range al { - temp := map[string]interface{}{ - "dc_location": acc.DCLocation, - "ckey": acc.CKey, - "meta": flattenMeta(acc.Meta), - - "acl": flattenRgAcl(acc.Acl), - - "company": acc.Company, - "companyurl": acc.CompanyUrl, - "created_by": acc.CreatedBy, - - "created_time": acc.CreatedTime, - - "deactivation_time": acc.DeactiovationTime, - "deleted_by": acc.DeletedBy, - - "deleted_time": acc.DeletedTime, - - "displayname": acc.DisplayName, - "guid": acc.GUID, - - "account_id": acc.ID, - "account_name": acc.Name, - - "resource_limits": flattenRgResourceLimits(acc.ResourceLimits), - "send_access_emails": acc.SendAccessEmails, - "service_account": acc.ServiceAccount, - - "status": acc.Status, - "updated_time": acc.UpdatedTime, - - "version": acc.Version, - "vins": acc.Vins, - - } - res = append(res, temp) - } - return res -} -*/ - func dataSourceAccountListRead(ctx context.Context, d *schema.ResourceData, m interface{}) diag.Diagnostics { accountList, err := utilityAccountListCheckPresence(ctx, d, m) if err != nil { @@ -148,22 +103,6 @@ func dataSourceAccountListSchemaMake() map[string]*schema.Schema { Computed: true, Elem: &schema.Resource{ Schema: map[string]*schema.Schema{ - /*uncomment for cloudbroker - "dc_location": { - Type: schema.TypeString, - Computed: true, - }, - "ckey": { - Type: schema.TypeString, - Computed: true, - }, - "meta": { - Type: schema.TypeList, - Computed: true, - Elem: &schema.Schema{ - Type: schema.TypeString, - }, - },*/ "acl": { Type: schema.TypeList, Computed: true, @@ -196,48 +135,14 @@ func dataSourceAccountListSchemaMake() map[string]*schema.Schema { }, }, }, - /*uncomment for cloudbroker - "company": { - Type: schema.TypeString, - Computed: true, - }, - "companyurl": { - Type: schema.TypeString, - Computed: true, - }, - "created_by": { - Type: schema.TypeString, - Computed: true, - }, - */ "created_time": { Type: schema.TypeInt, Computed: true, }, - /*uncomment for cloudbroker - "deactivation_time": { - Type: schema.TypeFloat, - Computed: true, - }, - "deleted_by": { - Type: schema.TypeString, - Computed: true, - }, - */ "deleted_time": { Type: schema.TypeInt, Computed: true, }, - /*uncomment for cloudbroker - "displayname": { - Type: schema.TypeString, - Computed: true, - }, - "guid": { - Type: schema.TypeInt, - Computed: true, - }, - */ "account_id": { Type: schema.TypeInt, Computed: true, @@ -246,49 +151,6 @@ func dataSourceAccountListSchemaMake() map[string]*schema.Schema { Type: schema.TypeString, Computed: true, }, - /*uncomment for cloudbroker - "resource_limits": { - Type: schema.TypeList, - Computed: true, - MaxItems: 1, - Elem: &schema.Resource{ - Schema: map[string]*schema.Schema{ - "cu_c": { - Type: schema.TypeFloat, - Computed: true, - }, - "cu_d": { - Type: schema.TypeFloat, - Computed: true, - }, - "cu_i": { - Type: schema.TypeFloat, - Computed: true, - }, - "cu_m": { - Type: schema.TypeFloat, - Computed: true, - }, - "cu_np": { - Type: schema.TypeFloat, - Computed: true, - }, - "gpu_units": { - Type: schema.TypeFloat, - Computed: true, - }, - }, - }, - }, - "send_access_emails": { - Type: schema.TypeBool, - Computed: true, - }, - "service_account": { - Type: schema.TypeBool, - Computed: true, - }, - */ "status": { Type: schema.TypeString, Computed: true, @@ -297,19 +159,6 @@ func dataSourceAccountListSchemaMake() map[string]*schema.Schema { Type: schema.TypeInt, Computed: true, }, - /*uncomment for cloudbroker - "version": { - Type: schema.TypeInt, - Computed: true, - }, - "vins": { - Type: schema.TypeList, - Computed: true, - Elem: &schema.Schema{ - Type: schema.TypeInt, - }, - }, - */ }, }, }, diff --git a/internal/service/cloudapi/account/resource_account.go b/internal/service/cloudapi/account/resource_account.go index 3ad2939..4a87285 100644 --- a/internal/service/cloudapi/account/resource_account.go +++ b/internal/service/cloudapi/account/resource_account.go @@ -37,7 +37,6 @@ import ( "strconv" "strings" - "github.com/google/uuid" "github.com/hashicorp/terraform-plugin-sdk/v2/diag" "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" "github.com/rudecs/terraform-provider-decort/internal/constants" @@ -49,22 +48,6 @@ import ( func resourceAccountCreate(ctx context.Context, d *schema.ResourceData, m interface{}) diag.Diagnostics { log.Debugf("resourceAccountCreate") - if accountId, ok := d.GetOk("account_id"); ok { - if exists, err := resourceAccountExists(ctx, d, m); exists { - if err != nil { - return diag.FromErr(err) - } - d.SetId(strconv.Itoa(accountId.(int))) - diagnostics := resourceAccountRead(ctx, d, m) - if diagnostics != nil { - return diagnostics - } - - return nil - } - return diag.Errorf("provided account id does not exist") - } - c := m.(*controller.ControllerCfg) urlValues := &url.Values{} @@ -138,7 +121,6 @@ func resourceAccountCreate(ctx context.Context, d *schema.ResourceData, m interf return diag.FromErr(err) } - id := uuid.New() d.SetId(accountId) d.Set("account_id", accountId) @@ -147,7 +129,42 @@ func resourceAccountCreate(ctx context.Context, d *schema.ResourceData, m interf return diagnostics } - d.SetId(id.String()) + urlValues = &url.Values{} + + if enable, ok := d.GetOk("enable"); ok { + api := accountDisableAPI + enable := enable.(bool) + if enable { + api = accountEnableAPI + } + urlValues.Add("accountId", strconv.Itoa(d.Get("account_id").(int))) + + _, err := c.DecortAPICall(ctx, "POST", api, urlValues) + if err != nil { + return diag.FromErr(err) + } + + urlValues = &url.Values{} + } + + if users, ok := d.GetOk("users"); ok { + addedUsers := users.([]interface{}) + + if len(addedUsers) > 0 { + for _, user := range addedUsers { + userConv := user.(map[string]interface{}) + urlValues.Add("accountId", strconv.Itoa(d.Get("account_id").(int))) + urlValues.Add("userId", userConv["user_id"].(string)) + urlValues.Add("accesstype", strings.ToUpper(userConv["access_type"].(string))) + _, err := c.DecortAPICall(ctx, "POST", accountAddUserAPI, urlValues) + if err != nil { + return diag.FromErr(err) + } + + urlValues = &url.Values{} + } + } + } return nil } diff --git a/internal/service/cloudapi/bservice/resource_bservice.go b/internal/service/cloudapi/bservice/resource_bservice.go index 9ce62e4..ab5ff65 100644 --- a/internal/service/cloudapi/bservice/resource_bservice.go +++ b/internal/service/cloudapi/bservice/resource_bservice.go @@ -36,7 +36,6 @@ import ( "net/url" "strconv" - "github.com/google/uuid" "github.com/hashicorp/terraform-plugin-sdk/v2/diag" "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" "github.com/rudecs/terraform-provider-decort/internal/constants" @@ -47,24 +46,6 @@ import ( func resourceBasicServiceCreate(ctx context.Context, d *schema.ResourceData, m interface{}) diag.Diagnostics { log.Debugf("resourceBasicServiceCreate") - if serviceId, ok := d.GetOk("service_id"); ok { - if exists, err := resourceBasicServiceExists(ctx, d, m); exists { - if err != nil { - return diag.FromErr(err) - } - id := uuid.New() - d.SetId(strconv.Itoa(serviceId.(int))) - d.Set("service_id", strconv.Itoa(serviceId.(int))) - diagnostics := resourceBasicServiceRead(ctx, d, m) - if diagnostics != nil { - return diagnostics - } - d.SetId(id.String()) - return nil - } - return diag.Errorf("provided service id does not exist") - } - c := m.(*controller.ControllerCfg) urlValues := &url.Values{} @@ -83,7 +64,6 @@ func resourceBasicServiceCreate(ctx context.Context, d *schema.ResourceData, m i return diag.FromErr(err) } - id := uuid.New() d.SetId(serviceId) d.Set("service_id", serviceId) @@ -92,8 +72,6 @@ func resourceBasicServiceCreate(ctx context.Context, d *schema.ResourceData, m i return diagnostics } - d.SetId(id.String()) - return nil } diff --git a/internal/service/cloudapi/bservice/resource_bservice_group.go b/internal/service/cloudapi/bservice/resource_bservice_group.go index 47271c8..145af41 100644 --- a/internal/service/cloudapi/bservice/resource_bservice_group.go +++ b/internal/service/cloudapi/bservice/resource_bservice_group.go @@ -37,7 +37,6 @@ import ( "strconv" "strings" - "github.com/google/uuid" "github.com/hashicorp/terraform-plugin-sdk/v2/diag" "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" "github.com/hashicorp/terraform-plugin-sdk/v2/helper/validation" @@ -49,26 +48,6 @@ import ( func resourceBasicServiceGroupCreate(ctx context.Context, d *schema.ResourceData, m interface{}) diag.Diagnostics { log.Debugf("resourceBasicServiceGroupCreate") - if compgroupId, ok := d.GetOk("compgroup_id"); ok { - if _, ok := d.GetOk("service_id"); ok { - if exists, err := resourceBasicServiceGroupExists(ctx, d, m); exists { - if err != nil { - return diag.FromErr(err) - } - id := uuid.New() - d.SetId(strconv.Itoa(compgroupId.(int))) - d.Set("compgroup_id", strconv.Itoa(compgroupId.(int))) - diagnostics := resourceBasicServiceGroupRead(ctx, d, m) - if diagnostics != nil { - return diagnostics - } - d.SetId(id.String()) - return nil - } - return diag.Errorf("provided compgroup id does not exist") - } - } - c := m.(*controller.ControllerCfg) urlValues := &url.Values{} @@ -124,7 +103,6 @@ func resourceBasicServiceGroupCreate(ctx context.Context, d *schema.ResourceData return diag.FromErr(err) } - id := uuid.New() d.SetId(compgroupId) d.Set("compgroup_id", compgroupId) @@ -133,8 +111,6 @@ func resourceBasicServiceGroupCreate(ctx context.Context, d *schema.ResourceData return diagnostics } - d.SetId(id.String()) - return nil } diff --git a/internal/service/cloudapi/disks/api.go b/internal/service/cloudapi/disks/api.go index 678cd69..9cc2c71 100644 --- a/internal/service/cloudapi/disks/api.go +++ b/internal/service/cloudapi/disks/api.go @@ -31,9 +31,11 @@ Documentation: https://github.com/rudecs/terraform-provider-decort/wiki package disks -const DisksCreateAPI = "/restmachine/cloudapi/disks/create" -const DisksGetAPI = "/restmachine/cloudapi/disks/get" // Returns single DiskRecord on success -const DisksListAPI = "/restmachine/cloudapi/disks/list" // Returns list of DiskRecord on success -const DisksResizeAPI = "/restmachine/cloudapi/disks/resize2" -const DisksRenameAPI = "/restmachine/cloudapi/disks/rename" -const DisksDeleteAPI = "/restmachine/cloudapi/disks/delete" +const disksCreateAPI = "/restmachine/cloudapi/disks/create" +const disksGetAPI = "/restmachine/cloudapi/disks/get" +const disksListAPI = "/restmachine/cloudapi/disks/list" +const disksResizeAPI = "/restmachine/cloudapi/disks/resize2" +const disksRenameAPI = "/restmachine/cloudapi/disks/rename" +const disksDeleteAPI = "/restmachine/cloudapi/disks/delete" +const disksIOLimitAPI = "/restmachine/cloudapi/disks/limitIO" +const disksRestoreAPI = "/restmachine/cloudapi/disks/restore" diff --git a/internal/service/cloudapi/disks/data_source_disk.go b/internal/service/cloudapi/disks/data_source_disk.go index 46b8cdd..f5e1982 100644 --- a/internal/service/cloudapi/disks/data_source_disk.go +++ b/internal/service/cloudapi/disks/data_source_disk.go @@ -34,162 +34,340 @@ package disks import ( "context" "encoding/json" - "fmt" // "net/url" + "github.com/google/uuid" "github.com/rudecs/terraform-provider-decort/internal/constants" - log "github.com/sirupsen/logrus" "github.com/hashicorp/terraform-plugin-sdk/v2/diag" "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" ) -func flattenDisk(d *schema.ResourceData, disk_facts string) error { - // This function expects disk_facts string to contain a response from disks/get API - // - // NOTE: this function modifies ResourceData argument - as such it should never be called - // from resourceDiskExists(...) method. Use utilityDiskCheckPresence instead. - - log.Debugf("flattenDisk: ready to unmarshal string %s", disk_facts) - - model := DiskRecord{} - - err := json.Unmarshal([]byte(disk_facts), &model) +func dataSourceDiskRead(ctx context.Context, d *schema.ResourceData, m interface{}) diag.Diagnostics { + disk, err := utilityDiskCheckPresence(ctx, d, m) if err != nil { - return err + return diag.FromErr(err) } - log.Debugf("flattenDisk: disk ID %d, disk AccountID %d", model.ID, model.AccountID) - - d.SetId(fmt.Sprintf("%d", model.ID)) - // d.Set("disk_id", model.ID) - we should NOT update disk_id in the schema. If it was set - it is already set, if it wasn't - we shouldn't - d.Set("name", model.Name) - d.Set("account_id", model.AccountID) - d.Set("account_name", model.AccountName) - d.Set("size", model.SizeMax) - // d.Set("sizeUsed", model.SizeUsed) - d.Set("type", model.Type) - d.Set("image_id", model.ImageID) - d.Set("sep_id", model.SepID) - d.Set("sep_type", model.SepType) - d.Set("pool", model.Pool) - // d.Set("compute_id", model.ComputeID) - - d.Set("description", model.Desc) + id := uuid.New() + d.SetId(id.String()) + + diskAcl, _ := json.Marshal(disk.Acl) + + d.Set("account_id", disk.AccountID) + d.Set("account_name", disk.AccountName) + d.Set("acl", string(diskAcl)) + d.Set("boot_partition", disk.BootPartition) + d.Set("compute_id", disk.ComputeID) + d.Set("compute_name", disk.ComputeName) + d.Set("created_time", disk.CreatedTime) + d.Set("deleted_time", disk.DeletedTime) + d.Set("desc", disk.Desc) + d.Set("destruction_time", disk.DestructionTime) + d.Set("devicename", disk.DeviceName) + d.Set("disk_path", disk.DiskPath) + d.Set("gid", disk.GridID) + d.Set("guid", disk.GUID) + d.Set("disk_id", disk.ID) + d.Set("image_id", disk.ImageID) + d.Set("images", disk.Images) + d.Set("iotune", flattenIOTune(disk.IOTune)) + d.Set("iqn", disk.IQN) + d.Set("login", disk.Login) + d.Set("milestones", disk.Milestones) + d.Set("disk_name", disk.Name) + d.Set("order", disk.Order) + d.Set("params", disk.Params) + d.Set("parent_id", disk.ParentId) + d.Set("passwd", disk.Passwd) + d.Set("pci_slot", disk.PciSlot) + d.Set("pool", disk.Pool) + d.Set("purge_attempts", disk.PurgeAttempts) + d.Set("purge_time", disk.PurgeTime) + d.Set("reality_device_number", disk.RealityDeviceNumber) + d.Set("reference_id", disk.ReferenceId) + d.Set("res_id", disk.ResID) + d.Set("res_name", disk.ResName) + d.Set("role", disk.Role) + d.Set("sep_id", disk.SepID) + d.Set("sep_type", disk.SepType) + d.Set("size_max", disk.SizeMax) + d.Set("size_used", disk.SizeUsed) + d.Set("snapshots", flattendDiskSnapshotList(disk.Snapshots)) + d.Set("status", disk.Status) + d.Set("tech_status", disk.TechStatus) + d.Set("type", disk.Type) + d.Set("vmid", disk.VMID) return nil } -func dataSourceDiskRead(ctx context.Context, d *schema.ResourceData, m interface{}) diag.Diagnostics { - disk_facts, err := utilityDiskCheckPresence(ctx, d, m) - if disk_facts == "" { - // if empty string is returned from utilityDiskCheckPresence then there is no - // such Disk and err tells so - just return it to the calling party - d.SetId("") // ensure ID is empty - return diag.FromErr(err) - } - - return diag.FromErr(flattenDisk(d, disk_facts)) -} - func dataSourceDiskSchemaMake() map[string]*schema.Schema { rets := map[string]*schema.Schema{ - "name": { - Type: schema.TypeString, - Optional: true, - Description: "Name of this disk. NOTE: disk names are NOT unique within an account. If disk ID is specified, disk name is ignored.", - }, - "disk_id": { - Type: schema.TypeInt, - Optional: true, - Description: "ID of the disk to get. If disk ID is specified, then disk name and account ID are ignored.", + Type: schema.TypeInt, + Required: true, }, - "account_id": { - Type: schema.TypeInt, - Optional: true, - Description: "ID of the account this disk belongs to. If disk ID is specified, then account ID is ignored.", + Type: schema.TypeInt, + Computed: true, }, - - // The rest of the data source Disk schema are all computed - "sep_id": { - Type: schema.TypeInt, - Computed: true, - Description: "Storage end-point provider serving this disk.", + "account_name": { + Type: schema.TypeString, + Computed: true, }, - - "pool": { - Type: schema.TypeString, - Computed: true, - Description: "Pool where this disk is located.", + "acl": { + Type: schema.TypeString, + Computed: true, }, - - "size": { - Type: schema.TypeInt, - Computed: true, - Description: "Size of the disk in GB.", + "boot_partition": { + Type: schema.TypeInt, + Computed: true, }, - - "type": { - Type: schema.TypeString, - Computed: true, - Description: "Type of this disk. E.g. D for data disks, B for boot.", + "compute_id": { + Type: schema.TypeInt, + Computed: true, }, - - "description": { - Type: schema.TypeString, - Computed: true, - Description: "User-defined text description of this disk.", + "compute_name": { + Type: schema.TypeString, + Computed: true, }, - - "account_name": { - Type: schema.TypeString, - Computed: true, - Description: "Name of the account this disk belongs to. If account ID is specified, account name is ignored.", + "created_time": { + Type: schema.TypeInt, + Computed: true, + }, + "deleted_time": { + Type: schema.TypeInt, + Computed: true, + }, + "desc": { + Type: schema.TypeString, + Computed: true, + }, + "destruction_time": { + Type: schema.TypeInt, + Computed: true, + }, + "devicename": { + Type: schema.TypeString, + Computed: true, + }, + "disk_path": { + Type: schema.TypeString, + Computed: true, + }, + "gid": { + Type: schema.TypeInt, + Computed: true, + }, + "guid": { + Type: schema.TypeInt, + Computed: true, }, - "image_id": { - Type: schema.TypeInt, - Computed: true, - Description: "ID of the image, which this disk was cloned from (valid for disk clones only).", + Type: schema.TypeInt, + Computed: true, }, - - "sep_type": { - Type: schema.TypeString, - Computed: true, - Description: "Type of the storage end-point provider serving this disk.", + "images": { + Type: schema.TypeList, + Computed: true, + Elem: &schema.Schema{ + Type: schema.TypeString, + }, }, - - /* - "snapshots": { - Type: schema.TypeList, - Computed: true, - Elem: &schema.Resource { - Schema: snapshotSubresourceSchemaMake(), + "iotune": { + Type: schema.TypeList, + Computed: true, + Elem: &schema.Resource{ + Schema: map[string]*schema.Schema{ + "read_bytes_sec": { + Type: schema.TypeInt, + Computed: true, + }, + "read_bytes_sec_max": { + Type: schema.TypeInt, + Computed: true, + }, + "read_iops_sec": { + Type: schema.TypeInt, + Computed: true, + }, + "read_iops_sec_max": { + Type: schema.TypeInt, + Computed: true, + }, + "size_iops_sec": { + Type: schema.TypeInt, + Computed: true, + }, + "total_bytes_sec": { + Type: schema.TypeInt, + Computed: true, + }, + "total_bytes_sec_max": { + Type: schema.TypeInt, + Computed: true, + }, + "total_iops_sec": { + Type: schema.TypeInt, + Computed: true, + }, + "total_iops_sec_max": { + Type: schema.TypeInt, + Computed: true, + }, + "write_bytes_sec": { + Type: schema.TypeInt, + Computed: true, + }, + "write_bytes_sec_max": { + Type: schema.TypeInt, + Computed: true, + }, + "write_iops_sec": { + Type: schema.TypeInt, + Computed: true, + }, + "write_iops_sec_max": { + Type: schema.TypeInt, + Computed: true, }, - Description: "List of user-created snapshots for this disk." }, - - "status": { - Type: schema.TypeString, - Computed: true, - Description: "Current model status of this disk.", - }, - - "tech_status": { - Type: schema.TypeString, - Computed: true, - Description: "Current technical status of this disk.", }, - - "compute_id": { - Type: schema.TypeInt, - Computed: true, - Description: "ID of the compute instance where this disk is attached to, or 0 for unattached disk.", + }, + "iqn": { + Type: schema.TypeString, + Computed: true, + }, + "login": { + Type: schema.TypeString, + Computed: true, + }, + "milestones": { + Type: schema.TypeInt, + Computed: true, + }, + "disk_name": { + Type: schema.TypeString, + Computed: true, + }, + "order": { + Type: schema.TypeInt, + Computed: true, + }, + "params": { + Type: schema.TypeString, + Computed: true, + }, + "parent_id": { + Type: schema.TypeInt, + Computed: true, + }, + "passwd": { + Type: schema.TypeString, + Computed: true, + }, + "pci_slot": { + Type: schema.TypeInt, + Computed: true, + }, + "pool": { + Type: schema.TypeString, + Computed: true, + }, + "purge_attempts": { + Type: schema.TypeInt, + Computed: true, + }, + "purge_time": { + Type: schema.TypeInt, + Computed: true, + }, + "reality_device_number": { + Type: schema.TypeInt, + Computed: true, + }, + "reference_id": { + Type: schema.TypeString, + Computed: true, + }, + "res_id": { + Type: schema.TypeString, + Computed: true, + }, + "res_name": { + Type: schema.TypeString, + Computed: true, + }, + "role": { + Type: schema.TypeString, + Computed: true, + }, + "sep_id": { + Type: schema.TypeInt, + Computed: true, + }, + "sep_type": { + Type: schema.TypeString, + Computed: true, + }, + "size_max": { + Type: schema.TypeInt, + Computed: true, + }, + "size_used": { + Type: schema.TypeInt, + Computed: true, + }, + "snapshots": { + Type: schema.TypeList, + Computed: true, + Elem: &schema.Resource{ + Schema: map[string]*schema.Schema{ + "guid": { + Type: schema.TypeString, + Computed: true, + }, + "label": { + Type: schema.TypeString, + Computed: true, + }, + "res_id": { + Type: schema.TypeString, + Computed: true, + }, + "snap_set_guid": { + Type: schema.TypeString, + Computed: true, + }, + "snap_set_time": { + Type: schema.TypeInt, + Computed: true, + }, + "timestamp": { + Type: schema.TypeInt, + Computed: true, + }, + }, }, - */ + }, + "status": { + Type: schema.TypeString, + Computed: true, + }, + "tech_status": { + Type: schema.TypeString, + Computed: true, + }, + "type": { + Type: schema.TypeString, + Computed: true, + }, + "vmid": { + Type: schema.TypeInt, + Computed: true, + }, } return rets diff --git a/internal/service/cloudapi/disks/data_source_disk_list.go b/internal/service/cloudapi/disks/data_source_disk_list.go index dc73729..efe16b6 100644 --- a/internal/service/cloudapi/disks/data_source_disk_list.go +++ b/internal/service/cloudapi/disks/data_source_disk_list.go @@ -41,11 +41,32 @@ import ( "github.com/rudecs/terraform-provider-decort/internal/constants" ) -func flattenDiskList(dl DisksListResp) []map[string]interface{} { +func flattenIOTune(iot IOTune) []map[string]interface{} { + res := make([]map[string]interface{}, 0) + temp := map[string]interface{}{ + "read_bytes_sec": iot.ReadBytesSec, + "read_bytes_sec_max": iot.ReadBytesSecMax, + "read_iops_sec": iot.ReadIopsSec, + "read_iops_sec_max": iot.ReadIopsSecMax, + "size_iops_sec": iot.SizeIopsSec, + "total_bytes_sec": iot.TotalBytesSec, + "total_bytes_sec_max": iot.TotalBytesSecMax, + "total_iops_sec": iot.TotalIopsSec, + "total_iops_sec_max": iot.TotalIopsSecMax, + "write_bytes_sec": iot.WriteBytesSec, + "write_bytes_sec_max": iot.WriteBytesSecMax, + "write_iops_sec": iot.WriteIopsSec, + "write_iops_sec_max": iot.WriteIopsSecMax, + } + + res = append(res, temp) + return res +} + +func flattenDiskList(dl DisksList) []map[string]interface{} { res := make([]map[string]interface{}, 0) for _, disk := range dl { diskAcl, _ := json.Marshal(disk.Acl) - diskIotune, _ := json.Marshal(disk.IOTune) temp := map[string]interface{}{ "account_id": disk.AccountID, "account_name": disk.AccountName, @@ -64,13 +85,13 @@ func flattenDiskList(dl DisksListResp) []map[string]interface{} { "disk_id": disk.ID, "image_id": disk.ImageID, "images": disk.Images, - "iotune": string(diskIotune), + "iotune": flattenIOTune(disk.IOTune), "iqn": disk.IQN, "login": disk.Login, "machine_id": disk.MachineId, "machine_name": disk.MachineName, "milestones": disk.Milestones, - "name": disk.Name, + "disk_name": disk.Name, "order": disk.Order, "params": disk.Params, "parent_id": disk.ParentId, @@ -93,7 +114,6 @@ func flattenDiskList(dl DisksListResp) []map[string]interface{} { "tech_status": disk.TechStatus, "type": disk.Type, "vmid": disk.VMID, - "update_by": disk.UpdateBy, } res = append(res, temp) } @@ -101,7 +121,7 @@ func flattenDiskList(dl DisksListResp) []map[string]interface{} { } -func flattendDiskSnapshotList(sl SnapshotRecordList) []interface{} { +func flattendDiskSnapshotList(sl SnapshotList) []interface{} { res := make([]interface{}, 0) for _, snapshot := range sl { temp := map[string]interface{}{ @@ -231,8 +251,64 @@ func dataSourceDiskListSchemaMake() map[string]*schema.Schema { }, }, "iotune": { - Type: schema.TypeString, + Type: schema.TypeList, Computed: true, + Elem: &schema.Resource{ + Schema: map[string]*schema.Schema{ + "read_bytes_sec": { + Type: schema.TypeInt, + Computed: true, + }, + "read_bytes_sec_max": { + Type: schema.TypeInt, + Computed: true, + }, + "read_iops_sec": { + Type: schema.TypeInt, + Computed: true, + }, + "read_iops_sec_max": { + Type: schema.TypeInt, + Computed: true, + }, + "size_iops_sec": { + Type: schema.TypeInt, + Computed: true, + }, + "total_bytes_sec": { + Type: schema.TypeInt, + Computed: true, + }, + "total_bytes_sec_max": { + Type: schema.TypeInt, + Computed: true, + }, + "total_iops_sec": { + Type: schema.TypeInt, + Computed: true, + }, + "total_iops_sec_max": { + Type: schema.TypeInt, + Computed: true, + }, + "write_bytes_sec": { + Type: schema.TypeInt, + Computed: true, + }, + "write_bytes_sec_max": { + Type: schema.TypeInt, + Computed: true, + }, + "write_iops_sec": { + Type: schema.TypeInt, + Computed: true, + }, + "write_iops_sec_max": { + Type: schema.TypeInt, + Computed: true, + }, + }, + }, }, "iqn": { Type: schema.TypeString, @@ -254,7 +330,7 @@ func dataSourceDiskListSchemaMake() map[string]*schema.Schema { Type: schema.TypeInt, Computed: true, }, - "name": { + "disk_name": { Type: schema.TypeString, Computed: true, }, @@ -374,10 +450,6 @@ func dataSourceDiskListSchemaMake() map[string]*schema.Schema { Type: schema.TypeInt, Computed: true, }, - "update_by": { - Type: schema.TypeInt, - Computed: true, - }, }, }, }, diff --git a/internal/service/cloudapi/disks/models.go b/internal/service/cloudapi/disks/models.go index 8b997ea..b5298e0 100644 --- a/internal/service/cloudapi/disks/models.go +++ b/internal/service/cloudapi/disks/models.go @@ -31,7 +31,7 @@ Documentation: https://github.com/rudecs/terraform-provider-decort/wiki package disks -type DiskRecord struct { +type Disk struct { Acl map[string]interface{} `json:"acl"` AccountID int `json:"accountId"` AccountName string `json:"accountName"` @@ -49,7 +49,7 @@ type DiskRecord struct { ID uint `json:"id"` ImageID int `json:"imageId"` Images []int `json:"images"` - IOTune map[string]interface{} `json:"iotune"` + IOTune IOTune `json:"iotune"` IQN string `json:"iqn"` Login string `json:"login"` Name string `json:"name"` @@ -73,7 +73,7 @@ type DiskRecord struct { SepID int `json:"sepId"` // NOTE: absent from compute/get output SizeMax int `json:"sizeMax"` SizeUsed int `json:"sizeUsed"` // sum over all snapshots of this disk to report total consumed space - Snapshots []SnapshotRecord `json:"snapshots"` + Snapshots []Snapshot `json:"snapshots"` Status string `json:"status"` TechStatus string `json:"techStatus"` Type string `json:"type"` @@ -81,7 +81,7 @@ type DiskRecord struct { VMID int `json:"vmid"` } -type SnapshotRecord struct { +type Snapshot struct { Guid string `json:"guid"` Label string `json:"label"` ResId string `json:"resId"` @@ -90,6 +90,22 @@ type SnapshotRecord struct { TimeStamp uint64 `json:"timestamp"` } -type SnapshotRecordList []SnapshotRecord +type SnapshotList []Snapshot -type DisksListResp []DiskRecord +type DisksList []Disk + +type IOTune struct { + ReadBytesSec int `json:"read_bytes_sec"` + ReadBytesSecMax int `json:"read_bytes_sec_max"` + ReadIopsSec int `json:"read_iops_sec"` + ReadIopsSecMax int `json:"read_iops_sec_max"` + SizeIopsSec int `json:"size_iops_sec"` + TotalBytesSec int `json:"total_bytes_sec"` + TotalBytesSecMax int `json:"total_bytes_sec_max"` + TotalIopsSec int `json:"total_iops_sec"` + TotalIopsSecMax int `json:"total_iops_sec_max"` + WriteBytesSec int `json:"write_bytes_sec"` + WriteBytesSecMax int `json:"write_bytes_sec_max"` + WriteIopsSec int `json:"write_iops_sec"` + WriteIopsSecMax int `json:"write_iops_sec_max"` +} diff --git a/internal/service/cloudapi/disks/resource_disk.go b/internal/service/cloudapi/disks/resource_disk.go index 1fe2b4a..9cb264b 100644 --- a/internal/service/cloudapi/disks/resource_disk.go +++ b/internal/service/cloudapi/disks/resource_disk.go @@ -32,15 +32,15 @@ Documentation: https://github.com/rudecs/terraform-provider-decort/wiki package disks import ( - // "encoding/json" "context" + "encoding/json" "fmt" "net/url" "strconv" + "strings" "github.com/rudecs/terraform-provider-decort/internal/constants" "github.com/rudecs/terraform-provider-decort/internal/controller" - "github.com/rudecs/terraform-provider-decort/internal/location" log "github.com/sirupsen/logrus" "github.com/hashicorp/terraform-plugin-sdk/v2/diag" @@ -49,16 +49,18 @@ import ( ) func resourceDiskCreate(ctx context.Context, d *schema.ResourceData, m interface{}) diag.Diagnostics { - log.Debugf("resourceDiskCreate: called for Disk name %q, Account ID %d", d.Get("name").(string), d.Get("account_id").(int)) - c := m.(*controller.ControllerCfg) urlValues := &url.Values{} - // accountId, gid, name, description, size, type, sep_id, pool + urlValues.Add("accountId", fmt.Sprintf("%d", d.Get("account_id").(int))) - urlValues.Add("gid", fmt.Sprintf("%d", location.DefaultGridID)) // we use default Grid ID, which was obtained along with DECORT Controller init - urlValues.Add("name", d.Get("name").(string)) - urlValues.Add("size", fmt.Sprintf("%d", d.Get("size").(int))) - urlValues.Add("type", "D") // NOTE: only disks of Data type are managed via plugin + urlValues.Add("gid", fmt.Sprintf("%d", d.Get("gid").(int))) + urlValues.Add("name", d.Get("disk_name").(string)) + urlValues.Add("size", fmt.Sprintf("%d", d.Get("size_max").(int))) + if typeRaw, ok := d.GetOk("type"); ok { + urlValues.Add("type", strings.ToUpper(typeRaw.(string))) + } else { + urlValues.Add("type", "D") + } if sepId, ok := d.GetOk("sep_id"); ok { urlValues.Add("sep_id", strconv.Itoa(sepId.(int))) @@ -68,126 +70,210 @@ func resourceDiskCreate(ctx context.Context, d *schema.ResourceData, m interface urlValues.Add("pool", poolName.(string)) } - argVal, argSet := d.GetOk("description") + argVal, argSet := d.GetOk("desc") if argSet { urlValues.Add("description", argVal.(string)) } - apiResp, err := c.DecortAPICall(ctx, "POST", DisksCreateAPI, urlValues) + diskId, err := c.DecortAPICall(ctx, "POST", disksCreateAPI, urlValues) if err != nil { return diag.FromErr(err) } - d.SetId(apiResp) // update ID of the resource to tell Terraform that the disk resource exists - diskId, _ := strconv.Atoi(apiResp) + urlValues = &url.Values{} + + d.SetId(diskId) // update ID of the resource to tell Terraform that the disk resource exists + + if iotuneRaw, ok := d.GetOk("iotune"); ok { + iot := iotuneRaw.([]interface{})[0] + iotune := iot.(map[string]interface{}) + urlValues.Add("diskId", diskId) + urlValues.Add("iops", strconv.Itoa(iotune["total_iops_sec"].(int))) + urlValues.Add("read_bytes_sec", strconv.Itoa(iotune["read_bytes_sec"].(int))) + urlValues.Add("read_bytes_sec_max", strconv.Itoa(iotune["read_bytes_sec_max"].(int))) + urlValues.Add("read_iops_sec", strconv.Itoa(iotune["read_iops_sec"].(int))) + urlValues.Add("read_iops_sec_max", strconv.Itoa(iotune["read_iops_sec_max"].(int))) + urlValues.Add("size_iops_sec", strconv.Itoa(iotune["size_iops_sec"].(int))) + urlValues.Add("total_bytes_sec", strconv.Itoa(iotune["total_bytes_sec"].(int))) + urlValues.Add("total_bytes_sec_max", strconv.Itoa(iotune["total_bytes_sec_max"].(int))) + urlValues.Add("total_iops_sec_max", strconv.Itoa(iotune["total_iops_sec_max"].(int))) + urlValues.Add("write_bytes_sec", strconv.Itoa(iotune["write_bytes_sec"].(int))) + urlValues.Add("write_bytes_sec_max", strconv.Itoa(iotune["write_bytes_sec_max"].(int))) + urlValues.Add("write_iops_sec", strconv.Itoa(iotune["write_iops_sec"].(int))) + urlValues.Add("write_iops_sec_max", strconv.Itoa(iotune["write_iops_sec_max"].(int))) + + _, err := c.DecortAPICall(ctx, "POST", disksIOLimitAPI, urlValues) + if err != nil { + return diag.FromErr(err) + } + + urlValues = &url.Values{} + } - log.Debugf("resourceDiskCreate: new Disk ID / name %d / %s creation sequence complete", diskId, d.Get("name").(string)) + dgn := resourceDiskRead(ctx, d, m) + if dgn != nil { + return dgn + } - // We may reuse dataSourceDiskRead here as we maintain similarity - // between Disk resource and Disk data source schemas - // Disk resource read function will also update resource ID on success, so that Terraform - // will know the resource exists (however, we already did it a few lines before) - return dataSourceDiskRead(ctx, d, m) + return nil } func resourceDiskRead(ctx context.Context, d *schema.ResourceData, m interface{}) diag.Diagnostics { - diskFacts, err := utilityDiskCheckPresence(ctx, d, m) - if diskFacts == "" { - // if empty string is returned from utilityDiskCheckPresence then there is no - // such Disk and err tells so - just return it to the calling party - d.SetId("") // ensure ID is empty - return diag.FromErr(err) + disk, err := utilityDiskCheckPresence(ctx, d, m) + if disk == nil { + d.SetId("") + if err != nil { + return diag.FromErr(err) + } + return nil } - return diag.FromErr(flattenDisk(d, diskFacts)) + diskAcl, _ := json.Marshal(disk.Acl) + + d.Set("account_id", disk.AccountID) + d.Set("account_name", disk.AccountName) + d.Set("acl", string(diskAcl)) + d.Set("boot_partition", disk.BootPartition) + d.Set("compute_id", disk.ComputeID) + d.Set("compute_name", disk.ComputeName) + d.Set("created_time", disk.CreatedTime) + d.Set("deleted_time", disk.DeletedTime) + d.Set("desc", disk.Desc) + d.Set("destruction_time", disk.DestructionTime) + d.Set("devicename", disk.DeviceName) + d.Set("disk_path", disk.DiskPath) + d.Set("gid", disk.GridID) + d.Set("guid", disk.GUID) + d.Set("disk_id", disk.ID) + d.Set("image_id", disk.ImageID) + d.Set("images", disk.Images) + d.Set("iotune", flattenIOTune(disk.IOTune)) + d.Set("iqn", disk.IQN) + d.Set("login", disk.Login) + d.Set("milestones", disk.Milestones) + d.Set("disk_name", disk.Name) + d.Set("order", disk.Order) + d.Set("params", disk.Params) + d.Set("parent_id", disk.ParentId) + d.Set("passwd", disk.Passwd) + d.Set("pci_slot", disk.PciSlot) + d.Set("pool", disk.Pool) + d.Set("purge_attempts", disk.PurgeAttempts) + d.Set("purge_time", disk.PurgeTime) + d.Set("reality_device_number", disk.RealityDeviceNumber) + d.Set("reference_id", disk.ReferenceId) + d.Set("res_id", disk.ResID) + d.Set("res_name", disk.ResName) + d.Set("role", disk.Role) + d.Set("sep_id", disk.SepID) + d.Set("sep_type", disk.SepType) + d.Set("size_max", disk.SizeMax) + d.Set("size_used", disk.SizeUsed) + d.Set("snapshots", flattendDiskSnapshotList(disk.Snapshots)) + d.Set("status", disk.Status) + d.Set("tech_status", disk.TechStatus) + d.Set("type", disk.Type) + d.Set("vmid", disk.VMID) + + return nil } func resourceDiskUpdate(ctx context.Context, d *schema.ResourceData, m interface{}) diag.Diagnostics { - // Update will only change the following attributes of the disk: - // - Size; to keep data safe, shrinking disk is not allowed. - // - Name - // - // Attempt to change disk type will throw an error and mark disk - // resource as partially updated - log.Debugf("resourceDiskUpdate: called for Disk ID / name %s / %s, Account ID %d", - d.Id(), d.Get("name").(string), d.Get("account_id").(int)) c := m.(*controller.ControllerCfg) + urlValues := &url.Values{} + + if d.HasChange("size_max") { + oldSize, newSize := d.GetChange("size_max") + if oldSize.(int) < newSize.(int) { + log.Debugf("resourceDiskUpdate: resizing disk ID %s - %d GB -> %d GB", + d.Id(), oldSize.(int), newSize.(int)) + urlValues.Add("diskId", d.Id()) + urlValues.Add("size", fmt.Sprintf("%d", newSize.(int))) + _, err := c.DecortAPICall(ctx, "POST", disksResizeAPI, urlValues) + if err != nil { + return diag.FromErr(err) + } + d.Set("size_max", newSize) + } else if oldSize.(int) > newSize.(int) { + return diag.FromErr(fmt.Errorf("resourceDiskUpdate: Disk ID %s - reducing disk size is not allowed", d.Id())) + } + urlValues = &url.Values{} + } - oldSize, newSize := d.GetChange("size") - if oldSize.(int) < newSize.(int) { - log.Debugf("resourceDiskUpdate: resizing disk ID %s - %d GB -> %d GB", - d.Id(), oldSize.(int), newSize.(int)) - sizeParams := &url.Values{} - sizeParams.Add("diskId", d.Id()) - sizeParams.Add("size", fmt.Sprintf("%d", newSize.(int))) - _, err := c.DecortAPICall(ctx, "POST", DisksResizeAPI, sizeParams) + if d.HasChange("disk_name") { + urlValues.Add("diskId", d.Id()) + urlValues.Add("name", d.Get("disk_name").(string)) + _, err := c.DecortAPICall(ctx, "POST", disksRenameAPI, urlValues) if err != nil { return diag.FromErr(err) } - d.Set("size", newSize) - } else if oldSize.(int) > newSize.(int) { - return diag.FromErr(fmt.Errorf("resourceDiskUpdate: Disk ID %s - reducing disk size is not allowed", d.Id())) + + urlValues = &url.Values{} } - oldName, newName := d.GetChange("name") - if oldName.(string) != newName.(string) { - log.Debugf("resourceDiskUpdate: renaming disk ID %d - %s -> %s", - d.Get("disk_id").(int), oldName.(string), newName.(string)) - renameParams := &url.Values{} - renameParams.Add("diskId", d.Id()) - renameParams.Add("name", newName.(string)) - _, err := c.DecortAPICall(ctx, "POST", DisksRenameAPI, renameParams) + if d.HasChange("iotune") { + iot := d.Get("iotune").([]interface{})[0] + iotune := iot.(map[string]interface{}) + urlValues.Add("diskId", d.Id()) + urlValues.Add("iops", strconv.Itoa(iotune["total_iops_sec"].(int))) + urlValues.Add("read_bytes_sec", strconv.Itoa(iotune["read_bytes_sec"].(int))) + urlValues.Add("read_bytes_sec_max", strconv.Itoa(iotune["read_bytes_sec_max"].(int))) + urlValues.Add("read_iops_sec", strconv.Itoa(iotune["read_iops_sec"].(int))) + urlValues.Add("read_iops_sec_max", strconv.Itoa(iotune["read_iops_sec_max"].(int))) + urlValues.Add("size_iops_sec", strconv.Itoa(iotune["size_iops_sec"].(int))) + urlValues.Add("total_bytes_sec", strconv.Itoa(iotune["total_bytes_sec"].(int))) + urlValues.Add("total_bytes_sec_max", strconv.Itoa(iotune["total_bytes_sec_max"].(int))) + urlValues.Add("total_iops_sec_max", strconv.Itoa(iotune["total_iops_sec_max"].(int))) + urlValues.Add("write_bytes_sec", strconv.Itoa(iotune["write_bytes_sec"].(int))) + urlValues.Add("write_bytes_sec_max", strconv.Itoa(iotune["write_bytes_sec_max"].(int))) + urlValues.Add("write_iops_sec", strconv.Itoa(iotune["write_iops_sec"].(int))) + urlValues.Add("write_iops_sec_max", strconv.Itoa(iotune["write_iops_sec_max"].(int))) + + _, err := c.DecortAPICall(ctx, "POST", disksIOLimitAPI, urlValues) if err != nil { return diag.FromErr(err) } + + urlValues = &url.Values{} } - /* - NOTE: plugin will manage disks of type "Data" only, and type cannot be changed once disk is created + if d.HasChange("restore") { + if d.Get("restore").(bool) { + urlValues.Add("diskId", d.Id()) + urlValues.Add("reason", d.Get("reason").(string)) - oldType, newType := d.GetChange("type") - if oldType.(string) != newType.(string) { - return fmt.Errorf("resourceDiskUpdate: Disk ID %s - changing type of existing disk not allowed", d.Id()) + _, err := c.DecortAPICall(ctx, "POST", disksRestoreAPI, urlValues) + if err != nil { + return diag.FromErr(err) + } + + urlValues = &url.Values{} } - */ - // we may reuse dataSourceDiskRead here as we maintain similarity - // between Compute resource and Compute data source schemas - return dataSourceDiskRead(ctx, d, m) + } + + return resourceDiskRead(ctx, d, m) } func resourceDiskDelete(ctx context.Context, d *schema.ResourceData, m interface{}) diag.Diagnostics { - // NOTE: this function tries to detach and destroy target Disk "permanently", so - // there is no way to restore it. - // If, however, the disk is attached to a compute, the method will - // fail (by failing the underpinning DECORt API call, which is issued with detach=false) - log.Debugf("resourceDiskDelete: called for Disk ID / name %d / %s, Account ID %d", - d.Get("disk_id").(int), d.Get("name").(string), d.Get("account_id").(int)) - diskFacts, err := utilityDiskCheckPresence(ctx, d, m) - if diskFacts == "" { + disk, err := utilityDiskCheckPresence(ctx, d, m) + if disk == nil { if err != nil { return diag.FromErr(err) } - // the specified Disk does not exist - in this case according to Terraform best practice - // we exit from Destroy method without error return nil } params := &url.Values{} params.Add("diskId", d.Id()) - // NOTE: we are not force-detaching disk from a compute (if attached) thus protecting - // data that may be on that disk from destruction. - // However, this may change in the future, as TF state management logic may want - // to delete disk resource BEFORE it is detached from compute instance, and, while - // perfectly OK from data preservation viewpoint, this is breaking expected TF workflow - // in the eyes of an experienced TF user - params.Add("detach", "0") - params.Add("permanently", "1") + params.Add("detach", strconv.FormatBool(d.Get("detach").(bool))) + params.Add("permanently", strconv.FormatBool(d.Get("permanently").(bool))) + params.Add("reason", d.Get("reason").(string)) c := m.(*controller.ControllerCfg) - _, err = c.DecortAPICall(ctx, "POST", DisksDeleteAPI, params) + _, err = c.DecortAPICall(ctx, "POST", disksDeleteAPI, params) if err != nil { return diag.FromErr(err) } @@ -196,12 +282,9 @@ func resourceDiskDelete(ctx context.Context, d *schema.ResourceData, m interface } func resourceDiskExists(ctx context.Context, d *schema.ResourceData, m interface{}) (bool, error) { - // Reminder: according to Terraform rules, this function should not modify its ResourceData argument - log.Debugf("resourceDiskExists: called for Disk ID / name %d / %s, Account ID %d", - d.Get("disk_id").(int), d.Get("name").(string), d.Get("account_id").(int)) diskFacts, err := utilityDiskCheckPresence(ctx, d, m) - if diskFacts == "" { + if diskFacts == nil { if err != nil { return false, err } @@ -212,101 +295,318 @@ func resourceDiskExists(ctx context.Context, d *schema.ResourceData, m interface func resourceDiskSchemaMake() map[string]*schema.Schema { rets := map[string]*schema.Schema{ - "name": { - Type: schema.TypeString, - Required: true, - Description: "Name of this disk. NOTE: disk names are NOT unique within an account. If disk ID is specified, disk name is ignored.", + "account_id": { + Type: schema.TypeInt, + Required: true, }, - - "disk_id": { - Type: schema.TypeInt, - Optional: true, - Description: "ID of the disk to get. If disk ID is specified, then disk name and account ID are ignored.", + "disk_name": { + Type: schema.TypeString, + Required: true, }, - - "account_id": { - Type: schema.TypeInt, - Required: true, - Description: "ID of the account this disk belongs to.", + "size_max": { + Type: schema.TypeInt, + Required: true, + }, + "gid": { + Type: schema.TypeInt, + Required: true, + }, + "pool": { + Type: schema.TypeString, + Optional: true, + Computed: true, }, - "sep_id": { - Type: schema.TypeInt, - Optional: true, - Computed: true, - ForceNew: true, - Description: "Storage end-point provider serving this disk. Cannot be changed for existing disk.", + Type: schema.TypeInt, + Optional: true, + Computed: true, + }, + "desc": { + Type: schema.TypeString, + Optional: true, + Computed: true, + }, + "type": { + Type: schema.TypeString, + Optional: true, + Computed: true, + ValidateFunc: validation.StringInSlice([]string{"D", "B", "T"}, false), }, - "pool": { - Type: schema.TypeString, + "detach": { + Type: schema.TypeBool, Optional: true, - Computed: true, - ForceNew: true, - Description: "Pool where this disk is located. Cannot be changed for existing disk.", + Default: false, + Description: "detach disk from machine first", }, - - "size": { - Type: schema.TypeInt, - Required: true, - ValidateFunc: validation.IntAtLeast(1), - Description: "Size of the disk in GB. Note, that existing disks can only be grown in size.", + "permanently": { + Type: schema.TypeBool, + Optional: true, + Default: false, + Description: "whether to completely delete the disk, works only with non attached disks", }, - - /* We moved "type" attribute to computed attributes section, as plugin manages disks of only - one type - "D", e.g. data disks. - "type": { + "reason": { Type: schema.TypeString, Optional: true, - Default: "D", - StateFunc: stateFuncToUpper, - ValidateFunc: validation.StringInSlice([]string{"B", "D"}, false), - Description: "Optional type of this disk. Defaults to D, i.e. data disk. Cannot be changed for existing disks.", + Default: "", + Description: "reason for an action", }, - */ - - "description": { - Type: schema.TypeString, + "restore": { + Type: schema.TypeBool, Optional: true, - Default: "Disk resource managed by Terraform", - Description: "Optional user-defined text description of this disk.", + Default: false, + Description: "restore deleting disk", }, - // The rest of the attributes are all computed + "disk_id": { + Type: schema.TypeInt, + Computed: true, + }, "account_name": { - Type: schema.TypeString, - Computed: true, - Description: "Name of the account this disk belongs to.", + Type: schema.TypeString, + Computed: true, + }, + "acl": { + Type: schema.TypeString, + Computed: true, + }, + "boot_partition": { + Type: schema.TypeInt, + Computed: true, + }, + "compute_id": { + Type: schema.TypeInt, + Computed: true, + }, + "compute_name": { + Type: schema.TypeString, + Computed: true, + }, + "created_time": { + Type: schema.TypeInt, + Computed: true, + }, + "deleted_time": { + Type: schema.TypeInt, + Computed: true, + }, + "destruction_time": { + Type: schema.TypeInt, + Computed: true, + }, + "devicename": { + Type: schema.TypeString, + Computed: true, + }, + "disk_path": { + Type: schema.TypeString, + Computed: true, + }, + "guid": { + Type: schema.TypeInt, + Computed: true, }, - "image_id": { - Type: schema.TypeInt, - Computed: true, - Description: "ID of the image, which this disk was cloned from (if ever cloned).", + Type: schema.TypeInt, + Computed: true, + }, + "images": { + Type: schema.TypeList, + Computed: true, + Elem: &schema.Schema{ + Type: schema.TypeString, + }, + }, + "iotune": { + Type: schema.TypeList, + Optional: true, + MaxItems: 1, + Computed: true, + Elem: &schema.Resource{ + Schema: map[string]*schema.Schema{ + "read_bytes_sec": { + Type: schema.TypeInt, + Optional: true, + Computed: true, + }, + "read_bytes_sec_max": { + Type: schema.TypeInt, + Optional: true, + Computed: true, + }, + "read_iops_sec": { + Type: schema.TypeInt, + Optional: true, + Computed: true, + }, + "read_iops_sec_max": { + Type: schema.TypeInt, + Optional: true, + Computed: true, + }, + "size_iops_sec": { + Type: schema.TypeInt, + Optional: true, + Computed: true, + }, + "total_bytes_sec": { + Type: schema.TypeInt, + Optional: true, + Computed: true, + }, + "total_bytes_sec_max": { + Type: schema.TypeInt, + Optional: true, + Computed: true, + }, + "total_iops_sec": { + Type: schema.TypeInt, + Optional: true, + Computed: true, + }, + "total_iops_sec_max": { + Type: schema.TypeInt, + Optional: true, + Computed: true, + }, + "write_bytes_sec": { + Type: schema.TypeInt, + Optional: true, + Computed: true, + }, + "write_bytes_sec_max": { + Type: schema.TypeInt, + Optional: true, + Computed: true, + }, + "write_iops_sec": { + Type: schema.TypeInt, + Optional: true, + Computed: true, + }, + "write_iops_sec_max": { + Type: schema.TypeInt, + Optional: true, + Computed: true, + }, + }, + }, + }, + "iqn": { + Type: schema.TypeString, + Computed: true, + }, + "login": { + Type: schema.TypeString, + Computed: true, + }, + "milestones": { + Type: schema.TypeInt, + Computed: true, }, - "type": { - Type: schema.TypeString, - Computed: true, - Description: "Type of this disk.", + "order": { + Type: schema.TypeInt, + Computed: true, + }, + "params": { + Type: schema.TypeString, + Computed: true, + }, + "parent_id": { + Type: schema.TypeInt, + Computed: true, + }, + "passwd": { + Type: schema.TypeString, + Computed: true, + }, + "pci_slot": { + Type: schema.TypeInt, + Computed: true, }, - "sep_type": { - Type: schema.TypeString, - Computed: true, - Description: "Type of the storage end-point provider serving this disk.", + "purge_attempts": { + Type: schema.TypeInt, + Computed: true, + }, + "purge_time": { + Type: schema.TypeInt, + Computed: true, + }, + "reality_device_number": { + Type: schema.TypeInt, + Computed: true, + }, + "reference_id": { + Type: schema.TypeString, + Computed: true, + }, + "res_id": { + Type: schema.TypeString, + Computed: true, + }, + "res_name": { + Type: schema.TypeString, + Computed: true, + }, + "role": { + Type: schema.TypeString, + Computed: true, }, - /* - "snapshots": { - Type: schema.TypeList, - Computed: true, - Elem: &schema.Resource { - Schema: snapshotSubresourceSchemaMake(), + "sep_type": { + Type: schema.TypeString, + Computed: true, + }, + "size_used": { + Type: schema.TypeInt, + Computed: true, + }, + "snapshots": { + Type: schema.TypeList, + Computed: true, + Elem: &schema.Resource{ + Schema: map[string]*schema.Schema{ + "guid": { + Type: schema.TypeString, + Computed: true, + }, + "label": { + Type: schema.TypeString, + Computed: true, + }, + "res_id": { + Type: schema.TypeString, + Computed: true, + }, + "snap_set_guid": { + Type: schema.TypeString, + Computed: true, + }, + "snap_set_time": { + Type: schema.TypeInt, + Computed: true, + }, + "timestamp": { + Type: schema.TypeInt, + Computed: true, + }, }, - Description: "List of user-created snapshots for this disk." }, - */ + }, + "status": { + Type: schema.TypeString, + Computed: true, + }, + "tech_status": { + Type: schema.TypeString, + Computed: true, + }, + "vmid": { + Type: schema.TypeInt, + Computed: true, + }, } return rets diff --git a/internal/service/cloudapi/disks/utility_disk.go b/internal/service/cloudapi/disks/utility_disk.go index 73053a8..1fb4544 100644 --- a/internal/service/cloudapi/disks/utility_disk.go +++ b/internal/service/cloudapi/disks/utility_disk.go @@ -34,7 +34,6 @@ package disks import ( "context" "encoding/json" - "fmt" "net/url" "strconv" @@ -44,103 +43,28 @@ import ( "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" ) -func utilityDiskCheckPresence(ctx context.Context, d *schema.ResourceData, m interface{}) (string, error) { - // This function tries to locate Disk by one of the following algorithms depending on - // the parameters passed: - // - if disk ID is specified -> by disk ID - // - if disk name is specifeid -> by disk name and either account ID or account name - // - // NOTE: disk names are not unique, so the first occurence of this name in the account will - // be returned. There is no such ambiguity when locating disk by its ID. - // - // If succeeded, it returns non empty string that contains JSON formatted facts about the disk - // as returned by disks/get API call. - // Otherwise it returns empty string and meaningful error. - // - // This function does not modify its ResourceData argument, so it is safe to use it as core - // method for resource's Exists method. - // - +func utilityDiskCheckPresence(ctx context.Context, d *schema.ResourceData, m interface{}) (*Disk, error) { c := m.(*controller.ControllerCfg) urlValues := &url.Values{} - // make it possible to use "read" & "check presence" functions with disk ID set so - // that Import of preexisting Disk resource is possible - idSet := false - theId, err := strconv.Atoi(d.Id()) - if err != nil || theId <= 0 { - diskId, argSet := d.GetOk("disk_id") - if argSet { - theId = diskId.(int) - idSet = true - } - } else { - idSet = true - } - - if idSet { - // disk ID is specified, try to get disk instance straight by this ID - log.Debugf("utilityDiskCheckPresence: locating disk by its ID %d", theId) - urlValues.Add("diskId", fmt.Sprintf("%d", theId)) - diskFacts, err := c.DecortAPICall(ctx, "POST", DisksGetAPI, urlValues) - if err != nil { - return "", err - } - return diskFacts, nil - } + disk := &Disk{} - // ID or disk_di was not set in the schema upon entering this function - rely on Disk name - // and Account ID to find the disk - diskName, argSet := d.GetOk("name") - if !argSet { - // no disk ID and no disk name - we cannot locate disk in this case - return "", fmt.Errorf("Cannot locate disk if name is empty and no disk ID specified") + if d.Get("disk_id").(int) == 0 { + urlValues.Add("diskId", d.Id()) + } else { + urlValues.Add("diskId", strconv.Itoa(d.Get("disk_id").(int))) } - // Valid account ID is required to locate disks - // obtain Account ID by account name - it should not be zero on success - - urlValues.Add("accountId", fmt.Sprintf("%d", d.Get("account_id").(int))) - diskFacts, err := c.DecortAPICall(ctx, "POST", DisksListAPI, urlValues) + log.Debugf("utilityDiskCheckPresence: load disk") + diskRaw, err := c.DecortAPICall(ctx, "POST", disksGetAPI, urlValues) if err != nil { - return "", err + return nil, err } - log.Debugf("utilityDiskCheckPresence: ready to unmarshal string %s", diskFacts) - - disksList := DisksListResp{} - err = json.Unmarshal([]byte(diskFacts), &disksList) + err = json.Unmarshal([]byte(diskRaw), disk) if err != nil { - return "", err - } - - // log.Printf("%#v", vm_list) - log.Debugf("utilityDiskCheckPresence: traversing decoded JSON of length %d", len(disksList)) - for index, item := range disksList { - // need to match disk by name, return the first match - if item.Name == diskName.(string) && item.Status != "DESTROYED" { - log.Debugf("utilityDiskCheckPresence: index %d, matched disk name %q", index, item.Name) - // we found the disk we need - not get detailed information via API call to disks/get - /* - // TODO: this may not be optimal as it initiates one extra call to the DECORT controller - // in spite of the fact that we already have all required information about the disk in - // item variable - // - get_urlValues := &url.Values{} - get_urlValues.Add("diskId", fmt.Sprintf("%d", item.ID)) - diskFacts, err = controller.decortAPICall("POST", DisksGetAPI, get_urlValues) - if err != nil { - return "", err - } - return diskFacts, nil - */ - reencodedItem, err := json.Marshal(item) - if err != nil { - return "", err - } - return string(reencodedItem[:]), nil - } + return nil, err } - return "", nil // there should be no error if disk does not exist + return disk, nil } diff --git a/internal/service/cloudapi/disks/utility_disk_list.go b/internal/service/cloudapi/disks/utility_disk_list.go index 50d3cf4..1782ac3 100644 --- a/internal/service/cloudapi/disks/utility_disk_list.go +++ b/internal/service/cloudapi/disks/utility_disk_list.go @@ -44,8 +44,8 @@ import ( "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" ) -func utilityDiskListCheckPresence(ctx context.Context, d *schema.ResourceData, m interface{}) (DisksListResp, error) { - diskList := DisksListResp{} +func utilityDiskListCheckPresence(ctx context.Context, d *schema.ResourceData, m interface{}) (DisksList, error) { + diskList := DisksList{} c := m.(*controller.ControllerCfg) urlValues := &url.Values{} @@ -62,8 +62,8 @@ func utilityDiskListCheckPresence(ctx context.Context, d *schema.ResourceData, m urlValues.Add("accountId", strconv.Itoa(accountId.(int))) } - log.Debugf("utilityDiskListCheckPresence: load grid list") - diskListRaw, err := c.DecortAPICall(ctx, "POST", DisksListAPI, urlValues) + log.Debugf("utilityDiskListCheckPresence: load disk list") + diskListRaw, err := c.DecortAPICall(ctx, "POST", disksListAPI, urlValues) if err != nil { return nil, err } diff --git a/internal/service/cloudapi/image/api.go b/internal/service/cloudapi/image/api.go new file mode 100644 index 0000000..49eb1d4 --- /dev/null +++ b/internal/service/cloudapi/image/api.go @@ -0,0 +1,40 @@ +/* +Copyright (c) 2019-2022 Digital Energy Cloud Solutions LLC. All Rights Reserved. +Authors: +Petr Krutov, +Stanislav Solovev, + +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. +*/ + +/* +Terraform DECORT provider - manage resources provided by DECORT (Digital Energy Cloud +Orchestration Technology) with Terraform by Hashicorp. + +Source code: https://github.com/rudecs/terraform-provider-decort + +Please see README.md to learn where to place source code so that it +builds seamlessly. + +Documentation: https://github.com/rudecs/terraform-provider-decort/wiki +*/ + +package image + +const imageCreateAPI = "/restmachine/cloudapi/image/createImage" +const imageCreateVirtualAPI = "/restmachine/cloudapi/image/createVirtual" +const imageGetAPI = "/restmachine/cloudapi/image/get" +const imageListGetAPI = "/restmachine/cloudapi/image/list" +const imageDeleteAPI = "/restmachine/cloudapi/image/delete" +const imageEditNameAPI = "/restmachine/cloudapi/image/rename" +const imageLinkAPI = "/restmachine/cloudapi/image/link" diff --git a/internal/service/cloudapi/image/data_source_image.go b/internal/service/cloudapi/image/data_source_image.go new file mode 100644 index 0000000..d5b6ef4 --- /dev/null +++ b/internal/service/cloudapi/image/data_source_image.go @@ -0,0 +1,123 @@ +/* +Copyright (c) 2019-2022 Digital Energy Cloud Solutions LLC. All Rights Reserved. +Authors: +Petr Krutov, +Stanislav Solovev, + +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. +*/ + +/* +Terraform DECORT provider - manage resources provided by DECORT (Digital Energy Cloud +Orchestration Technology) with Terraform by Hashicorp. + +Source code: https://github.com/rudecs/terraform-provider-decort + +Please see README.md to learn where to place source code so that it +builds seamlessly. + +Documentation: https://github.com/rudecs/terraform-provider-decort/wiki +*/ + +package image + +import ( + "context" + + "github.com/google/uuid" + "github.com/hashicorp/terraform-plugin-sdk/v2/diag" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" + "github.com/rudecs/terraform-provider-decort/internal/constants" +) + +func flattenHistory(history []History) []map[string]interface{} { + temp := make([]map[string]interface{}, 0) + for _, item := range history { + t := map[string]interface{}{ + "id": item.Id, + "guid": item.Guid, + "timestamp": item.Timestamp, + } + + temp = append(temp, t) + } + return temp +} + +func flattenImage(d *schema.ResourceData, img *ImageExtend) { + d.Set("unc_path", img.UNCPath) + d.Set("ckey", img.CKey) + d.Set("account_id", img.AccountId) + d.Set("acl", img.Acl) + d.Set("architecture", img.Architecture) + d.Set("boot_type", img.BootType) + d.Set("bootable", img.Bootable) + d.Set("compute_ci_id", img.ComputeCiId) + d.Set("deleted_time", img.DeletedTime) + d.Set("desc", img.Description) + d.Set("drivers", img.Drivers) + d.Set("enabled", img.Enabled) + d.Set("gid", img.GridId) + d.Set("guid", img.GUID) + d.Set("history", flattenHistory(img.History)) + d.Set("hot_resize", img.HotResize) + d.Set("image_id", img.Id) + d.Set("last_modified", img.LastModified) + d.Set("link_to", img.LinkTo) + d.Set("milestones", img.Milestones) + d.Set("image_name", img.Name) + d.Set("password", img.Password) + d.Set("pool_name", img.Pool) + d.Set("provider_name", img.ProviderName) + d.Set("purge_attempts", img.PurgeAttempts) + d.Set("res_id", img.ResId) + d.Set("rescuecd", img.RescueCD) + d.Set("sep_id", img.SepId) + d.Set("shared_with", img.SharedWith) + d.Set("size", img.Size) + d.Set("status", img.Status) + d.Set("tech_status", img.TechStatus) + d.Set("type", img.Type) + d.Set("username", img.Username) + d.Set("version", img.Version) +} + +func dataSourceImageRead(ctx context.Context, d *schema.ResourceData, m interface{}) diag.Diagnostics { + image, err := utilityImageCheckPresence(ctx, d, m) + if err != nil { + + return diag.FromErr(err) + } + + id := uuid.New() + d.SetId(id.String()) + + flattenImage(d, image) + + return nil +} + +func DataSourceImage() *schema.Resource { + return &schema.Resource{ + SchemaVersion: 1, + + ReadContext: dataSourceImageRead, + + Timeouts: &schema.ResourceTimeout{ + Read: &constants.Timeout30s, + Default: &constants.Timeout60s, + }, + + Schema: dataSourceImageExtendSchemaMake(), + } +} diff --git a/internal/service/cloudapi/image/data_source_image_list.go b/internal/service/cloudapi/image/data_source_image_list.go new file mode 100644 index 0000000..08e5f18 --- /dev/null +++ b/internal/service/cloudapi/image/data_source_image_list.go @@ -0,0 +1,126 @@ +/* +Copyright (c) 2019-2022 Digital Energy Cloud Solutions LLC. All Rights Reserved. +Authors: +Petr Krutov, +Stanislav Solovev, + +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. +*/ + +/* +Terraform DECORT provider - manage resources provided by DECORT (Digital Energy Cloud +Orchestration Technology) with Terraform by Hashicorp. + +Source code: https://github.com/rudecs/terraform-provider-decort + +Please see README.md to learn where to place source code so that it +builds seamlessly. + +Documentation: https://github.com/rudecs/terraform-provider-decort/wiki +*/ + +package image + +import ( + "context" + + "github.com/google/uuid" + "github.com/hashicorp/terraform-plugin-sdk/v2/diag" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" + "github.com/rudecs/terraform-provider-decort/internal/constants" +) + +func flattenImageList(il ImageList) []map[string]interface{} { + res := make([]map[string]interface{}, 0) + for _, img := range il { + temp := map[string]interface{}{ + "account_id": img.AccountId, + "architecture": img.Architecture, + "boot_type": img.BootType, + "bootable": img.Bootable, + "cdrom": img.CDROM, + "desc": img.Description, + "drivers": img.Drivers, + "hot_resize": img.HotResize, + "image_id": img.Id, + "link_to": img.LinkTo, + "image_name": img.Name, + "pool_name": img.Pool, + "sep_id": img.SepId, + "size": img.Size, + "status": img.Status, + "type": img.Type, + "username": img.Username, + "virtual": img.Virtual, + } + res = append(res, temp) + } + return res +} + +func dataSourceImageListRead(ctx context.Context, d *schema.ResourceData, m interface{}) diag.Diagnostics { + imageList, err := utilityImageListCheckPresence(ctx, d, m) + if err != nil { + return diag.FromErr(err) + } + id := uuid.New() + d.SetId(id.String()) + d.Set("items", flattenImageList(imageList)) + + return nil +} + +func dataSourceImageListSchemaMake() map[string]*schema.Schema { + rets := map[string]*schema.Schema{ + "account_id": { + Type: schema.TypeInt, + Optional: true, + Description: "optional account ID to include account images", + }, + "page": { + Type: schema.TypeInt, + Optional: true, + Description: "page number", + }, + "size": { + Type: schema.TypeInt, + Optional: true, + Description: "page size", + }, + "items": { + Type: schema.TypeList, + Computed: true, + Description: "image list", + Elem: &schema.Resource{ + Schema: dataSourceImageSchemaMake(), + }, + }, + } + + return rets +} + +func DataSourceImageList() *schema.Resource { + return &schema.Resource{ + SchemaVersion: 1, + + ReadContext: dataSourceImageListRead, + + Timeouts: &schema.ResourceTimeout{ + Read: &constants.Timeout30s, + Default: &constants.Timeout60s, + }, + + Schema: dataSourceImageListSchemaMake(), + } +} diff --git a/internal/service/cloudapi/image/image_ds_subresource.go b/internal/service/cloudapi/image/image_ds_subresource.go new file mode 100644 index 0000000..5b0f97a --- /dev/null +++ b/internal/service/cloudapi/image/image_ds_subresource.go @@ -0,0 +1,208 @@ +/* +Copyright (c) 2019-2022 Digital Energy Cloud Solutions LLC. All Rights Reserved. +Authors: +Petr Krutov, +Stanislav Solovev, + +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. +*/ + +/* +Terraform DECORT provider - manage resources provided by DECORT (Digital Energy Cloud +Orchestration Technology) with Terraform by Hashicorp. + +Source code: https://github.com/rudecs/terraform-provider-decort + +Please see README.md to learn where to place source code so that it +builds seamlessly. + +Documentation: https://github.com/rudecs/terraform-provider-decort/wiki +*/ + +package image + +import "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" + +func dataSourceImageExtendSchemaMake() map[string]*schema.Schema { + return map[string]*schema.Schema{ + "image_id": { + Type: schema.TypeInt, + Required: true, + }, + "show_all": { + Type: schema.TypeBool, + Default: false, + Optional: true, + }, + + "unc_path": { + Type: schema.TypeString, + Computed: true, + }, + "ckey": { + Type: schema.TypeString, + Computed: true, + }, + "account_id": { + Type: schema.TypeInt, + Computed: true, + }, + "acl": { + Type: schema.TypeString, + Computed: true, + }, + "architecture": { + Type: schema.TypeString, + Computed: true, + }, + "boot_type": { + Type: schema.TypeString, + Computed: true, + }, + "bootable": { + Type: schema.TypeBool, + Computed: true, + }, + "compute_ci_id": { + Type: schema.TypeInt, + Computed: true, + }, + "deleted_time": { + Type: schema.TypeString, + Computed: true, + }, + "desc": { + Type: schema.TypeString, + Computed: true, + }, + "drivers": { + Type: schema.TypeList, + Computed: true, + Elem: &schema.Schema{ + Type: schema.TypeString, + }, + }, + "enabled": { + Type: schema.TypeBool, + Computed: true, + }, + "gid": { + Type: schema.TypeInt, + Computed: true, + }, + "guid": { + Type: schema.TypeInt, + Computed: true, + }, + "history": { + Type: schema.TypeList, + Computed: true, + Elem: &schema.Resource{ + Schema: map[string]*schema.Schema{ + "guid": { + Type: schema.TypeString, + Computed: true, + }, + "id": { + Type: schema.TypeInt, + Computed: true, + }, + "timestamp": { + Type: schema.TypeInt, + Computed: true, + }, + }, + }, + }, + "hot_resize": { + Type: schema.TypeBool, + Computed: true, + }, + + "last_modified": { + Type: schema.TypeInt, + Computed: true, + }, + "link_to": { + Type: schema.TypeInt, + Computed: true, + }, + "milestones": { + Type: schema.TypeInt, + Computed: true, + }, + "image_name": { + Type: schema.TypeString, + Computed: true, + }, + "password": { + Type: schema.TypeString, + Computed: true, + }, + "pool_name": { + Type: schema.TypeString, + Computed: true, + }, + "provider_name": { + Type: schema.TypeString, + Computed: true, + }, + "purge_attempts": { + Type: schema.TypeInt, + Computed: true, + }, + "res_id": { + Type: schema.TypeString, + Computed: true, + }, + "rescuecd": { + Type: schema.TypeBool, + Computed: true, + }, + "sep_id": { + Type: schema.TypeInt, + Computed: true, + }, + "shared_with": { + Type: schema.TypeList, + Computed: true, + Elem: &schema.Schema{ + Type: schema.TypeInt, + }, + }, + "size": { + Type: schema.TypeInt, + Computed: true, + }, + "status": { + Type: schema.TypeString, + Computed: true, + }, + "tech_status": { + Type: schema.TypeString, + Computed: true, + }, + "type": { + Type: schema.TypeString, + Computed: true, + }, + "username": { + Type: schema.TypeString, + Computed: true, + }, + "version": { + Type: schema.TypeString, + Computed: true, + }, + } +} diff --git a/internal/service/cloudapi/image/image_item_subresource.go b/internal/service/cloudapi/image/image_item_subresource.go new file mode 100644 index 0000000..06aa342 --- /dev/null +++ b/internal/service/cloudapi/image/image_item_subresource.go @@ -0,0 +1,132 @@ +/* +Copyright (c) 2019-2022 Digital Energy Cloud Solutions LLC. All Rights Reserved. +Authors: +Petr Krutov, +Stanislav Solovev, + +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. +*/ + +/* +Terraform DECORT provider - manage resources provided by DECORT (Digital Energy Cloud +Orchestration Technology) with Terraform by Hashicorp. + +Source code: https://github.com/rudecs/terraform-provider-decort + +Please see README.md to learn where to place source code so that it +builds seamlessly. + +Documentation: https://github.com/rudecs/terraform-provider-decort/wiki +*/ + +package image + +import "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" + +func dataSourceImageSchemaMake() map[string]*schema.Schema { + return map[string]*schema.Schema{ + "account_id": { + Type: schema.TypeInt, + Computed: true, + Description: "Owner account id", + }, + "architecture": { + Type: schema.TypeString, + Computed: true, + Description: "Image architecture", + }, + "boot_type": { + Type: schema.TypeString, + Computed: true, + Description: "Boot image type", + }, + "bootable": { + Type: schema.TypeBool, + Computed: true, + Description: "Flag, true if image is bootable, otherwise - false", + }, + "cdrom": { + Type: schema.TypeBool, + Computed: true, + Description: "Flag, true if image is cdrom image, otherwise - false", + }, + "desc": { + Type: schema.TypeString, + Computed: true, + Description: "Image description", + }, + "drivers": { + Type: schema.TypeList, + Computed: true, + Elem: &schema.Schema{ + Type: schema.TypeString, + }, + Description: "Image drivers", + }, + "hot_resize": { + Type: schema.TypeBool, + Computed: true, + Description: "Flag, true if image supports hot resize, else if not", + }, + "image_id": { + Type: schema.TypeInt, + Computed: true, + Description: "Image id", + }, + "link_to": { + Type: schema.TypeInt, + Computed: true, + Description: "For virtual images, id image, which current image linked", + }, + "image_name": { + Type: schema.TypeString, + Computed: true, + Description: "Image name", + }, + "pool_name": { + Type: schema.TypeString, + Computed: true, + Description: "Image pool", + }, + "sep_id": { + Type: schema.TypeInt, + Computed: true, + Description: "Image storage endpoint id", + }, + "size": { + Type: schema.TypeInt, + Computed: true, + Description: "Image size", + }, + "status": { + Type: schema.TypeString, + Computed: true, + Description: "Image status", + }, + "type": { + Type: schema.TypeString, + Computed: true, + Description: "Image type", + }, + "username": { + Type: schema.TypeString, + Computed: true, + Description: "username", + }, + "virtual": { + Type: schema.TypeBool, + Computed: true, + Description: "True if image is virtula, otherwise - else", + }, + } +} diff --git a/internal/service/cloudapi/image/image_rs_subresource.go b/internal/service/cloudapi/image/image_rs_subresource.go new file mode 100644 index 0000000..bbd87a7 --- /dev/null +++ b/internal/service/cloudapi/image/image_rs_subresource.go @@ -0,0 +1,158 @@ +/* +Copyright (c) 2019-2022 Digital Energy Cloud Solutions LLC. All Rights Reserved. +Authors: +Petr Krutov, +Stanislav Solovev, + +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. +*/ + +/* +Terraform DECORT provider - manage resources provided by DECORT (Digital Energy Cloud +Orchestration Technology) with Terraform by Hashicorp. + +Source code: https://github.com/rudecs/terraform-provider-decort + +Please see README.md to learn where to place source code so that it +builds seamlessly. + +Documentation: https://github.com/rudecs/terraform-provider-decort/wiki +*/ + +package image + +import ( + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/validation" +) + +func resourceImageSchemaMake(sch map[string]*schema.Schema) map[string]*schema.Schema { + delete(sch, "show_all") + sch["name"] = &schema.Schema{ + Type: schema.TypeString, + Required: true, + Description: "Name of the rescue disk", + } + + sch["url"] = &schema.Schema{ + Type: schema.TypeString, + Required: true, + Description: "URL where to download media from", + } + + sch["gid"] = &schema.Schema{ + Type: schema.TypeInt, + Required: true, + Description: "grid (platform) ID where this template should be create in", + } + + sch["image_id"] = &schema.Schema{ + Type: schema.TypeInt, + Optional: true, + Computed: true, + Description: "image id", + } + + sch["boot_type"] = &schema.Schema{ + Type: schema.TypeString, + Required: true, + ValidateFunc: validation.StringInSlice([]string{"bios", "uefi"}, true), + Description: "Boot type of image bios or uefi", + } + + sch["type"] = &schema.Schema{ + Type: schema.TypeString, + Required: true, + ValidateFunc: validation.StringInSlice([]string{"linux", "windows", "other"}, true), + Description: "Image type linux, windows or other", + } + + sch["hot_resize"] = &schema.Schema{ + Type: schema.TypeBool, + Optional: true, + Computed: true, + Description: "Does this machine supports hot resize", + } + + sch["username"] = &schema.Schema{ + Type: schema.TypeString, + Optional: true, + Computed: true, + Description: "Optional username for the image", + } + + sch["password"] = &schema.Schema{ + Type: schema.TypeString, + Optional: true, + Computed: true, + Description: "Optional password for the image", + } + + sch["account_id"] = &schema.Schema{ + Type: schema.TypeInt, + Optional: true, + Computed: true, + Description: "AccountId to make the image exclusive", + } + + sch["username_dl"] = &schema.Schema{ + Type: schema.TypeString, + Optional: true, + Description: "username for upload binary media", + } + + sch["password_dl"] = &schema.Schema{ + Type: schema.TypeString, + Optional: true, + Description: "password for upload binary media", + } + + sch["pool_name"] = &schema.Schema{ + Type: schema.TypeString, + Optional: true, + Computed: true, + Description: "pool for image create", + } + + sch["sep_id"] = &schema.Schema{ + Type: schema.TypeInt, + Optional: true, + Computed: true, + Description: "storage endpoint provider ID", + } + + sch["architecture"] = &schema.Schema{ + Type: schema.TypeString, + Optional: true, + Computed: true, + ValidateFunc: validation.StringInSlice([]string{"X86_64", "PPC64_LE"}, true), + Description: "binary architecture of this image, one of X86_64 of PPC64_LE", + } + + sch["drivers"] = &schema.Schema{ + Type: schema.TypeList, + Required: true, + Elem: &schema.Schema{ + Type: schema.TypeString, + }, + } + + sch["permanently"] = &schema.Schema{ + Type: schema.TypeBool, + Optional: true, + Default: false, + Description: "whether to completely delete the image", + } + + return sch +} diff --git a/internal/service/cloudapi/image/image_virtual_rs_subresource.go b/internal/service/cloudapi/image/image_virtual_rs_subresource.go new file mode 100644 index 0000000..06c62f4 --- /dev/null +++ b/internal/service/cloudapi/image/image_virtual_rs_subresource.go @@ -0,0 +1,66 @@ +/* +Copyright (c) 2019-2022 Digital Energy Cloud Solutions LLC. All Rights Reserved. +Authors: +Petr Krutov, +Stanislav Solovev, + +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. +*/ + +/* +Terraform DECORT provider - manage resources provided by DECORT (Digital Energy Cloud +Orchestration Technology) with Terraform by Hashicorp. + +Source code: https://github.com/rudecs/terraform-provider-decort + +Please see README.md to learn where to place source code so that it +builds seamlessly. + +Documentation: https://github.com/rudecs/terraform-provider-decort/wiki +*/ + +package image + +import ( + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" +) + +func resourceImageVirtualSchemaMake(sch map[string]*schema.Schema) map[string]*schema.Schema { + delete(sch, "show_all") + sch["name"] = &schema.Schema{ + Type: schema.TypeString, + Required: true, + Description: "Name of the rescue disk", + } + + sch["link_to"] = &schema.Schema{ + Type: schema.TypeInt, + Required: true, + Description: "ID of real image to link this virtual image to upon creation", + } + + sch["permanently"] = &schema.Schema{ + Type: schema.TypeBool, + Optional: true, + Default: false, + Description: "whether to completely delete the image", + } + + sch["image_id"] = &schema.Schema{ + Type: schema.TypeInt, + Computed: true, + Description: "Image id", + } + + return sch +} diff --git a/internal/service/cloudapi/image/models.go b/internal/service/cloudapi/image/models.go new file mode 100644 index 0000000..a499849 --- /dev/null +++ b/internal/service/cloudapi/image/models.go @@ -0,0 +1,148 @@ +/* +Copyright (c) 2019-2022 Digital Energy Cloud Solutions LLC. All Rights Reserved. +Authors: +Petr Krutov, +Stanislav Solovev, + +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. +*/ + +/* +Terraform DECORT provider - manage resources provided by DECORT (Digital Energy Cloud +Orchestration Technology) with Terraform by Hashicorp. + +Source code: https://github.com/rudecs/terraform-provider-decort + +Please see README.md to learn where to place source code so that it +builds seamlessly. + +Documentation: https://github.com/rudecs/terraform-provider-decort/wiki +*/ + +package image + +/* +type History struct { + Guid string `json:"guid"` + Id int `json:"id"` + Timestamp int64 `json:"timestamp"` +} + +type Image struct { + ImageId int `json:"id"` + Name string `json:"name"` + Url string `json:"url"` + Gid int `json:"gid"` + Guid int `json:"guid"` + Boottype string `json:"bootType"` + Imagetype string `json:"type"` + Drivers []string `json:"drivers"` + Hotresize bool `json:"hotResize"` + Bootable bool `json:"bootable"` + Username string `json:"username"` + Password string `json:"password"` + AccountId int `json:"accountId"` + UsernameDL string `json:"usernameDL"` + PasswordDL string `json:"passwordDL"` + SepId int `json:"sepId"` + PoolName string `json:"pool"` + Architecture string `json:"architecture"` + UNCPath string `json:"UNCPath"` + LinkTo int `json:"linkTo"` + Status string `json:"status"` + TechStatus string `json:"techStatus"` + Size int `json:"size"` + Version string `json:"version"` + Enabled bool `json:"enabled"` + ComputeciId int `json:"computeciId"` + Milestones int `json:"milestones"` + ProviderName string `json:"provider_name"` + PurgeAttempts int `json:"purgeAttempts"` + ReferenceId string `json:"referenceId"` + ResId string `json:"resId"` + ResName string `json:"resName"` + Rescuecd bool `json:"rescuecd"` + Meta []interface{} `json:"_meta"` + History []History `json:"history"` + LastModified int64 `json:"lastModified"` + Desc string `json:"desc"` + SharedWith []int `json:"sharedWith"` +} +*/ + +type Image struct { + AccountId int `json:"accountId"` + Architecture string `json:"architecture"` + BootType string `json:"bootType"` + Bootable bool `json:"bootable"` + CDROM bool `json:"cdrom"` + Description string `json:"desc"` + Drivers []string `json:"drivers"` + HotResize bool `json:"hotResize"` + Id int `json:"id"` + LinkTo int `json:"linkTo"` + Name string `json:"name"` + Pool string `json:"pool"` + SepId int `json:"sepId"` + Size int `json:"size"` + Status string `json:"status"` + Type string `json:"type"` + Username string `json:"username"` + Virtual bool `json:"virtual"` +} + +type ImageList []Image + +type History struct { + Guid string `json:"guid"` + Id int `json:"id"` + Timestamp int64 `json:"timestamp"` +} + +type ImageExtend struct { + UNCPath string `json:"UNCPath"` + CKey string `json:"_ckey"` + AccountId int `json:"accountId"` + Acl interface{} `json:"acl"` + Architecture string `json:"architecture"` + BootType string `json:"bootType"` + Bootable bool `json:"bootable"` + ComputeCiId int `json:"computeciId"` + DeletedTime int `json:"deletedTime"` + Description string `json:"desc"` + Drivers []string `json:"drivers"` + Enabled bool `json:"enabled"` + GridId int `json:"gid"` + GUID int `json:"guid"` + History []History `json:"history"` + HotResize bool `json:"hotResize"` + Id int `json:"id"` + LastModified int `json:"lastModified"` + LinkTo int `json:"linkTo"` + Milestones int `json:"milestones"` + Name string `json:"name"` + Password string `json:"password"` + Pool string `json:"pool"` + ProviderName string `json:"provider_name"` + PurgeAttempts int `json:"purgeAttempts"` + ResId string `json:"resId"` + RescueCD bool `json:"rescuecd"` + SepId int `json:"sepId"` + SharedWith []int `json:"sharedWith"` + Size int `json:"size"` + Status string `json:"status"` + TechStatus string `json:"techStatus"` + Type string `json:"type"` + Username string `json:"username"` + Version string `json:"version"` +} diff --git a/internal/service/cloudapi/image/resource_image.go b/internal/service/cloudapi/image/resource_image.go new file mode 100644 index 0000000..f963141 --- /dev/null +++ b/internal/service/cloudapi/image/resource_image.go @@ -0,0 +1,259 @@ +/* +Copyright (c) 2019-2022 Digital Energy Cloud Solutions LLC. All Rights Reserved. +Authors: +Petr Krutov, +Stanislav Solovev, + +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. +*/ + +/* +Terraform DECORT provider - manage resources provided by DECORT (Digital Energy Cloud +Orchestration Technology) with Terraform by Hashicorp. + +Source code: https://github.com/rudecs/terraform-provider-decort + +Please see README.md to learn where to place source code so that it +builds seamlessly. + +Documentation: https://github.com/rudecs/terraform-provider-decort/wiki +*/ + +package image + +import ( + "context" + "net/url" + "strconv" + + "github.com/hashicorp/terraform-plugin-sdk/v2/diag" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" + "github.com/rudecs/terraform-provider-decort/internal/constants" + "github.com/rudecs/terraform-provider-decort/internal/controller" + log "github.com/sirupsen/logrus" +) + +func resourceImageCreate(ctx context.Context, d *schema.ResourceData, m interface{}) diag.Diagnostics { + log.Debugf("resourceImageCreate: called for image %s", d.Get("name").(string)) + + c := m.(*controller.ControllerCfg) + urlValues := &url.Values{} + urlValues.Add("name", d.Get("name").(string)) + urlValues.Add("url", d.Get("url").(string)) + urlValues.Add("gid", strconv.Itoa(d.Get("gid").(int))) + urlValues.Add("boottype", d.Get("boot_type").(string)) + urlValues.Add("imagetype", d.Get("image_type").(string)) + + tstr := d.Get("drivers").([]interface{}) + temp := "" + l := len(tstr) + for i, str := range tstr { + s := "\"" + str.(string) + "\"" + if i != (l - 1) { + s += "," + } + temp = temp + s + } + temp = "[" + temp + "]" + urlValues.Add("drivers", temp) + + if hotresize, ok := d.GetOk("hot_resize"); ok { + urlValues.Add("hotresize", strconv.FormatBool(hotresize.(bool))) + } + if username, ok := d.GetOk("username"); ok { + urlValues.Add("username", username.(string)) + } + if password, ok := d.GetOk("password"); ok { + urlValues.Add("password", password.(string)) + } + if accountId, ok := d.GetOk("account_id"); ok { + urlValues.Add("accountId", strconv.Itoa(accountId.(int))) + } + if usernameDL, ok := d.GetOk("username_dl"); ok { + urlValues.Add("usernameDL", usernameDL.(string)) + } + if passwordDL, ok := d.GetOk("password_dl"); ok { + urlValues.Add("passwordDL", passwordDL.(string)) + } + if sepId, ok := d.GetOk("sep_id"); ok { + urlValues.Add("sepId", strconv.Itoa(sepId.(int))) + } + if poolName, ok := d.GetOk("pool_name"); ok { + urlValues.Add("poolName", poolName.(string)) + } + if architecture, ok := d.GetOk("architecture"); ok { + urlValues.Add("architecture", architecture.(string)) + } + + imageId, err := c.DecortAPICall(ctx, "POST", imageCreateAPI, urlValues) + if err != nil { + return diag.FromErr(err) + } + + d.SetId(imageId) + d.Set("image_id", imageId) + + _, err = utilityImageCheckPresence(ctx, d, m) + if err != nil { + return diag.FromErr(err) + } + + diagnostics := resourceImageRead(ctx, d, m) + if diagnostics != nil { + return diagnostics + } + + return nil +} + +func resourceImageRead(ctx context.Context, d *schema.ResourceData, m interface{}) diag.Diagnostics { + log.Debugf("resourceImageRead: called for %s id: %s", d.Get("name").(string), d.Id()) + + img, err := utilityImageCheckPresence(ctx, d, m) + if img == nil { + d.SetId("") + return diag.FromErr(err) + } + + d.Set("unc_path", img.UNCPath) + d.Set("ckey", img.CKey) + d.Set("account_id", img.AccountId) + d.Set("acl", img.Acl) + d.Set("architecture", img.Architecture) + d.Set("boot_type", img.BootType) + d.Set("bootable", img.Bootable) + d.Set("compute_ci_id", img.ComputeCiId) + d.Set("deleted_time", img.DeletedTime) + d.Set("desc", img.Description) + d.Set("drivers", img.Drivers) + d.Set("enabled", img.Enabled) + d.Set("gid", img.GridId) + d.Set("guid", img.GUID) + d.Set("history", flattenHistory(img.History)) + d.Set("hot_resize", img.HotResize) + d.Set("image_id", img.Id) + d.Set("last_modified", img.LastModified) + d.Set("link_to", img.LinkTo) + d.Set("milestones", img.Milestones) + d.Set("image_name", img.Name) + d.Set("password", img.Password) + d.Set("pool_name", img.Pool) + d.Set("provider_name", img.ProviderName) + d.Set("purge_attempts", img.PurgeAttempts) + d.Set("res_id", img.ResId) + d.Set("rescuecd", img.RescueCD) + d.Set("sep_id", img.SepId) + d.Set("shared_with", img.SharedWith) + d.Set("size", img.Size) + d.Set("status", img.Status) + d.Set("tech_status", img.TechStatus) + d.Set("type", img.Type) + d.Set("username", img.Username) + d.Set("version", img.Version) + + return nil +} + +func resourceImageDelete(ctx context.Context, d *schema.ResourceData, m interface{}) diag.Diagnostics { + log.Debugf("resourceImageDelete: called for %s, id: %s", d.Get("name").(string), d.Id()) + + image, err := utilityImageCheckPresence(ctx, d, m) + if image == nil { + if err != nil { + return diag.FromErr(err) + } + return nil + } + + c := m.(*controller.ControllerCfg) + urlValues := &url.Values{} + urlValues.Add("imageId", strconv.Itoa(d.Get("image_id").(int))) + + if permanently, ok := d.GetOk("permanently"); ok { + urlValues.Add("permanently", strconv.FormatBool(permanently.(bool))) + } + + _, err = c.DecortAPICall(ctx, "POST", imageDeleteAPI, urlValues) + if err != nil { + return diag.FromErr(err) + } + d.SetId("") + + return nil +} + +func resourceImageExists(ctx context.Context, d *schema.ResourceData, m interface{}) (bool, error) { + log.Debugf("resourceImageExists: called for %s, id: %s", d.Get("name").(string), d.Id()) + + image, err := utilityImageCheckPresence(ctx, d, m) + if image == nil { + if err != nil { + return false, err + } + return false, nil + } + + return true, nil +} + +func resourceImageEditName(ctx context.Context, d *schema.ResourceData, m interface{}) error { + log.Debugf("resourceImageEditName: called for %s, id: %s", d.Get("name").(string), d.Id()) + c := m.(*controller.ControllerCfg) + urlValues := &url.Values{} + urlValues.Add("imageId", strconv.Itoa(d.Get("image_id").(int))) + urlValues.Add("name", d.Get("name").(string)) + _, err := c.DecortAPICall(ctx, "POST", imageEditNameAPI, urlValues) + if err != nil { + return err + } + + return nil +} + +func resourceImageEdit(ctx context.Context, d *schema.ResourceData, m interface{}) diag.Diagnostics { + log.Debugf("resourceImageEdit: called for %s, id: %s", d.Get("name").(string), d.Id()) + + if d.HasChange("name") { + err := resourceImageEditName(ctx, d, m) + if err != nil { + return diag.FromErr(err) + } + } + + return resourceImageRead(ctx, d, m) +} + +func ResourceImage() *schema.Resource { + return &schema.Resource{ + SchemaVersion: 1, + + CreateContext: resourceImageCreate, + ReadContext: resourceImageRead, + UpdateContext: resourceImageEdit, + DeleteContext: resourceImageDelete, + + Importer: &schema.ResourceImporter{ + State: schema.ImportStatePassthrough, + }, + + Timeouts: &schema.ResourceTimeout{ + Create: &constants.Timeout60s, + Read: &constants.Timeout30s, + Update: &constants.Timeout60s, + Delete: &constants.Timeout60s, + Default: &constants.Timeout60s, + }, + + Schema: resourceImageSchemaMake(dataSourceImageExtendSchemaMake()), + } +} diff --git a/internal/service/cloudapi/image/resource_image_virtual.go b/internal/service/cloudapi/image/resource_image_virtual.go new file mode 100644 index 0000000..4252a7f --- /dev/null +++ b/internal/service/cloudapi/image/resource_image_virtual.go @@ -0,0 +1,132 @@ +/* +Copyright (c) 2019-2022 Digital Energy Cloud Solutions LLC. All Rights Reserved. +Authors: +Petr Krutov, +Stanislav Solovev, + +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. +*/ + +/* +Terraform DECORT provider - manage resources provided by DECORT (Digital Energy Cloud +Orchestration Technology) with Terraform by Hashicorp. + +Source code: https://github.com/rudecs/terraform-provider-decort + +Please see README.md to learn where to place source code so that it +builds seamlessly. + +Documentation: https://github.com/rudecs/terraform-provider-decort/wiki +*/ + +package image + +import ( + "context" + "net/url" + "strconv" + + "github.com/hashicorp/terraform-plugin-sdk/v2/diag" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" + "github.com/rudecs/terraform-provider-decort/internal/constants" + "github.com/rudecs/terraform-provider-decort/internal/controller" + log "github.com/sirupsen/logrus" +) + +func resourceImageVirtualCreate(ctx context.Context, d *schema.ResourceData, m interface{}) diag.Diagnostics { + log.Debugf("resourceImageVirtualCreate: called for image %s", d.Get("name").(string)) + + c := m.(*controller.ControllerCfg) + urlValues := &url.Values{} + urlValues.Add("name", d.Get("name").(string)) + urlValues.Add("targetId", strconv.Itoa(d.Get("target_id").(int))) + + imageId, err := c.DecortAPICall(ctx, "POST", imageCreateVirtualAPI, urlValues) + if err != nil { + return diag.FromErr(err) + } + + d.SetId(imageId) + d.Set("image_id", imageId) + + _, err = utilityImageCheckPresence(ctx, d, m) + if err != nil { + return diag.FromErr(err) + } + + diagnostics := resourceImageRead(ctx, d, m) + if diagnostics != nil { + return diagnostics + } + + return nil +} + +func resourceImageVirtualEdit(ctx context.Context, d *schema.ResourceData, m interface{}) diag.Diagnostics { + log.Debugf("resourceImageEdit: called for %s, id: %s", d.Get("name").(string), d.Id()) + + if d.HasChange("name") { + err := resourceImageEditName(ctx, d, m) + if err != nil { + return diag.FromErr(err) + } + } + + if d.HasChange("link_to") { + err := resourceImageVirtualLink(ctx, d, m) + if err != nil { + return diag.FromErr(err) + } + } + + return resourceImageRead(ctx, d, m) +} + +func resourceImageVirtualLink(ctx context.Context, d *schema.ResourceData, m interface{}) error { + log.Debugf("resourceVirtualImageLink: called for %s, id: %s", d.Get("name").(string), d.Id()) + c := m.(*controller.ControllerCfg) + urlValues := &url.Values{} + urlValues.Add("imageId", strconv.Itoa(d.Get("image_id").(int))) + urlValues.Add("targetId", strconv.Itoa(d.Get("link_to").(int))) + _, err := c.DecortAPICall(ctx, "POST", imageLinkAPI, urlValues) + if err != nil { + return err + } + + return nil +} + +func ResourceImageVirtual() *schema.Resource { + return &schema.Resource{ + SchemaVersion: 1, + + CreateContext: resourceImageVirtualCreate, + ReadContext: resourceImageRead, + UpdateContext: resourceImageVirtualEdit, + DeleteContext: resourceImageDelete, + + Importer: &schema.ResourceImporter{ + State: schema.ImportStatePassthrough, + }, + + Timeouts: &schema.ResourceTimeout{ + Create: &constants.Timeout60s, + Read: &constants.Timeout30s, + Update: &constants.Timeout60s, + Delete: &constants.Timeout60s, + Default: &constants.Timeout60s, + }, + + Schema: resourceImageVirtualSchemaMake(dataSourceImageExtendSchemaMake()), + } +} diff --git a/internal/service/cloudapi/image/utility_image.go b/internal/service/cloudapi/image/utility_image.go new file mode 100644 index 0000000..dd9e58d --- /dev/null +++ b/internal/service/cloudapi/image/utility_image.go @@ -0,0 +1,75 @@ +/* +Copyright (c) 2019-2022 Digital Energy Cloud Solutions LLC. All Rights Reserved. +Authors: +Petr Krutov, +Stanislav Solovev, + +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. +*/ + +/* +Terraform DECORT provider - manage resources provided by DECORT (Digital Energy Cloud +Orchestration Technology) with Terraform by Hashicorp. + +Source code: https://github.com/rudecs/terraform-provider-decort + +Please see README.md to learn where to place source code so that it +builds seamlessly. + +Documentation: https://github.com/rudecs/terraform-provider-decort/wiki +*/ + +package image + +import ( + "context" + "encoding/json" + "errors" + "fmt" + "net/url" + "strconv" + + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" + "github.com/rudecs/terraform-provider-decort/internal/controller" +) + +func utilityImageCheckPresence(ctx context.Context, d *schema.ResourceData, m interface{}) (*ImageExtend, error) { + c := m.(*controller.ControllerCfg) + urlValues := &url.Values{} + + if (strconv.Itoa(d.Get("image_id").(int))) != "0" { + urlValues.Add("imageId", strconv.Itoa(d.Get("image_id").(int))) + } else { + urlValues.Add("imageId", d.Id()) + } + + if showAll, ok := d.GetOk("show_all"); ok { + urlValues.Add("page", strconv.FormatBool(showAll.(bool))) + } + + resp, err := c.DecortAPICall(ctx, "POST", imageGetAPI, urlValues) + if err != nil { + return nil, err + } + + if resp == "" { + return nil, nil + } + + image := &ImageExtend{} + if err := json.Unmarshal([]byte(resp), image); err != nil { + return nil, errors.New(fmt.Sprint("Can not unmarshall data to image: ", resp, " ", image)) + } + + return image, nil +} diff --git a/internal/service/cloudapi/image/utility_image_list.go b/internal/service/cloudapi/image/utility_image_list.go new file mode 100644 index 0000000..724018e --- /dev/null +++ b/internal/service/cloudapi/image/utility_image_list.go @@ -0,0 +1,74 @@ +/* +Copyright (c) 2019-2022 Digital Energy Cloud Solutions LLC. All Rights Reserved. +Authors: +Petr Krutov, +Stanislav Solovev, + +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. +*/ + +/* +Terraform DECORT provider - manage resources provided by DECORT (Digital Energy Cloud +Orchestration Technology) with Terraform by Hashicorp. + +Source code: https://github.com/rudecs/terraform-provider-decort + +Please see README.md to learn where to place source code so that it +builds seamlessly. + +Documentation: https://github.com/rudecs/terraform-provider-decort/wiki +*/ + +package image + +import ( + "context" + "encoding/json" + "net/url" + "strconv" + + "github.com/rudecs/terraform-provider-decort/internal/controller" + log "github.com/sirupsen/logrus" + + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" +) + +func utilityImageListCheckPresence(ctx context.Context, d *schema.ResourceData, m interface{}) (ImageList, error) { + imageList := ImageList{} + c := m.(*controller.ControllerCfg) + urlValues := &url.Values{} + + if accountId, ok := d.GetOk("account_id"); ok { + urlValues.Add("accountId", strconv.Itoa(accountId.(int))) + } + + if page, ok := d.GetOk("page"); ok { + urlValues.Add("page", strconv.Itoa(page.(int))) + } + if size, ok := d.GetOk("size"); ok { + urlValues.Add("size", strconv.Itoa(size.(int))) + } + + log.Debugf("utilityImageListCheckPresence: load image list") + imageListRaw, err := c.DecortAPICall(ctx, "POST", imageListGetAPI, urlValues) + if err != nil { + return nil, err + } + + err = json.Unmarshal([]byte(imageListRaw), &imageList) + if err != nil { + return nil, err + } + + return imageList, nil +} diff --git a/internal/service/cloudbroker/account/account_audit_ds_subresource.go b/internal/service/cloudbroker/account/account_audit_ds_subresource.go new file mode 100644 index 0000000..9ceabee --- /dev/null +++ b/internal/service/cloudbroker/account/account_audit_ds_subresource.go @@ -0,0 +1,59 @@ +/* +Copyright (c) 2019-2022 Digital Energy Cloud Solutions LLC. All Rights Reserved. +Authors: +Petr Krutov, +Stanislav Solovev, + +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. +*/ + +/* +Terraform DECORT provider - manage resources provided by DECORT (Digital Energy Cloud +Orchestration Technology) with Terraform by Hashicorp. + +Source code: https://github.com/rudecs/terraform-provider-decort + +Please see README.md to learn where to place source code so that it +builds seamlessly. + +Documentation: https://github.com/rudecs/terraform-provider-decort/wiki +*/ + +package account + +import "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" + +func dataSourceAccountAuditSchemaMake() map[string]*schema.Schema { + return map[string]*schema.Schema{ + "call": { + Type: schema.TypeString, + Computed: true, + }, + "responsetime": { + Type: schema.TypeFloat, + Computed: true, + }, + "statuscode": { + Type: schema.TypeInt, + Computed: true, + }, + "timestamp": { + Type: schema.TypeFloat, + Computed: true, + }, + "user": { + Type: schema.TypeString, + Computed: true, + }, + } +} diff --git a/internal/service/cloudbroker/account/account_compute_ds_subresource.go b/internal/service/cloudbroker/account/account_compute_ds_subresource.go new file mode 100644 index 0000000..f6305ae --- /dev/null +++ b/internal/service/cloudbroker/account/account_compute_ds_subresource.go @@ -0,0 +1,119 @@ +/* +Copyright (c) 2019-2022 Digital Energy Cloud Solutions LLC. All Rights Reserved. +Authors: +Petr Krutov, +Stanislav Solovev, + +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. +*/ + +/* +Terraform DECORT provider - manage resources provided by DECORT (Digital Energy Cloud +Orchestration Technology) with Terraform by Hashicorp. + +Source code: https://github.com/rudecs/terraform-provider-decort + +Please see README.md to learn where to place source code so that it +builds seamlessly. + +Documentation: https://github.com/rudecs/terraform-provider-decort/wiki +*/ + +package account + +import "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" + +func dataSourceAccountComputeSchemaMake() map[string]*schema.Schema { + return map[string]*schema.Schema{ + "account_id": { + Type: schema.TypeInt, + Computed: true, + }, + "account_name": { + Type: schema.TypeString, + Computed: true, + }, + "cpus": { + Type: schema.TypeInt, + Computed: true, + }, + "created_by": { + Type: schema.TypeString, + Computed: true, + }, + "created_time": { + Type: schema.TypeInt, + Computed: true, + }, + "deleted_by": { + Type: schema.TypeString, + Computed: true, + }, + "deleted_time": { + Type: schema.TypeInt, + Computed: true, + }, + "compute_id": { + Type: schema.TypeInt, + Computed: true, + }, + "compute_name": { + Type: schema.TypeString, + Computed: true, + }, + "ram": { + Type: schema.TypeInt, + Computed: true, + }, + "registered": { + Type: schema.TypeBool, + Computed: true, + }, + "rg_id": { + Type: schema.TypeInt, + Computed: true, + }, + "rg_name": { + Type: schema.TypeString, + Computed: true, + }, + "status": { + Type: schema.TypeString, + Computed: true, + }, + "tech_status": { + Type: schema.TypeString, + Computed: true, + }, + "total_disks_size": { + Type: schema.TypeInt, + Computed: true, + }, + "updated_by": { + Type: schema.TypeString, + Computed: true, + }, + "updated_time": { + Type: schema.TypeInt, + Computed: true, + }, + "user_managed": { + Type: schema.TypeBool, + Computed: true, + }, + "vins_connected": { + Type: schema.TypeInt, + Computed: true, + }, + } +} diff --git a/internal/service/cloudbroker/account/account_disk_ds_subresource.go b/internal/service/cloudbroker/account/account_disk_ds_subresource.go new file mode 100644 index 0000000..049185c --- /dev/null +++ b/internal/service/cloudbroker/account/account_disk_ds_subresource.go @@ -0,0 +1,63 @@ +/* +Copyright (c) 2019-2022 Digital Energy Cloud Solutions LLC. All Rights Reserved. +Authors: +Petr Krutov, +Stanislav Solovev, + +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. +*/ + +/* +Terraform DECORT provider - manage resources provided by DECORT (Digital Energy Cloud +Orchestration Technology) with Terraform by Hashicorp. + +Source code: https://github.com/rudecs/terraform-provider-decort + +Please see README.md to learn where to place source code so that it +builds seamlessly. + +Documentation: https://github.com/rudecs/terraform-provider-decort/wiki +*/ + +package account + +import "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" + +func dataSourceAccountDiskSchemaMake() map[string]*schema.Schema { + return map[string]*schema.Schema{ + "disk_id": { + Type: schema.TypeInt, + Computed: true, + }, + "disk_name": { + Type: schema.TypeString, + Computed: true, + }, + "pool_name": { + Type: schema.TypeString, + Computed: true, + }, + "sep_id": { + Type: schema.TypeInt, + Computed: true, + }, + "size_max": { + Type: schema.TypeInt, + Computed: true, + }, + "type": { + Type: schema.TypeString, + Computed: true, + }, + } +} diff --git a/internal/service/cloudbroker/account/account_ds.go b/internal/service/cloudbroker/account/account_ds.go new file mode 100644 index 0000000..990db78 --- /dev/null +++ b/internal/service/cloudbroker/account/account_ds.go @@ -0,0 +1,262 @@ +/* +Copyright (c) 2019-2022 Digital Energy Cloud Solutions LLC. All Rights Reserved. +Authors: +Petr Krutov, +Stanislav Solovev, + +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. +*/ + +/* +Terraform DECORT provider - manage resources provided by DECORT (Digital Energy Cloud +Orchestration Technology) with Terraform by Hashicorp. + +Source code: https://github.com/rudecs/terraform-provider-decort + +Please see README.md to learn where to place source code so that it +builds seamlessly. + +Documentation: https://github.com/rudecs/terraform-provider-decort/wiki +*/ + +package account + +import "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" + +func dataSourceAccountSchemaMake() map[string]*schema.Schema { + res := map[string]*schema.Schema{ + "account_id": { + Type: schema.TypeInt, + Required: true, + }, + "dc_location": { + Type: schema.TypeString, + Computed: true, + }, + "resources": { + Type: schema.TypeList, + Computed: true, + Elem: &schema.Resource{ + Schema: map[string]*schema.Schema{ + "current": { + Type: schema.TypeList, + Computed: true, + Elem: &schema.Resource{ + Schema: map[string]*schema.Schema{ + "cpu": { + Type: schema.TypeInt, + Computed: true, + }, + "disksize": { + Type: schema.TypeInt, + Computed: true, + }, + "extips": { + Type: schema.TypeInt, + Computed: true, + }, + "exttraffic": { + Type: schema.TypeInt, + Computed: true, + }, + "gpu": { + Type: schema.TypeInt, + Computed: true, + }, + "ram": { + Type: schema.TypeInt, + Computed: true, + }, + }, + }, + }, + "reserved": { + Type: schema.TypeList, + Computed: true, + Elem: &schema.Resource{ + Schema: map[string]*schema.Schema{ + "cpu": { + Type: schema.TypeInt, + Computed: true, + }, + "disksize": { + Type: schema.TypeInt, + Computed: true, + }, + "extips": { + Type: schema.TypeInt, + Computed: true, + }, + "exttraffic": { + Type: schema.TypeInt, + Computed: true, + }, + "gpu": { + Type: schema.TypeInt, + Computed: true, + }, + "ram": { + Type: schema.TypeInt, + Computed: true, + }, + }, + }, + }, + }, + }, + }, + "ckey": { + Type: schema.TypeString, + Computed: true, + }, + "meta": { + Type: schema.TypeList, + Computed: true, + Elem: &schema.Schema{ + Type: schema.TypeString, + }, + }, + "acl": { + Type: schema.TypeList, + Computed: true, + Elem: &schema.Resource{ + Schema: map[string]*schema.Schema{ + "explicit": { + Type: schema.TypeBool, + Computed: true, + }, + "guid": { + Type: schema.TypeString, + Computed: true, + }, + "right": { + Type: schema.TypeString, + Computed: true, + }, + "status": { + Type: schema.TypeString, + Computed: true, + }, + "type": { + Type: schema.TypeString, + Computed: true, + }, + "user_group_id": { + Type: schema.TypeString, + Computed: true, + }, + }, + }, + }, + "company": { + Type: schema.TypeString, + Computed: true, + }, + "companyurl": { + Type: schema.TypeString, + Computed: true, + }, + "created_by": { + Type: schema.TypeString, + Computed: true, + }, + "created_time": { + Type: schema.TypeInt, + Computed: true, + }, + "deactivation_time": { + Type: schema.TypeFloat, + Computed: true, + }, + "deleted_by": { + Type: schema.TypeString, + Computed: true, + }, + "deleted_time": { + Type: schema.TypeInt, + Computed: true, + }, + "displayname": { + Type: schema.TypeString, + Computed: true, + }, + "guid": { + Type: schema.TypeInt, + Computed: true, + }, + "account_name": { + Type: schema.TypeString, + Computed: true, + }, + "resource_limits": { + Type: schema.TypeList, + Computed: true, + Elem: &schema.Resource{ + Schema: map[string]*schema.Schema{ + "cu_c": { + Type: schema.TypeFloat, + Computed: true, + }, + "cu_d": { + Type: schema.TypeFloat, + Computed: true, + }, + "cu_i": { + Type: schema.TypeFloat, + Computed: true, + }, + "cu_m": { + Type: schema.TypeFloat, + Computed: true, + }, + "cu_np": { + Type: schema.TypeFloat, + Computed: true, + }, + "gpu_units": { + Type: schema.TypeFloat, + Computed: true, + }, + }, + }, + }, + "send_access_emails": { + Type: schema.TypeBool, + Computed: true, + }, + "service_account": { + Type: schema.TypeBool, + Computed: true, + }, + "status": { + Type: schema.TypeString, + Computed: true, + }, + "updated_time": { + Type: schema.TypeInt, + Computed: true, + }, + "version": { + Type: schema.TypeInt, + Computed: true, + }, + "vins": { + Type: schema.TypeList, + Computed: true, + Elem: &schema.Schema{ + Type: schema.TypeInt, + }, + }, + } + return res +} diff --git a/internal/service/cloudbroker/account/account_fg_ds_subresource.go b/internal/service/cloudbroker/account/account_fg_ds_subresource.go new file mode 100644 index 0000000..28db8ee --- /dev/null +++ b/internal/service/cloudbroker/account/account_fg_ds_subresource.go @@ -0,0 +1,123 @@ +/* +Copyright (c) 2019-2022 Digital Energy Cloud Solutions LLC. All Rights Reserved. +Authors: +Petr Krutov, +Stanislav Solovev, + +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. +*/ + +/* +Terraform DECORT provider - manage resources provided by DECORT (Digital Energy Cloud +Orchestration Technology) with Terraform by Hashicorp. + +Source code: https://github.com/rudecs/terraform-provider-decort + +Please see README.md to learn where to place source code so that it +builds seamlessly. + +Documentation: https://github.com/rudecs/terraform-provider-decort/wiki +*/ + +package account + +import "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" + +func dataSourceAccountFlipGroupSchemaMake() map[string]*schema.Schema { + return map[string]*schema.Schema{ + "account_id": { + Type: schema.TypeInt, + Computed: true, + }, + "client_type": { + Type: schema.TypeString, + Computed: true, + }, + "conn_type": { + Type: schema.TypeString, + Computed: true, + }, + "created_by": { + Type: schema.TypeString, + Computed: true, + }, + "created_time": { + Type: schema.TypeInt, + Computed: true, + }, + "default_gw": { + Type: schema.TypeString, + Computed: true, + }, + "deleted_by": { + Type: schema.TypeString, + Computed: true, + }, + "deleted_time": { + Type: schema.TypeInt, + Computed: true, + }, + "desc": { + Type: schema.TypeString, + Computed: true, + }, + "gid": { + Type: schema.TypeInt, + Computed: true, + }, + "guid": { + Type: schema.TypeInt, + Computed: true, + }, + "fg_id": { + Type: schema.TypeInt, + Computed: true, + }, + "ip": { + Type: schema.TypeString, + Computed: true, + }, + "milestones": { + Type: schema.TypeInt, + Computed: true, + }, + "fg_name": { + Type: schema.TypeString, + Computed: true, + }, + "net_id": { + Type: schema.TypeInt, + Computed: true, + }, + "net_type": { + Type: schema.TypeString, + Computed: true, + }, + "netmask": { + Type: schema.TypeInt, + Computed: true, + }, + "status": { + Type: schema.TypeString, + Computed: true, + }, + "updated_by": { + Type: schema.TypeString, + Computed: true, + }, + "updated_time": { + Type: schema.TypeInt, + Computed: true, + }, + } +} diff --git a/internal/service/cloudbroker/account/account_item_ds_subresource.go b/internal/service/cloudbroker/account/account_item_ds_subresource.go new file mode 100644 index 0000000..9d7e809 --- /dev/null +++ b/internal/service/cloudbroker/account/account_item_ds_subresource.go @@ -0,0 +1,189 @@ +/* +Copyright (c) 2019-2022 Digital Energy Cloud Solutions LLC. All Rights Reserved. +Authors: +Petr Krutov, +Stanislav Solovev, + +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. +*/ + +/* +Terraform DECORT provider - manage resources provided by DECORT (Digital Energy Cloud +Orchestration Technology) with Terraform by Hashicorp. + +Source code: https://github.com/rudecs/terraform-provider-decort + +Please see README.md to learn where to place source code so that it +builds seamlessly. + +Documentation: https://github.com/rudecs/terraform-provider-decort/wiki +*/ + +package account + +import "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" + +func dataSourceAccountItemSchemaMake() map[string]*schema.Schema { + return map[string]*schema.Schema{ + "dc_location": { + Type: schema.TypeString, + Computed: true, + }, + "ckey": { + Type: schema.TypeString, + Computed: true, + }, + "meta": { + Type: schema.TypeList, + Computed: true, + Elem: &schema.Schema{ + Type: schema.TypeString, + }, + }, + "acl": { + Type: schema.TypeList, + Computed: true, + Elem: &schema.Resource{ + Schema: map[string]*schema.Schema{ + "explicit": { + Type: schema.TypeBool, + Computed: true, + }, + "guid": { + Type: schema.TypeString, + Computed: true, + }, + "right": { + Type: schema.TypeString, + Computed: true, + }, + "status": { + Type: schema.TypeString, + Computed: true, + }, + "type": { + Type: schema.TypeString, + Computed: true, + }, + "user_group_id": { + Type: schema.TypeString, + Computed: true, + }, + }, + }, + }, + "company": { + Type: schema.TypeString, + Computed: true, + }, + "companyurl": { + Type: schema.TypeString, + Computed: true, + }, + "created_by": { + Type: schema.TypeString, + Computed: true, + }, + "created_time": { + Type: schema.TypeInt, + Computed: true, + }, + "deactivation_time": { + Type: schema.TypeFloat, + Computed: true, + }, + "deleted_by": { + Type: schema.TypeString, + Computed: true, + }, + "deleted_time": { + Type: schema.TypeInt, + Computed: true, + }, + "displayname": { + Type: schema.TypeString, + Computed: true, + }, + "guid": { + Type: schema.TypeInt, + Computed: true, + }, + "account_id": { + Type: schema.TypeInt, + Computed: true, + }, + "account_name": { + Type: schema.TypeString, + Computed: true, + }, + "resource_limits": { + Type: schema.TypeList, + Computed: true, + Elem: &schema.Resource{ + Schema: map[string]*schema.Schema{ + "cu_c": { + Type: schema.TypeFloat, + Computed: true, + }, + "cu_d": { + Type: schema.TypeFloat, + Computed: true, + }, + "cu_i": { + Type: schema.TypeFloat, + Computed: true, + }, + "cu_m": { + Type: schema.TypeFloat, + Computed: true, + }, + "cu_np": { + Type: schema.TypeFloat, + Computed: true, + }, + "gpu_units": { + Type: schema.TypeFloat, + Computed: true, + }, + }, + }, + }, + "send_access_emails": { + Type: schema.TypeBool, + Computed: true, + }, + "service_account": { + Type: schema.TypeBool, + Computed: true, + }, + "status": { + Type: schema.TypeString, + Computed: true, + }, + "updated_time": { + Type: schema.TypeInt, + Computed: true, + }, + "version": { + Type: schema.TypeInt, + Computed: true, + }, + "vins": { + Type: schema.TypeList, + Computed: true, + Elem: &schema.Schema{ + Type: schema.TypeInt, + }, + }, + } +} diff --git a/internal/service/cloudbroker/account/account_rg_ds_subresource.go b/internal/service/cloudbroker/account/account_rg_ds_subresource.go new file mode 100644 index 0000000..389a663 --- /dev/null +++ b/internal/service/cloudbroker/account/account_rg_ds_subresource.go @@ -0,0 +1,205 @@ +/* +Copyright (c) 2019-2022 Digital Energy Cloud Solutions LLC. All Rights Reserved. +Authors: +Petr Krutov, +Stanislav Solovev, + +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. +*/ + +/* +Terraform DECORT provider - manage resources provided by DECORT (Digital Energy Cloud +Orchestration Technology) with Terraform by Hashicorp. + +Source code: https://github.com/rudecs/terraform-provider-decort + +Please see README.md to learn where to place source code so that it +builds seamlessly. + +Documentation: https://github.com/rudecs/terraform-provider-decort/wiki +*/ + +package account + +import "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" + +func dataSourceAccountRGSchemaMake() map[string]*schema.Schema { + return map[string]*schema.Schema{ + "computes": { + Type: schema.TypeList, + Computed: true, + Elem: &schema.Resource{ + Schema: map[string]*schema.Schema{ + "started": { + Type: schema.TypeInt, + Computed: true, + }, + "stopped": { + Type: schema.TypeInt, + Computed: true, + }, + }, + }, + }, + "resources": { + Type: schema.TypeList, + Computed: true, + Elem: &schema.Resource{ + Schema: map[string]*schema.Schema{ + "consumed": { + Type: schema.TypeList, + Computed: true, + Elem: &schema.Resource{ + Schema: map[string]*schema.Schema{ + "cpu": { + Type: schema.TypeInt, + Computed: true, + }, + "disksize": { + Type: schema.TypeInt, + Computed: true, + }, + "extips": { + Type: schema.TypeInt, + Computed: true, + }, + "exttraffic": { + Type: schema.TypeInt, + Computed: true, + }, + "gpu": { + Type: schema.TypeInt, + Computed: true, + }, + "ram": { + Type: schema.TypeInt, + Computed: true, + }, + }, + }, + }, + + "limits": { + Type: schema.TypeList, + Computed: true, + Elem: &schema.Resource{ + Schema: map[string]*schema.Schema{ + "cpu": { + Type: schema.TypeInt, + Computed: true, + }, + "disksize": { + Type: schema.TypeInt, + Computed: true, + }, + "extips": { + Type: schema.TypeInt, + Computed: true, + }, + "exttraffic": { + Type: schema.TypeInt, + Computed: true, + }, + "gpu": { + Type: schema.TypeInt, + Computed: true, + }, + "ram": { + Type: schema.TypeInt, + Computed: true, + }, + }, + }, + }, + "reserved": { + Type: schema.TypeList, + Computed: true, + Elem: &schema.Resource{ + Schema: map[string]*schema.Schema{ + "cpu": { + Type: schema.TypeInt, + Computed: true, + }, + "disksize": { + Type: schema.TypeInt, + Computed: true, + }, + "extips": { + Type: schema.TypeInt, + Computed: true, + }, + "exttraffic": { + Type: schema.TypeInt, + Computed: true, + }, + "gpu": { + Type: schema.TypeInt, + Computed: true, + }, + "ram": { + Type: schema.TypeInt, + Computed: true, + }, + }, + }, + }, + }, + }, + }, + + "created_by": { + Type: schema.TypeString, + Computed: true, + }, + "created_time": { + Type: schema.TypeInt, + Computed: true, + }, + "deleted_by": { + Type: schema.TypeString, + Computed: true, + }, + "deleted_time": { + Type: schema.TypeInt, + Computed: true, + }, + "rg_id": { + Type: schema.TypeInt, + Computed: true, + }, + "milestones": { + Type: schema.TypeInt, + Computed: true, + }, + "rg_name": { + Type: schema.TypeString, + Computed: true, + }, + "status": { + Type: schema.TypeString, + Computed: true, + }, + "updated_by": { + Type: schema.TypeString, + Computed: true, + }, + "updated_time": { + Type: schema.TypeInt, + Computed: true, + }, + "vinses": { + Type: schema.TypeInt, + Computed: true, + }, + } +} diff --git a/internal/service/cloudbroker/account/account_rs.go b/internal/service/cloudbroker/account/account_rs.go new file mode 100644 index 0000000..1ee4115 --- /dev/null +++ b/internal/service/cloudbroker/account/account_rs.go @@ -0,0 +1,320 @@ +/* +Copyright (c) 2019-2022 Digital Energy Cloud Solutions LLC. All Rights Reserved. +Authors: +Petr Krutov, +Stanislav Solovev, + +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. +*/ + +/* +Terraform DECORT provider - manage resources provided by DECORT (Digital Energy Cloud +Orchestration Technology) with Terraform by Hashicorp. + +Source code: https://github.com/rudecs/terraform-provider-decort + +Please see README.md to learn where to place source code so that it +builds seamlessly. + +Documentation: https://github.com/rudecs/terraform-provider-decort/wiki +*/ + +package account + +import "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" + +func resourceAccountSchemaMake() map[string]*schema.Schema { + return map[string]*schema.Schema{ + "account_name": { + Type: schema.TypeString, + Required: true, + Description: "account name", + }, + "username": { + Type: schema.TypeString, + Required: true, + Description: "username of owner the account", + }, + "emailaddress": { + Type: schema.TypeString, + Optional: true, + Description: "email", + }, + "send_access_emails": { + Type: schema.TypeBool, + Optional: true, + Default: true, + Description: "if true send emails when a user is granted access to resources", + }, + "users": { + Type: schema.TypeList, + Optional: true, + Elem: &schema.Resource{ + Schema: map[string]*schema.Schema{ + "user_id": { + Type: schema.TypeString, + Required: true, + }, + "access_type": { + Type: schema.TypeString, + Required: true, + }, + "recursive_delete": { + Type: schema.TypeBool, + Optional: true, + Default: false, + }, + }, + }, + }, + "restore": { + Type: schema.TypeBool, + Optional: true, + Description: "restore a deleted account", + }, + "permanently": { + Type: schema.TypeBool, + Optional: true, + Default: false, + Description: "whether to completely delete the account", + }, + "enable": { + Type: schema.TypeBool, + Optional: true, + Description: "enable/disable account", + }, + "resource_limits": { + Type: schema.TypeList, + Optional: true, + Computed: true, + MaxItems: 1, + Elem: &schema.Resource{ + Schema: map[string]*schema.Schema{ + "cu_c": { + Type: schema.TypeFloat, + Optional: true, + Computed: true, + }, + "cu_d": { + Type: schema.TypeFloat, + Optional: true, + Computed: true, + }, + "cu_i": { + Type: schema.TypeFloat, + Optional: true, + Computed: true, + }, + "cu_m": { + Type: schema.TypeFloat, + Optional: true, + Computed: true, + }, + "cu_np": { + Type: schema.TypeFloat, + Optional: true, + Computed: true, + }, + "gpu_units": { + Type: schema.TypeFloat, + Optional: true, + Computed: true, + }, + }, + }, + }, + "account_id": { + Type: schema.TypeInt, + Optional: true, + Computed: true, + }, + "dc_location": { + Type: schema.TypeString, + Computed: true, + }, + "resources": { + Type: schema.TypeList, + Computed: true, + Elem: &schema.Resource{ + Schema: map[string]*schema.Schema{ + "current": { + Type: schema.TypeList, + Computed: true, + Elem: &schema.Resource{ + Schema: map[string]*schema.Schema{ + "cpu": { + Type: schema.TypeInt, + Computed: true, + }, + "disksize": { + Type: schema.TypeInt, + Computed: true, + }, + "extips": { + Type: schema.TypeInt, + Computed: true, + }, + "exttraffic": { + Type: schema.TypeInt, + Computed: true, + }, + "gpu": { + Type: schema.TypeInt, + Computed: true, + }, + "ram": { + Type: schema.TypeInt, + Computed: true, + }, + }, + }, + }, + "reserved": { + Type: schema.TypeList, + Computed: true, + Elem: &schema.Resource{ + Schema: map[string]*schema.Schema{ + "cpu": { + Type: schema.TypeInt, + Computed: true, + }, + "disksize": { + Type: schema.TypeInt, + Computed: true, + }, + "extips": { + Type: schema.TypeInt, + Computed: true, + }, + "exttraffic": { + Type: schema.TypeInt, + Computed: true, + }, + "gpu": { + Type: schema.TypeInt, + Computed: true, + }, + "ram": { + Type: schema.TypeInt, + Computed: true, + }, + }, + }, + }, + }, + }, + }, + "ckey": { + Type: schema.TypeString, + Computed: true, + }, + "meta": { + Type: schema.TypeList, + Computed: true, + Elem: &schema.Schema{ + Type: schema.TypeString, + }, + }, + "acl": { + Type: schema.TypeList, + Computed: true, + Elem: &schema.Resource{ + Schema: map[string]*schema.Schema{ + "explicit": { + Type: schema.TypeBool, + Computed: true, + }, + "guid": { + Type: schema.TypeString, + Computed: true, + }, + "right": { + Type: schema.TypeString, + Computed: true, + }, + "status": { + Type: schema.TypeString, + Computed: true, + }, + "type": { + Type: schema.TypeString, + Computed: true, + }, + "user_group_id": { + Type: schema.TypeString, + Computed: true, + }, + }, + }, + }, + "company": { + Type: schema.TypeString, + Computed: true, + }, + "companyurl": { + Type: schema.TypeString, + Computed: true, + }, + "created_by": { + Type: schema.TypeString, + Computed: true, + }, + "created_time": { + Type: schema.TypeInt, + Computed: true, + }, + "deactivation_time": { + Type: schema.TypeFloat, + Computed: true, + }, + "deleted_by": { + Type: schema.TypeString, + Computed: true, + }, + "deleted_time": { + Type: schema.TypeInt, + Computed: true, + }, + "displayname": { + Type: schema.TypeString, + Computed: true, + }, + "guid": { + Type: schema.TypeInt, + Computed: true, + }, + "service_account": { + Type: schema.TypeBool, + Computed: true, + }, + "status": { + Type: schema.TypeString, + Computed: true, + }, + "updated_time": { + Type: schema.TypeInt, + Computed: true, + }, + "version": { + Type: schema.TypeInt, + Computed: true, + }, + "vins": { + Type: schema.TypeList, + Computed: true, + Elem: &schema.Schema{ + Type: schema.TypeInt, + }, + }, + } +} diff --git a/internal/service/cloudbroker/account/account_vins_ds_subresource.go b/internal/service/cloudbroker/account/account_vins_ds_subresource.go new file mode 100644 index 0000000..4032aad --- /dev/null +++ b/internal/service/cloudbroker/account/account_vins_ds_subresource.go @@ -0,0 +1,107 @@ +/* +Copyright (c) 2019-2022 Digital Energy Cloud Solutions LLC. All Rights Reserved. +Authors: +Petr Krutov, +Stanislav Solovev, + +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. +*/ + +/* +Terraform DECORT provider - manage resources provided by DECORT (Digital Energy Cloud +Orchestration Technology) with Terraform by Hashicorp. + +Source code: https://github.com/rudecs/terraform-provider-decort + +Please see README.md to learn where to place source code so that it +builds seamlessly. + +Documentation: https://github.com/rudecs/terraform-provider-decort/wiki +*/ + +package account + +import "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" + +func dataSourceAccountVinsSchema() map[string]*schema.Schema { + return map[string]*schema.Schema{ + "account_id": { + Type: schema.TypeInt, + Computed: true, + }, + "account_name": { + Type: schema.TypeString, + Computed: true, + }, + "computes": { + Type: schema.TypeInt, + Computed: true, + }, + "created_by": { + Type: schema.TypeString, + Computed: true, + }, + "created_time": { + Type: schema.TypeInt, + Computed: true, + }, + "deleted_by": { + Type: schema.TypeString, + Computed: true, + }, + "deleted_time": { + Type: schema.TypeInt, + Computed: true, + }, + "external_ip": { + Type: schema.TypeString, + Computed: true, + }, + "vin_id": { + Type: schema.TypeInt, + Computed: true, + }, + "vin_name": { + Type: schema.TypeString, + Computed: true, + }, + "network": { + Type: schema.TypeString, + Computed: true, + }, + "pri_vnf_dev_id": { + Type: schema.TypeInt, + Computed: true, + }, + "rg_id": { + Type: schema.TypeInt, + Computed: true, + }, + "rg_name": { + Type: schema.TypeString, + Computed: true, + }, + "status": { + Type: schema.TypeString, + Computed: true, + }, + "updated_by": { + Type: schema.TypeString, + Computed: true, + }, + "updated_time": { + Type: schema.TypeInt, + Computed: true, + }, + } +} diff --git a/internal/service/cloudbroker/account/api.go b/internal/service/cloudbroker/account/api.go new file mode 100644 index 0000000..3ed17ed --- /dev/null +++ b/internal/service/cloudbroker/account/api.go @@ -0,0 +1,54 @@ +/* +Copyright (c) 2019-2022 Digital Energy Cloud Solutions LLC. All Rights Reserved. +Authors: +Petr Krutov, +Stanislav Solovev, + +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. +*/ + +/* +Terraform DECORT provider - manage resources provided by DECORT (Digital Energy Cloud +Orchestration Technology) with Terraform by Hashicorp. + +Source code: https://github.com/rudecs/terraform-provider-decort + +Please see README.md to learn where to place source code so that it +builds seamlessly. + +Documentation: https://github.com/rudecs/terraform-provider-decort/wiki +*/ + +package account + +const accountAddUserAPI = "/restmachine/cloudbroker/account/addUser" +const accountAuditsAPI = "/restmachine/cloudbroker/account/audits" +const accountCreateAPI = "/restmachine/cloudbroker/account/create" +const accountDeleteAPI = "/restmachine/cloudbroker/account/delete" +const accountDeleteUserAPI = "/restmachine/cloudbroker/account/deleteUser" +const accountDisableAPI = "/restmachine/cloudbroker/account/disable" +const accountEnableAPI = "/restmachine/cloudbroker/account/enable" +const accountGetAPI = "/restmachine/cloudbroker/account/get" +const accountListAPI = "/restmachine/cloudbroker/account/list" +const accountListComputesAPI = "/restmachine/cloudbroker/account/listComputes" +const accountListDeletedAPI = "/restmachine/cloudbroker/account/listDeleted" +const accountListDisksAPI = "/restmachine/cloudbroker/account/listDisks" +const accountListFlipGroupsAPI = "/restmachine/cloudbroker/account/listFlipGroups" +const accountListRGAPI = "/restmachine/cloudbroker/account/listRG" +const accountListVinsAPI = "/restmachine/cloudbroker/account/listVins" +const accountRestoreAPI = "/restmachine/cloudbroker/account/restore" +const accountUpdateAPI = "/restmachine/cloudbroker/account/update" +const accountUpdateUserAPI = "/restmachine/cloudbroker/account/updateUser" +const accountsEnableAPI = "/restmachine/cloudbroker/account/enableAccounts" +const accountsDisableAPI = "/restmachine/cloudbroker/account/disableAccounts" +const accountsDeleteAPI = "/restmachine/cloudbroker/account/deleteAccounts" diff --git a/internal/service/cloudbroker/account/data_source_account.go b/internal/service/cloudbroker/account/data_source_account.go new file mode 100644 index 0000000..7bf5ce8 --- /dev/null +++ b/internal/service/cloudbroker/account/data_source_account.go @@ -0,0 +1,108 @@ +/* +Copyright (c) 2019-2022 Digital Energy Cloud Solutions LLC. All Rights Reserved. +Authors: +Petr Krutov, +Stanislav Solovev, + +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. +*/ + +/* +Terraform DECORT provider - manage resources provided by DECORT (Digital Energy Cloud +Orchestration Technology) with Terraform by Hashicorp. + +Source code: https://github.com/rudecs/terraform-provider-decort + +Please see README.md to learn where to place source code so that it +builds seamlessly. + +Documentation: https://github.com/rudecs/terraform-provider-decort/wiki +*/ + +package account + +import ( + "context" + + "github.com/google/uuid" + "github.com/hashicorp/terraform-plugin-sdk/v2/diag" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" + "github.com/rudecs/terraform-provider-decort/internal/constants" + "github.com/rudecs/terraform-provider-decort/internal/flattens" +) + +func dataSourceAccountRead(ctx context.Context, d *schema.ResourceData, m interface{}) diag.Diagnostics { + acc, err := utilityAccountCheckPresence(ctx, d, m) + if err != nil { + return diag.FromErr(err) + } + + id := uuid.New() + d.SetId(id.String()) + d.Set("dc_location", acc.DCLocation) + d.Set("resources", flattenAccResources(acc.Resources)) + d.Set("ckey", acc.CKey) + d.Set("meta", flattens.FlattenMeta(acc.Meta)) + d.Set("acl", flattenAccAcl(acc.Acl)) + d.Set("company", acc.Company) + d.Set("companyurl", acc.CompanyUrl) + d.Set("created_by", acc.CreatedBy) + d.Set("created_time", acc.CreatedTime) + d.Set("deactivation_time", acc.DeactiovationTime) + d.Set("deleted_by", acc.DeletedBy) + d.Set("deleted_time", acc.DeletedTime) + d.Set("displayname", acc.DisplayName) + d.Set("guid", acc.GUID) + d.Set("account_id", acc.ID) + d.Set("account_name", acc.Name) + d.Set("resource_limits", flattenRgResourceLimits(acc.ResourceLimits)) + d.Set("send_access_emails", acc.SendAccessEmails) + d.Set("service_account", acc.ServiceAccount) + d.Set("status", acc.Status) + d.Set("updated_time", acc.UpdatedTime) + d.Set("version", acc.Version) + d.Set("vins", acc.Vins) + + return nil +} + +func flattenAccAcl(acls []AccountAclRecord) []map[string]interface{} { + res := make([]map[string]interface{}, 0) + for _, acls := range acls { + temp := map[string]interface{}{ + "explicit": acls.IsExplicit, + "guid": acls.Guid, + "right": acls.Rights, + "status": acls.Status, + "type": acls.Type, + "user_group_id": acls.UgroupID, + } + res = append(res, temp) + } + return res +} + +func DataSourceAccount() *schema.Resource { + return &schema.Resource{ + SchemaVersion: 1, + + ReadContext: dataSourceAccountRead, + + Timeouts: &schema.ResourceTimeout{ + Read: &constants.Timeout30s, + Default: &constants.Timeout60s, + }, + + Schema: dataSourceAccountSchemaMake(), + } +} diff --git a/internal/service/cloudbroker/account/data_source_account_audits_list.go b/internal/service/cloudbroker/account/data_source_account_audits_list.go new file mode 100644 index 0000000..ccaaead --- /dev/null +++ b/internal/service/cloudbroker/account/data_source_account_audits_list.go @@ -0,0 +1,104 @@ +/* +Copyright (c) 2019-2022 Digital Energy Cloud Solutions LLC. All Rights Reserved. +Authors: +Petr Krutov, +Stanislav Solovev, + +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. +*/ + +/* +Terraform DECORT provider - manage resources provided by DECORT (Digital Energy Cloud +Orchestration Technology) with Terraform by Hashicorp. + +Source code: https://github.com/rudecs/terraform-provider-decort + +Please see README.md to learn where to place source code so that it +builds seamlessly. + +Documentation: https://github.com/rudecs/terraform-provider-decort/wiki +*/ + +package account + +import ( + "context" + + "github.com/google/uuid" + "github.com/hashicorp/terraform-plugin-sdk/v2/diag" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" + "github.com/rudecs/terraform-provider-decort/internal/constants" +) + +func flattenAccountAuditsList(aal AccountAuditsList) []map[string]interface{} { + res := make([]map[string]interface{}, 0) + for _, aa := range aal { + temp := map[string]interface{}{ + "call": aa.Call, + "responsetime": aa.ResponseTime, + "statuscode": aa.StatusCode, + "timestamp": aa.Timestamp, + "user": aa.User, + } + res = append(res, temp) + } + return res + +} + +func dataSourceAccountAuditsListRead(ctx context.Context, d *schema.ResourceData, m interface{}) diag.Diagnostics { + accountAuditsList, err := utilityAccountAuditsListCheckPresence(ctx, d, m) + if err != nil { + return diag.FromErr(err) + } + + id := uuid.New() + d.SetId(id.String()) + d.Set("items", flattenAccountAuditsList(accountAuditsList)) + + return nil +} + +func dataSourceAccountAuditsListSchemaMake() map[string]*schema.Schema { + res := map[string]*schema.Schema{ + "account_id": { + Type: schema.TypeInt, + Required: true, + Description: "ID of the account", + }, + "items": { + Type: schema.TypeList, + Computed: true, + Description: "Search Result", + Elem: &schema.Resource{ + Schema: dataSourceAccountAuditSchemaMake(), + }, + }, + } + return res +} + +func DataSourceAccountAuditsList() *schema.Resource { + return &schema.Resource{ + SchemaVersion: 1, + + ReadContext: dataSourceAccountAuditsListRead, + + Timeouts: &schema.ResourceTimeout{ + Read: &constants.Timeout30s, + Default: &constants.Timeout60s, + }, + + Schema: dataSourceAccountAuditsListSchemaMake(), + } +} diff --git a/internal/service/cloudbroker/account/data_source_account_computes_list.go b/internal/service/cloudbroker/account/data_source_account_computes_list.go new file mode 100644 index 0000000..e181095 --- /dev/null +++ b/internal/service/cloudbroker/account/data_source_account_computes_list.go @@ -0,0 +1,119 @@ +/* +Copyright (c) 2019-2022 Digital Energy Cloud Solutions LLC. All Rights Reserved. +Authors: +Petr Krutov, +Stanislav Solovev, + +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. +*/ + +/* +Terraform DECORT provider - manage resources provided by DECORT (Digital Energy Cloud +Orchestration Technology) with Terraform by Hashicorp. + +Source code: https://github.com/rudecs/terraform-provider-decort + +Please see README.md to learn where to place source code so that it +builds seamlessly. + +Documentation: https://github.com/rudecs/terraform-provider-decort/wiki +*/ + +package account + +import ( + "context" + + "github.com/google/uuid" + "github.com/hashicorp/terraform-plugin-sdk/v2/diag" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" + "github.com/rudecs/terraform-provider-decort/internal/constants" +) + +func flattenAccountComputesList(acl AccountComputesList) []map[string]interface{} { + res := make([]map[string]interface{}, 0) + for _, acc := range acl { + temp := map[string]interface{}{ + "account_id": acc.AccountId, + "account_name": acc.AccountName, + "cpus": acc.CPUs, + "created_by": acc.CreatedBy, + "created_time": acc.CreatedTime, + "deleted_by": acc.DeletedBy, + "deleted_time": acc.DeletedTime, + "compute_id": acc.ComputeId, + "compute_name": acc.ComputeName, + "ram": acc.RAM, + "registered": acc.Registered, + "rg_id": acc.RgId, + "rg_name": acc.RgName, + "status": acc.Status, + "tech_status": acc.TechStatus, + "total_disks_size": acc.TotalDisksSize, + "updated_by": acc.UpdatedBy, + "updated_time": acc.UpdatedTime, + "user_managed": acc.UserManaged, + "vins_connected": acc.VinsConnected, + } + res = append(res, temp) + } + return res + +} + +func dataSourceAccountComputesListRead(ctx context.Context, d *schema.ResourceData, m interface{}) diag.Diagnostics { + accountComputesList, err := utilityAccountComputesListCheckPresence(ctx, d, m) + if err != nil { + return diag.FromErr(err) + } + + id := uuid.New() + d.SetId(id.String()) + d.Set("items", flattenAccountComputesList(accountComputesList)) + + return nil +} + +func dataSourceAccountComputesListSchemaMake() map[string]*schema.Schema { + res := map[string]*schema.Schema{ + "account_id": { + Type: schema.TypeInt, + Required: true, + Description: "ID of the account", + }, + "items": { + Type: schema.TypeList, + Computed: true, + Description: "Search Result", + Elem: &schema.Resource{ + Schema: dataSourceAccountComputeSchemaMake(), + }, + }, + } + return res +} + +func DataSourceAccountComputesList() *schema.Resource { + return &schema.Resource{ + SchemaVersion: 1, + + ReadContext: dataSourceAccountComputesListRead, + + Timeouts: &schema.ResourceTimeout{ + Read: &constants.Timeout30s, + Default: &constants.Timeout60s, + }, + + Schema: dataSourceAccountComputesListSchemaMake(), + } +} diff --git a/internal/service/cloudbroker/account/data_source_account_deleted_list.go b/internal/service/cloudbroker/account/data_source_account_deleted_list.go new file mode 100644 index 0000000..04120b4 --- /dev/null +++ b/internal/service/cloudbroker/account/data_source_account_deleted_list.go @@ -0,0 +1,69 @@ +/* +Copyright (c) 2019-2022 Digital Energy Cloud Solutions LLC. All Rights Reserved. +Authors: +Petr Krutov, +Stanislav Solovev, + +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. +*/ + +/* +Terraform DECORT provider - manage resources provided by DECORT (Digital Energy Cloud +Orchestration Technology) with Terraform by Hashicorp. + +Source code: https://github.com/rudecs/terraform-provider-decort + +Please see README.md to learn where to place source code so that it +builds seamlessly. + +Documentation: https://github.com/rudecs/terraform-provider-decort/wiki +*/ + +package account + +import ( + "context" + + "github.com/google/uuid" + "github.com/hashicorp/terraform-plugin-sdk/v2/diag" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" + "github.com/rudecs/terraform-provider-decort/internal/constants" +) + +func dataSourceAccountDeletedListRead(ctx context.Context, d *schema.ResourceData, m interface{}) diag.Diagnostics { + accountDeletedList, err := utilityAccountDeletedListCheckPresence(ctx, d, m) + if err != nil { + return diag.FromErr(err) + } + + id := uuid.New() + d.SetId(id.String()) + d.Set("items", flattenAccountList(accountDeletedList)) + + return nil +} + +func DataSourceAccountDeletedList() *schema.Resource { + return &schema.Resource{ + SchemaVersion: 1, + + ReadContext: dataSourceAccountDeletedListRead, + + Timeouts: &schema.ResourceTimeout{ + Read: &constants.Timeout30s, + Default: &constants.Timeout60s, + }, + + Schema: dataSourceAccountListSchemaMake(), + } +} diff --git a/internal/service/cloudbroker/account/data_source_account_disks_list.go b/internal/service/cloudbroker/account/data_source_account_disks_list.go new file mode 100644 index 0000000..b823e9a --- /dev/null +++ b/internal/service/cloudbroker/account/data_source_account_disks_list.go @@ -0,0 +1,104 @@ +/* +Copyright (c) 2019-2022 Digital Energy Cloud Solutions LLC. All Rights Reserved. +Authors: +Petr Krutov, +Stanislav Solovev, + +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. +*/ + +/* +Terraform DECORT provider - manage resources provided by DECORT (Digital Energy Cloud +Orchestration Technology) with Terraform by Hashicorp. + +Source code: https://github.com/rudecs/terraform-provider-decort + +Please see README.md to learn where to place source code so that it +builds seamlessly. + +Documentation: https://github.com/rudecs/terraform-provider-decort/wiki +*/ +package account + +import ( + "context" + + "github.com/google/uuid" + "github.com/hashicorp/terraform-plugin-sdk/v2/diag" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" + "github.com/rudecs/terraform-provider-decort/internal/constants" +) + +func flattenAccountDisksList(adl AccountDisksList) []map[string]interface{} { + res := make([]map[string]interface{}, 0) + for _, ad := range adl { + temp := map[string]interface{}{ + "disk_id": ad.ID, + "disk_name": ad.Name, + "pool_name": ad.Pool, + "sep_id": ad.SepId, + "size_max": ad.SizeMax, + "type": ad.Type, + } + res = append(res, temp) + } + return res + +} + +func dataSourceAccountDisksListRead(ctx context.Context, d *schema.ResourceData, m interface{}) diag.Diagnostics { + accountDisksList, err := utilityAccountDisksListCheckPresence(ctx, d, m) + if err != nil { + return diag.FromErr(err) + } + + id := uuid.New() + d.SetId(id.String()) + d.Set("items", flattenAccountDisksList(accountDisksList)) + + return nil +} + +func dataSourceAccountDisksListSchemaMake() map[string]*schema.Schema { + res := map[string]*schema.Schema{ + "account_id": { + Type: schema.TypeInt, + Required: true, + Description: "ID of the account", + }, + "items": { + Type: schema.TypeList, + Computed: true, + Description: "Search Result", + Elem: &schema.Resource{ + Schema: dataSourceAccountDiskSchemaMake(), + }, + }, + } + return res +} + +func DataSourceAccountDisksList() *schema.Resource { + return &schema.Resource{ + SchemaVersion: 1, + + ReadContext: dataSourceAccountDisksListRead, + + Timeouts: &schema.ResourceTimeout{ + Read: &constants.Timeout30s, + Default: &constants.Timeout60s, + }, + + Schema: dataSourceAccountDisksListSchemaMake(), + } +} diff --git a/internal/service/cloudbroker/account/data_source_account_flipgroups_list.go b/internal/service/cloudbroker/account/data_source_account_flipgroups_list.go new file mode 100644 index 0000000..4a318b2 --- /dev/null +++ b/internal/service/cloudbroker/account/data_source_account_flipgroups_list.go @@ -0,0 +1,120 @@ +/* +Copyright (c) 2019-2022 Digital Energy Cloud Solutions LLC. All Rights Reserved. +Authors: +Petr Krutov, +Stanislav Solovev, + +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. +*/ + +/* +Terraform DECORT provider - manage resources provided by DECORT (Digital Energy Cloud +Orchestration Technology) with Terraform by Hashicorp. + +Source code: https://github.com/rudecs/terraform-provider-decort + +Please see README.md to learn where to place source code so that it +builds seamlessly. + +Documentation: https://github.com/rudecs/terraform-provider-decort/wiki +*/ + +package account + +import ( + "context" + + "github.com/google/uuid" + "github.com/hashicorp/terraform-plugin-sdk/v2/diag" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" + "github.com/rudecs/terraform-provider-decort/internal/constants" +) + +func flattenAccountFlipGroupsList(afgl AccountFlipGroupsList) []map[string]interface{} { + res := make([]map[string]interface{}, 0) + for _, afg := range afgl { + temp := map[string]interface{}{ + "account_id": afg.AccountId, + "client_type": afg.ClientType, + "conn_type": afg.ConnType, + "created_by": afg.CreatedBy, + "created_time": afg.CreatedTime, + "default_gw": afg.DefaultGW, + "deleted_by": afg.DeletedBy, + "deleted_time": afg.DeletedTime, + "desc": afg.Desc, + "gid": afg.GID, + "guid": afg.GUID, + "fg_id": afg.ID, + "ip": afg.IP, + "milestones": afg.Milestones, + "fg_name": afg.Name, + "net_id": afg.NetID, + "net_type": afg.NetType, + "netmask": afg.NetMask, + "status": afg.Status, + "updated_by": afg.UpdatedBy, + "updated_time": afg.UpdatedTime, + } + res = append(res, temp) + } + return res + +} + +func dataSourceAccountFlipGroupsListRead(ctx context.Context, d *schema.ResourceData, m interface{}) diag.Diagnostics { + accountFlipGroupsList, err := utilityAccountFlipGroupsListCheckPresence(ctx, d, m) + if err != nil { + return diag.FromErr(err) + } + + id := uuid.New() + d.SetId(id.String()) + d.Set("items", flattenAccountFlipGroupsList(accountFlipGroupsList)) + + return nil +} + +func dataSourceAccountFlipGroupsListSchemaMake() map[string]*schema.Schema { + res := map[string]*schema.Schema{ + "account_id": { + Type: schema.TypeInt, + Required: true, + Description: "ID of the account", + }, + "items": { + Type: schema.TypeList, + Computed: true, + Description: "Search Result", + Elem: &schema.Resource{ + Schema: dataSourceAccountFlipGroupSchemaMake(), + }, + }, + } + return res +} + +func DataSourceAccountFlipGroupsList() *schema.Resource { + return &schema.Resource{ + SchemaVersion: 1, + + ReadContext: dataSourceAccountFlipGroupsListRead, + + Timeouts: &schema.ResourceTimeout{ + Read: &constants.Timeout30s, + Default: &constants.Timeout60s, + }, + + Schema: dataSourceAccountFlipGroupsListSchemaMake(), + } +} diff --git a/internal/service/cloudbroker/account/data_source_account_list.go b/internal/service/cloudbroker/account/data_source_account_list.go new file mode 100644 index 0000000..c733c12 --- /dev/null +++ b/internal/service/cloudbroker/account/data_source_account_list.go @@ -0,0 +1,167 @@ +/* +Copyright (c) 2019-2022 Digital Energy Cloud Solutions LLC. All Rights Reserved. +Authors: +Petr Krutov, +Stanislav Solovev, + +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. +*/ + +/* +Terraform DECORT provider - manage resources provided by DECORT (Digital Energy Cloud +Orchestration Technology) with Terraform by Hashicorp. + +Source code: https://github.com/rudecs/terraform-provider-decort + +Please see README.md to learn where to place source code so that it +builds seamlessly. + +Documentation: https://github.com/rudecs/terraform-provider-decort/wiki +*/ + +package account + +import ( + "context" + + "github.com/google/uuid" + "github.com/hashicorp/terraform-plugin-sdk/v2/diag" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" + "github.com/rudecs/terraform-provider-decort/internal/constants" + "github.com/rudecs/terraform-provider-decort/internal/flattens" +) + +func flattenRgAcl(rgAcls []AccountAclRecord) []map[string]interface{} { + res := make([]map[string]interface{}, 0) + for _, rgAcl := range rgAcls { + temp := map[string]interface{}{ + "explicit": rgAcl.IsExplicit, + "guid": rgAcl.Guid, + "right": rgAcl.Rights, + "status": rgAcl.Status, + "type": rgAcl.Type, + "user_group_id": rgAcl.UgroupID, + } + res = append(res, temp) + } + return res +} + +func flattenAccountList(al AccountList) []map[string]interface{} { + res := make([]map[string]interface{}, 0) + for _, acc := range al { + temp := map[string]interface{}{ + "dc_location": acc.DCLocation, + "ckey": acc.CKey, + "meta": flattens.FlattenMeta(acc.Meta), + + "acl": flattenRgAcl(acc.Acl), + + "company": acc.Company, + "companyurl": acc.CompanyUrl, + "created_by": acc.CreatedBy, + + "created_time": acc.CreatedTime, + + "deactivation_time": acc.DeactiovationTime, + "deleted_by": acc.DeletedBy, + + "deleted_time": acc.DeletedTime, + + "displayname": acc.DisplayName, + "guid": acc.GUID, + + "account_id": acc.ID, + "account_name": acc.Name, + + "resource_limits": flattenRgResourceLimits(acc.ResourceLimits), + "send_access_emails": acc.SendAccessEmails, + "service_account": acc.ServiceAccount, + + "status": acc.Status, + "updated_time": acc.UpdatedTime, + + "version": acc.Version, + "vins": acc.Vins, + } + res = append(res, temp) + } + return res +} + +func flattenRgResourceLimits(rl ResourceLimits) []map[string]interface{} { + res := make([]map[string]interface{}, 0) + temp := map[string]interface{}{ + "cu_c": rl.CUC, + "cu_d": rl.CUD, + "cu_i": rl.CUI, + "cu_m": rl.CUM, + "cu_np": rl.CUNP, + "gpu_units": rl.GpuUnits, + } + res = append(res, temp) + + return res + +} + +func dataSourceAccountListRead(ctx context.Context, d *schema.ResourceData, m interface{}) diag.Diagnostics { + accountList, err := utilityAccountListCheckPresence(ctx, d, m) + if err != nil { + return diag.FromErr(err) + } + + id := uuid.New() + d.SetId(id.String()) + d.Set("items", flattenAccountList(accountList)) + + return nil +} + +func dataSourceAccountListSchemaMake() map[string]*schema.Schema { + res := map[string]*schema.Schema{ + "page": { + Type: schema.TypeInt, + Optional: true, + Description: "Page number", + }, + "size": { + Type: schema.TypeInt, + Optional: true, + Description: "Page size", + }, + "items": { + Type: schema.TypeList, + Computed: true, + Elem: &schema.Resource{ + Schema: dataSourceAccountItemSchemaMake(), + }, + }, + } + return res +} + +func DataSourceAccountList() *schema.Resource { + return &schema.Resource{ + SchemaVersion: 1, + + ReadContext: dataSourceAccountListRead, + + Timeouts: &schema.ResourceTimeout{ + Read: &constants.Timeout30s, + Default: &constants.Timeout60s, + }, + + Schema: dataSourceAccountListSchemaMake(), + } +} diff --git a/internal/service/cloudbroker/account/data_source_account_rg_list.go b/internal/service/cloudbroker/account/data_source_account_rg_list.go new file mode 100644 index 0000000..f810db4 --- /dev/null +++ b/internal/service/cloudbroker/account/data_source_account_rg_list.go @@ -0,0 +1,157 @@ +/* +Copyright (c) 2019-2022 Digital Energy Cloud Solutions LLC. All Rights Reserved. +Authors: +Petr Krutov, +Stanislav Solovev, + +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. +*/ + +/* +Terraform DECORT provider - manage resources provided by DECORT (Digital Energy Cloud +Orchestration Technology) with Terraform by Hashicorp. + +Source code: https://github.com/rudecs/terraform-provider-decort + +Please see README.md to learn where to place source code so that it +builds seamlessly. + +Documentation: https://github.com/rudecs/terraform-provider-decort/wiki +*/ + +package account + +import ( + "context" + + "github.com/google/uuid" + "github.com/hashicorp/terraform-plugin-sdk/v2/diag" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" + "github.com/rudecs/terraform-provider-decort/internal/constants" +) + +func flattenAccountRGList(argl AccountRGList) []map[string]interface{} { + res := make([]map[string]interface{}, 0) + for _, arg := range argl { + temp := map[string]interface{}{ + "computes": flattenAccRGComputes(arg.Computes), + "resources": flattenAccRGResources(arg.Resources), + "created_by": arg.CreatedBy, + "created_time": arg.CreatedTime, + "deleted_by": arg.DeletedBy, + "deleted_time": arg.DeletedTime, + "rg_id": arg.RGID, + "milestones": arg.Milestones, + "rg_name": arg.RGName, + "status": arg.Status, + "updated_by": arg.UpdatedBy, + "updated_time": arg.UpdatedTime, + "vinses": arg.Vinses, + } + res = append(res, temp) + } + return res + +} + +func flattenAccRGComputes(argc AccountRGComputes) []map[string]interface{} { + res := make([]map[string]interface{}, 0) + temp := map[string]interface{}{ + "started": argc.Started, + "stopped": argc.Stopped, + } + res = append(res, temp) + return res +} + +func flattenAccRGResources(argr AccountRGResources) []map[string]interface{} { + res := make([]map[string]interface{}, 0) + temp := map[string]interface{}{ + "consumed": flattenAccResource(argr.Consumed), + "limits": flattenAccResource(argr.Limits), + "reserved": flattenAccResource(argr.Reserved), + } + res = append(res, temp) + return res +} + +func flattenAccResources(r Resources) []map[string]interface{} { + res := make([]map[string]interface{}, 0) + temp := map[string]interface{}{ + "current": flattenAccResource(r.Current), + "reserved": flattenAccResource(r.Reserved), + } + res = append(res, temp) + return res +} + +func flattenAccResource(r Resource) []map[string]interface{} { + res := make([]map[string]interface{}, 0) + temp := map[string]interface{}{ + "cpu": r.CPU, + "disksize": r.Disksize, + "extips": r.Extips, + "exttraffic": r.Exttraffic, + "gpu": r.GPU, + "ram": r.RAM, + } + res = append(res, temp) + return res +} + +func dataSourceAccountRGListRead(ctx context.Context, d *schema.ResourceData, m interface{}) diag.Diagnostics { + accountRGList, err := utilityAccountRGListCheckPresence(ctx, d, m) + if err != nil { + return diag.FromErr(err) + } + + id := uuid.New() + d.SetId(id.String()) + d.Set("items", flattenAccountRGList(accountRGList)) + + return nil +} + +func dataSourceAccountRGListSchemaMake() map[string]*schema.Schema { + res := map[string]*schema.Schema{ + "account_id": { + Type: schema.TypeInt, + Required: true, + Description: "ID of the account", + }, + "items": { + Type: schema.TypeList, + Computed: true, + Description: "Search Result", + Elem: &schema.Resource{ + Schema: dataSourceAccountRGSchemaMake(), + }, + }, + } + return res +} + +func DataSourceAccountRGList() *schema.Resource { + return &schema.Resource{ + SchemaVersion: 1, + + ReadContext: dataSourceAccountRGListRead, + + Timeouts: &schema.ResourceTimeout{ + Read: &constants.Timeout30s, + Default: &constants.Timeout60s, + }, + + Schema: dataSourceAccountRGListSchemaMake(), + } +} diff --git a/internal/service/cloudbroker/account/data_source_account_vins_list.go b/internal/service/cloudbroker/account/data_source_account_vins_list.go new file mode 100644 index 0000000..7110629 --- /dev/null +++ b/internal/service/cloudbroker/account/data_source_account_vins_list.go @@ -0,0 +1,116 @@ +/* +Copyright (c) 2019-2022 Digital Energy Cloud Solutions LLC. All Rights Reserved. +Authors: +Petr Krutov, +Stanislav Solovev, + +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. +*/ + +/* +Terraform DECORT provider - manage resources provided by DECORT (Digital Energy Cloud +Orchestration Technology) with Terraform by Hashicorp. + +Source code: https://github.com/rudecs/terraform-provider-decort + +Please see README.md to learn where to place source code so that it +builds seamlessly. + +Documentation: https://github.com/rudecs/terraform-provider-decort/wiki +*/ + +package account + +import ( + "context" + + "github.com/google/uuid" + "github.com/hashicorp/terraform-plugin-sdk/v2/diag" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" + "github.com/rudecs/terraform-provider-decort/internal/constants" +) + +func flattenAccountVinsList(avl AccountVinsList) []map[string]interface{} { + res := make([]map[string]interface{}, 0) + for _, av := range avl { + temp := map[string]interface{}{ + "account_id": av.AccountId, + "account_name": av.AccountName, + "computes": av.Computes, + "created_by": av.CreatedBy, + "created_time": av.CreatedTime, + "deleted_by": av.DeletedBy, + "deleted_time": av.DeletedTime, + "external_ip": av.ExternalIP, + "vin_id": av.ID, + "vin_name": av.Name, + "network": av.Network, + "pri_vnf_dev_id": av.PriVnfDevId, + "rg_id": av.RgId, + "rg_name": av.RgName, + "status": av.Status, + "updated_by": av.UpdatedBy, + "updated_time": av.UpdatedTime, + } + res = append(res, temp) + } + return res + +} + +func dataSourceAccountVinsListRead(ctx context.Context, d *schema.ResourceData, m interface{}) diag.Diagnostics { + accountVinsList, err := utilityAccountVinsListCheckPresence(ctx, d, m) + if err != nil { + return diag.FromErr(err) + } + + id := uuid.New() + d.SetId(id.String()) + d.Set("items", flattenAccountVinsList(accountVinsList)) + + return nil +} + +func dataSourceAccountVinsListSchemaMake() map[string]*schema.Schema { + res := map[string]*schema.Schema{ + "account_id": { + Type: schema.TypeInt, + Required: true, + Description: "ID of the account", + }, + "items": { + Type: schema.TypeList, + Computed: true, + Description: "Search Result", + Elem: &schema.Resource{ + Schema: dataSourceAccountVinsSchema(), + }, + }, + } + return res +} + +func DataSourceAccountVinsList() *schema.Resource { + return &schema.Resource{ + SchemaVersion: 1, + + ReadContext: dataSourceAccountVinsListRead, + + Timeouts: &schema.ResourceTimeout{ + Read: &constants.Timeout30s, + Default: &constants.Timeout60s, + }, + + Schema: dataSourceAccountVinsListSchemaMake(), + } +} diff --git a/internal/service/cloudbroker/account/models.go b/internal/service/cloudbroker/account/models.go new file mode 100644 index 0000000..d38c953 --- /dev/null +++ b/internal/service/cloudbroker/account/models.go @@ -0,0 +1,219 @@ +/* +Copyright (c) 2019-2022 Digital Energy Cloud Solutions LLC. All Rights Reserved. +Authors: +Petr Krutov, +Stanislav Solovev, + +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. +*/ + +/* +Terraform DECORT provider - manage resources provided by DECORT (Digital Energy Cloud +Orchestration Technology) with Terraform by Hashicorp. + +Source code: https://github.com/rudecs/terraform-provider-decort + +Please see README.md to learn where to place source code so that it +builds seamlessly. + +Documentation: https://github.com/rudecs/terraform-provider-decort/wiki +*/ + +package account + +type AccountAclRecord struct { + IsExplicit bool `json:"explicit"` + Guid string `json:"guid"` + Rights string `json:"right"` + Status string `json:"status"` + Type string `json:"type"` + UgroupID string `json:"userGroupId"` +} + +type ResourceLimits struct { + CUC float64 `json:"CU_C"` + CUD float64 `json:"CU_D"` + CUI float64 `json:"CU_I"` + CUM float64 `json:"CU_M"` + CUNP float64 `json:"CU_NP"` + GpuUnits float64 `json:"gpu_units"` +} + +type Account struct { + DCLocation string `json:"DCLocation"` + CKey string `jspn:"_ckey"` + Meta []interface{} `json:"_meta"` + Acl []AccountAclRecord `json:"acl"` + Company string `json:"company"` + CompanyUrl string `json:"companyurl"` + CreatedBy string `jspn:"createdBy"` + CreatedTime int `json:"createdTime"` + DeactiovationTime float64 `json:"deactivationTime"` + DeletedBy string `json:"deletedBy"` + DeletedTime int `json:"deletedTime"` + DisplayName string `json:"displayname"` + GUID int `json:"guid"` + ID int `json:"id"` + Name string `json:"name"` + ResourceLimits ResourceLimits `json:"resourceLimits"` + SendAccessEmails bool `json:"sendAccessEmails"` + ServiceAccount bool `json:"serviceAccount"` + Status string `json:"status"` + UpdatedTime int `json:"updatedTime"` + Version int `json:"version"` + Vins []int `json:"vins"` +} + +type AccountList []Account + +type Resource struct { + CPU int `json:"cpu"` + Disksize int `json:"disksize"` + Extips int `json:"extips"` + Exttraffic int `json:"exttraffic"` + GPU int `json:"gpu"` + RAM int `json:"ram"` +} + +type Resources struct { + Current Resource `json:"Current"` + Reserved Resource `json:"Reserved"` +} + +type AccountWithResources struct { + Account + Resources Resources `json:"Resources"` +} + +type AccountCompute struct { + AccountId int `json:"accountId"` + AccountName string `json:"accountName"` + CPUs int `json:"cpus"` + CreatedBy string `json:"createdBy"` + CreatedTime int `json:"createdTime"` + DeletedBy string `json:"deletedBy"` + DeletedTime int `json:"deletedTime"` + ComputeId int `json:"id"` + ComputeName string `json:"name"` + RAM int `json:"ram"` + Registered bool `json:"registered"` + RgId int `json:"rgId"` + RgName string `json:"rgName"` + Status string `json:"status"` + TechStatus string `json:"techStatus"` + TotalDisksSize int `json:"totalDisksSize"` + UpdatedBy string `json:"updatedBy"` + UpdatedTime int `json:"updatedTime"` + UserManaged bool `json:"userManaged"` + VinsConnected int `json:"vinsConnected"` +} + +type AccountComputesList []AccountCompute + +type AccountDisk struct { + ID int `json:"id"` + Name string `json:"name"` + Pool string `json:"pool"` + SepId int `json:"sepId"` + SizeMax int `json:"sizeMax"` + Type string `json:"type"` +} + +type AccountDisksList []AccountDisk + +type AccountVin struct { + AccountId int `json:"accountId"` + AccountName string `json:"accountName"` + Computes int `json:"computes"` + CreatedBy string `json:"createdBy"` + CreatedTime int `json:"createdTime"` + DeletedBy string `json:"deletedBy"` + DeletedTime int `json:"deletedTime"` + ExternalIP string `json:"externalIP"` + ID int `json:"id"` + Name string `json:"name"` + Network string `json:"network"` + PriVnfDevId int `json:"priVnfDevId"` + RgId int `json:"rgId"` + RgName string `json:"rgName"` + Status string `json:"status"` + UpdatedBy string `json:"updatedBy"` + UpdatedTime int `json:"updatedTime"` +} + +type AccountVinsList []AccountVin + +type AccountAudit struct { + Call string `json:"call"` + ResponseTime float64 `json:"responsetime"` + StatusCode int `json:"statuscode"` + Timestamp float64 `json:"timestamp"` + User string `json:"user"` +} + +type AccountAuditsList []AccountAudit + +type AccountRGComputes struct { + Started int `json:"Started"` + Stopped int `json:"Stopped"` +} + +type AccountRGResources struct { + Consumed Resource `json:"Consumed"` + Limits Resource `json:"Limits"` + Reserved Resource `json:"Reserved"` +} + +type AccountRG struct { + Computes AccountRGComputes `json:"Computes"` + Resources AccountRGResources `json:"Resources"` + CreatedBy string `json:"createdBy"` + CreatedTime int `json:"createdTime"` + DeletedBy string `json:"deletedBy"` + DeletedTime int `json:"deletedTime"` + RGID int `json:"id"` + Milestones int `json:"milestones"` + RGName string `json:"name"` + Status string `json:"status"` + UpdatedBy string `json:"updatedBy"` + UpdatedTime int `json:"updatedTime"` + Vinses int `json:"vinses"` +} + +type AccountRGList []AccountRG + +type AccountFlipGroup struct { + AccountId int `json:"accountId"` + ClientType string `json:"clientType"` + ConnType string `json:"connType"` + CreatedBy string `json:"createdBy"` + CreatedTime int `json:"createdTime"` + DefaultGW string `json:"defaultGW"` + DeletedBy string `json:"deletedBy"` + DeletedTime int `json:"deletedTime"` + Desc string `json:"desc"` + GID int `json:"gid"` + GUID int `json:"guid"` + ID int `json:"id"` + IP string `json:"ip"` + Milestones int `json:"milestones"` + Name string `json:"name"` + NetID int `json:"netId"` + NetType string `json:"netType"` + NetMask int `json:"netmask"` + Status string `json:"status"` + UpdatedBy string `json:"updatedBy"` + UpdatedTime int `json:"updatedTime"` +} + +type AccountFlipGroupsList []AccountFlipGroup diff --git a/internal/service/cloudbroker/account/resource_account.go b/internal/service/cloudbroker/account/resource_account.go new file mode 100644 index 0000000..2647b9d --- /dev/null +++ b/internal/service/cloudbroker/account/resource_account.go @@ -0,0 +1,485 @@ +/* +Copyright (c) 2019-2022 Digital Energy Cloud Solutions LLC. All Rights Reserved. +Authors: +Petr Krutov, +Stanislav Solovev, + +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. +*/ + +/* +Terraform DECORT provider - manage resources provided by DECORT (Digital Energy Cloud +Orchestration Technology) with Terraform by Hashicorp. + +Source code: https://github.com/rudecs/terraform-provider-decort + +Please see README.md to learn where to place source code so that it +builds seamlessly. + +Documentation: https://github.com/rudecs/terraform-provider-decort/wiki +*/ + +package account + +import ( + "context" + "net/url" + "strconv" + "strings" + + "github.com/hashicorp/terraform-plugin-sdk/v2/diag" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" + "github.com/rudecs/terraform-provider-decort/internal/constants" + "github.com/rudecs/terraform-provider-decort/internal/controller" + "github.com/rudecs/terraform-provider-decort/internal/flattens" + log "github.com/sirupsen/logrus" +) + +func resourceAccountCreate(ctx context.Context, d *schema.ResourceData, m interface{}) diag.Diagnostics { + log.Debugf("resourceAccountCreate") + + c := m.(*controller.ControllerCfg) + urlValues := &url.Values{} + + urlValues.Add("name", d.Get("account_name").(string)) + urlValues.Add("username", d.Get("username").(string)) + + if emailaddress, ok := d.GetOk("emailaddress"); ok { + urlValues.Add("emailaddress", emailaddress.(string)) + } + if sendAccessEmails, ok := d.GetOk("send_access_emails"); ok { + urlValues.Add("sendAccessEmails", strconv.FormatBool(sendAccessEmails.(bool))) + } + if resLimits, ok := d.GetOk("resource_limits"); ok { + resLimit := resLimits.([]interface{})[0] + resLimitConv := resLimit.(map[string]interface{}) + if resLimitConv["cu_m"] != nil { + maxMemCap := int(resLimitConv["cu_m"].(float64)) + if maxMemCap == 0 { + urlValues.Add("maxMemoryCapacity", strconv.Itoa(-1)) + } else { + urlValues.Add("maxMemoryCapacity", strconv.Itoa(maxMemCap)) + } + } + if resLimitConv["cu_d"] != nil { + maxDiskCap := int(resLimitConv["cu_d"].(float64)) + if maxDiskCap == 0 { + urlValues.Add("maxVDiskCapacity", strconv.Itoa(-1)) + } else { + urlValues.Add("maxVDiskCapacity", strconv.Itoa(maxDiskCap)) + } + } + if resLimitConv["cu_c"] != nil { + maxCPUCap := int(resLimitConv["cu_c"].(float64)) + if maxCPUCap == 0 { + urlValues.Add("maxCPUCapacity", strconv.Itoa(-1)) + } else { + urlValues.Add("maxCPUCapacity", strconv.Itoa(maxCPUCap)) + } + + } + if resLimitConv["cu_i"] != nil { + maxNumPublicIP := int(resLimitConv["cu_i"].(float64)) + if maxNumPublicIP == 0 { + urlValues.Add("maxNumPublicIP", strconv.Itoa(-1)) + } else { + urlValues.Add("maxNumPublicIP", strconv.Itoa(maxNumPublicIP)) + } + + } + if resLimitConv["cu_np"] != nil { + maxNP := int(resLimitConv["cu_np"].(float64)) + if maxNP == 0 { + urlValues.Add("maxNetworkPeerTransfer", strconv.Itoa(-1)) + } else { + urlValues.Add("maxNetworkPeerTransfer", strconv.Itoa(maxNP)) + } + + } + if resLimitConv["gpu_units"] != nil { + gpuUnits := int(resLimitConv["gpu_units"].(float64)) + if gpuUnits == 0 { + urlValues.Add("gpu_units", strconv.Itoa(-1)) + } else { + urlValues.Add("gpu_units", strconv.Itoa(gpuUnits)) + } + } + } + + accountId, err := c.DecortAPICall(ctx, "POST", accountCreateAPI, urlValues) + if err != nil { + return diag.FromErr(err) + } + + d.SetId(accountId) + d.Set("account_id", accountId) + + diagnostics := resourceAccountRead(ctx, d, m) + if diagnostics != nil { + return diagnostics + } + + if enable, ok := d.GetOk("enable"); ok { + api := accountDisableAPI + enable := enable.(bool) + if enable { + api = accountEnableAPI + } + urlValues.Add("accountId", strconv.Itoa(d.Get("account_id").(int))) + + _, err := c.DecortAPICall(ctx, "POST", api, urlValues) + if err != nil { + return diag.FromErr(err) + } + + urlValues = &url.Values{} + } + + if users, ok := d.GetOk("users"); ok { + addedUsers := users.([]interface{}) + + if len(addedUsers) > 0 { + for _, user := range addedUsers { + userConv := user.(map[string]interface{}) + urlValues.Add("accountId", strconv.Itoa(d.Get("account_id").(int))) + urlValues.Add("userId", userConv["user_id"].(string)) + urlValues.Add("accesstype", strings.ToUpper(userConv["access_type"].(string))) + _, err := c.DecortAPICall(ctx, "POST", accountAddUserAPI, urlValues) + if err != nil { + return diag.FromErr(err) + } + + urlValues = &url.Values{} + } + } + } + + return nil +} + +func resourceAccountRead(ctx context.Context, d *schema.ResourceData, m interface{}) diag.Diagnostics { + log.Debugf("resourceAccountRead") + + acc, err := utilityAccountCheckPresence(ctx, d, m) + if acc == nil { + d.SetId("") + return diag.FromErr(err) + } + + d.Set("dc_location", acc.DCLocation) + d.Set("resources", flattenAccResources(acc.Resources)) + d.Set("ckey", acc.CKey) + d.Set("meta", flattens.FlattenMeta(acc.Meta)) + d.Set("acl", flattenAccAcl(acc.Acl)) + d.Set("company", acc.Company) + d.Set("companyurl", acc.CompanyUrl) + d.Set("created_by", acc.CreatedBy) + d.Set("created_time", acc.CreatedTime) + d.Set("deactivation_time", acc.DeactiovationTime) + d.Set("deleted_by", acc.DeletedBy) + d.Set("deleted_time", acc.DeletedTime) + d.Set("displayname", acc.DisplayName) + d.Set("guid", acc.GUID) + d.Set("account_id", acc.ID) + d.Set("account_name", acc.Name) + d.Set("resource_limits", flattenRgResourceLimits(acc.ResourceLimits)) + d.Set("send_access_emails", acc.SendAccessEmails) + d.Set("service_account", acc.ServiceAccount) + d.Set("status", acc.Status) + d.Set("updated_time", acc.UpdatedTime) + d.Set("version", acc.Version) + d.Set("vins", acc.Vins) + + return nil +} + +func resourceAccountDelete(ctx context.Context, d *schema.ResourceData, m interface{}) diag.Diagnostics { + log.Debugf("resourceAccountDelete") + + account, err := utilityAccountCheckPresence(ctx, d, m) + if account == nil { + if err != nil { + return diag.FromErr(err) + } + return nil + } + + c := m.(*controller.ControllerCfg) + urlValues := &url.Values{} + urlValues.Add("accountId", strconv.Itoa(d.Get("account_id").(int))) + urlValues.Add("permanently", strconv.FormatBool(d.Get("permanently").(bool))) + + _, err = c.DecortAPICall(ctx, "POST", accountDeleteAPI, urlValues) + if err != nil { + return diag.FromErr(err) + } + d.SetId("") + + return nil +} + +func resourceAccountExists(ctx context.Context, d *schema.ResourceData, m interface{}) (bool, error) { + log.Debugf("resourceAccountExists") + + account, err := utilityAccountCheckPresence(ctx, d, m) + if account == nil { + if err != nil { + return false, err + } + return false, nil + } + + return true, nil +} + +func resourceAccountEdit(ctx context.Context, d *schema.ResourceData, m interface{}) diag.Diagnostics { + log.Debugf("resourceAccountEdit") + c := m.(*controller.ControllerCfg) + + urlValues := &url.Values{} + if d.HasChange("enable") { + api := accountDisableAPI + enable := d.Get("enable").(bool) + if enable { + api = accountEnableAPI + } + urlValues.Add("accountId", strconv.Itoa(d.Get("account_id").(int))) + + _, err := c.DecortAPICall(ctx, "POST", api, urlValues) + if err != nil { + return diag.FromErr(err) + } + + urlValues = &url.Values{} + } + + if d.HasChange("account_name") { + urlValues.Add("name", d.Get("account_name").(string)) + urlValues.Add("accountId", strconv.Itoa(d.Get("account_id").(int))) + _, err := c.DecortAPICall(ctx, "POST", accountUpdateAPI, urlValues) + if err != nil { + return diag.FromErr(err) + } + + urlValues = &url.Values{} + } + if d.HasChange("resource_limits") { + resLimit := d.Get("resource_limits").([]interface{})[0] + resLimitConv := resLimit.(map[string]interface{}) + + if resLimitConv["cu_m"] != nil { + maxMemCap := int(resLimitConv["cu_m"].(float64)) + if maxMemCap == 0 { + urlValues.Add("maxMemoryCapacity", strconv.Itoa(-1)) + } else { + urlValues.Add("maxMemoryCapacity", strconv.Itoa(maxMemCap)) + } + } + if resLimitConv["cu_d"] != nil { + maxDiskCap := int(resLimitConv["cu_d"].(float64)) + if maxDiskCap == 0 { + urlValues.Add("maxVDiskCapacity", strconv.Itoa(-1)) + } else { + urlValues.Add("maxVDiskCapacity", strconv.Itoa(maxDiskCap)) + } + } + if resLimitConv["cu_c"] != nil { + maxCPUCap := int(resLimitConv["cu_c"].(float64)) + if maxCPUCap == 0 { + urlValues.Add("maxCPUCapacity", strconv.Itoa(-1)) + } else { + urlValues.Add("maxCPUCapacity", strconv.Itoa(maxCPUCap)) + } + + } + if resLimitConv["cu_i"] != nil { + maxNumPublicIP := int(resLimitConv["cu_i"].(float64)) + if maxNumPublicIP == 0 { + urlValues.Add("maxNumPublicIP", strconv.Itoa(-1)) + } else { + urlValues.Add("maxNumPublicIP", strconv.Itoa(maxNumPublicIP)) + } + + } + if resLimitConv["cu_np"] != nil { + maxNP := int(resLimitConv["cu_np"].(float64)) + if maxNP == 0 { + urlValues.Add("maxNetworkPeerTransfer", strconv.Itoa(-1)) + } else { + urlValues.Add("maxNetworkPeerTransfer", strconv.Itoa(maxNP)) + } + + } + if resLimitConv["gpu_units"] != nil { + gpuUnits := int(resLimitConv["gpu_units"].(float64)) + if gpuUnits == 0 { + urlValues.Add("gpu_units", strconv.Itoa(-1)) + } else { + urlValues.Add("gpu_units", strconv.Itoa(gpuUnits)) + } + } + + urlValues.Add("accountId", strconv.Itoa(d.Get("account_id").(int))) + _, err := c.DecortAPICall(ctx, "POST", accountUpdateAPI, urlValues) + if err != nil { + return diag.FromErr(err) + } + + urlValues = &url.Values{} + } + + if d.HasChange("send_access_emails") { + urlValues.Add("sendAccessEmails", strconv.FormatBool(d.Get("send_access_emails").(bool))) + urlValues.Add("accountId", strconv.Itoa(d.Get("account_id").(int))) + _, err := c.DecortAPICall(ctx, "POST", accountUpdateAPI, urlValues) + if err != nil { + return diag.FromErr(err) + } + + urlValues = &url.Values{} + } + + if d.HasChange("restore") { + restore := d.Get("restore").(bool) + if restore { + urlValues.Add("accountId", strconv.Itoa(d.Get("account_id").(int))) + _, err := c.DecortAPICall(ctx, "POST", accountRestoreAPI, urlValues) + if err != nil { + return diag.FromErr(err) + } + + urlValues = &url.Values{} + } + } + + if d.HasChange("users") { + deletedUsers := make([]interface{}, 0) + addedUsers := make([]interface{}, 0) + updatedUsers := make([]interface{}, 0) + + old, new := d.GetChange("users") + oldConv := old.([]interface{}) + newConv := new.([]interface{}) + for _, el := range oldConv { + if !isContainsUser(newConv, el) { + deletedUsers = append(deletedUsers, el) + } + } + for _, el := range newConv { + if !isContainsUser(oldConv, el) { + addedUsers = append(addedUsers, el) + } else { + if isChangedUser(oldConv, el) { + updatedUsers = append(updatedUsers, el) + } + } + } + + if len(deletedUsers) > 0 { + for _, user := range deletedUsers { + userConv := user.(map[string]interface{}) + urlValues.Add("accountId", strconv.Itoa(d.Get("account_id").(int))) + urlValues.Add("userId", userConv["user_id"].(string)) + urlValues.Add("recursivedelete", strconv.FormatBool(userConv["recursive_delete"].(bool))) + _, err := c.DecortAPICall(ctx, "POST", accountDeleteUserAPI, urlValues) + if err != nil { + return diag.FromErr(err) + } + + urlValues = &url.Values{} + } + } + + if len(addedUsers) > 0 { + for _, user := range addedUsers { + userConv := user.(map[string]interface{}) + urlValues.Add("accountId", strconv.Itoa(d.Get("account_id").(int))) + urlValues.Add("userId", userConv["user_id"].(string)) + urlValues.Add("accesstype", strings.ToUpper(userConv["access_type"].(string))) + _, err := c.DecortAPICall(ctx, "POST", accountAddUserAPI, urlValues) + if err != nil { + return diag.FromErr(err) + } + + urlValues = &url.Values{} + } + } + + if len(updatedUsers) > 0 { + for _, user := range updatedUsers { + userConv := user.(map[string]interface{}) + urlValues.Add("accountId", strconv.Itoa(d.Get("account_id").(int))) + urlValues.Add("userId", userConv["user_id"].(string)) + urlValues.Add("accesstype", strings.ToUpper(userConv["access_type"].(string))) + _, err := c.DecortAPICall(ctx, "POST", accountUpdateUserAPI, urlValues) + if err != nil { + return diag.FromErr(err) + } + + urlValues = &url.Values{} + } + } + + } + + return nil +} + +func isContainsUser(els []interface{}, el interface{}) bool { + for _, elOld := range els { + elOldConv := elOld.(map[string]interface{}) + elConv := el.(map[string]interface{}) + if elOldConv["user_id"].(string) == elConv["user_id"].(string) { + return true + } + } + return false +} + +func isChangedUser(els []interface{}, el interface{}) bool { + for _, elOld := range els { + elOldConv := elOld.(map[string]interface{}) + elConv := el.(map[string]interface{}) + if elOldConv["user_id"].(string) == elConv["user_id"].(string) && + (!strings.EqualFold(elOldConv["access_type"].(string), elConv["access_type"].(string)) || + elOldConv["recursive_delete"].(bool) != elConv["recursive_delete"].(bool)) { + return true + } + } + return false +} + +func ResourceAccount() *schema.Resource { + return &schema.Resource{ + SchemaVersion: 1, + + CreateContext: resourceAccountCreate, + ReadContext: resourceAccountRead, + UpdateContext: resourceAccountEdit, + DeleteContext: resourceAccountDelete, + + Importer: &schema.ResourceImporter{ + State: schema.ImportStatePassthrough, + }, + + Timeouts: &schema.ResourceTimeout{ + Create: &constants.Timeout60s, + Read: &constants.Timeout30s, + Update: &constants.Timeout60s, + Delete: &constants.Timeout60s, + Default: &constants.Timeout60s, + }, + + Schema: resourceAccountSchemaMake(), + } +} diff --git a/internal/service/cloudbroker/account/utility_account.go b/internal/service/cloudbroker/account/utility_account.go new file mode 100644 index 0000000..092162b --- /dev/null +++ b/internal/service/cloudbroker/account/utility_account.go @@ -0,0 +1,69 @@ +/* +Copyright (c) 2019-2022 Digital Energy Cloud Solutions LLC. All Rights Reserved. +Authors: +Petr Krutov, +Stanislav Solovev, + +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. +*/ + +/* +Terraform DECORT provider - manage resources provided by DECORT (Digital Energy Cloud +Orchestration Technology) with Terraform by Hashicorp. + +Source code: https://github.com/rudecs/terraform-provider-decort + +Please see README.md to learn where to place source code so that it +builds seamlessly. + +Documentation: https://github.com/rudecs/terraform-provider-decort/wiki +*/ + +package account + +import ( + "context" + "encoding/json" + "net/url" + "strconv" + + "github.com/rudecs/terraform-provider-decort/internal/controller" + log "github.com/sirupsen/logrus" + + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" +) + +func utilityAccountCheckPresence(ctx context.Context, d *schema.ResourceData, m interface{}) (*AccountWithResources, error) { + account := &AccountWithResources{} + c := m.(*controller.ControllerCfg) + urlValues := &url.Values{} + + if (strconv.Itoa(d.Get("account_id").(int))) != "0" { + urlValues.Add("accountId", strconv.Itoa(d.Get("account_id").(int))) + } else { + urlValues.Add("accountId", d.Id()) + } + + log.Debugf("utilityAccountCheckPresence: load account") + accountRaw, err := c.DecortAPICall(ctx, "POST", accountGetAPI, urlValues) + if err != nil { + return nil, err + } + + err = json.Unmarshal([]byte(accountRaw), &account) + if err != nil { + return nil, err + } + + return account, nil +} diff --git a/internal/service/cloudbroker/account/utility_account_audits_list.go b/internal/service/cloudbroker/account/utility_account_audits_list.go new file mode 100644 index 0000000..c89cedd --- /dev/null +++ b/internal/service/cloudbroker/account/utility_account_audits_list.go @@ -0,0 +1,65 @@ +/* +Copyright (c) 2019-2022 Digital Energy Cloud Solutions LLC. All Rights Reserved. +Authors: +Petr Krutov, +Stanislav Solovev, + +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. +*/ + +/* +Terraform DECORT provider - manage resources provided by DECORT (Digital Energy Cloud +Orchestration Technology) with Terraform by Hashicorp. + +Source code: https://github.com/rudecs/terraform-provider-decort + +Please see README.md to learn where to place source code so that it +builds seamlessly. + +Documentation: https://github.com/rudecs/terraform-provider-decort/wiki +*/ + +package account + +import ( + "context" + "encoding/json" + "net/url" + "strconv" + + "github.com/rudecs/terraform-provider-decort/internal/controller" + log "github.com/sirupsen/logrus" + + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" +) + +func utilityAccountAuditsListCheckPresence(ctx context.Context, d *schema.ResourceData, m interface{}) (AccountAuditsList, error) { + accountAuditsList := AccountAuditsList{} + c := m.(*controller.ControllerCfg) + urlValues := &url.Values{} + + urlValues.Add("accountId", strconv.Itoa(d.Get("account_id").(int))) + + log.Debugf("utilityAccountAuditsListCheckPresence: load account list") + accountAuditsListRaw, err := c.DecortAPICall(ctx, "POST", accountAuditsAPI, urlValues) + if err != nil { + return nil, err + } + + err = json.Unmarshal([]byte(accountAuditsListRaw), &accountAuditsList) + if err != nil { + return nil, err + } + + return accountAuditsList, nil +} diff --git a/internal/service/cloudbroker/account/utility_account_computes_list.go b/internal/service/cloudbroker/account/utility_account_computes_list.go new file mode 100644 index 0000000..9b746da --- /dev/null +++ b/internal/service/cloudbroker/account/utility_account_computes_list.go @@ -0,0 +1,65 @@ +/* +Copyright (c) 2019-2022 Digital Energy Cloud Solutions LLC. All Rights Reserved. +Authors: +Petr Krutov, +Stanislav Solovev, + +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. +*/ + +/* +Terraform DECORT provider - manage resources provided by DECORT (Digital Energy Cloud +Orchestration Technology) with Terraform by Hashicorp. + +Source code: https://github.com/rudecs/terraform-provider-decort + +Please see README.md to learn where to place source code so that it +builds seamlessly. + +Documentation: https://github.com/rudecs/terraform-provider-decort/wiki +*/ + +package account + +import ( + "context" + "encoding/json" + "net/url" + "strconv" + + "github.com/rudecs/terraform-provider-decort/internal/controller" + log "github.com/sirupsen/logrus" + + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" +) + +func utilityAccountComputesListCheckPresence(ctx context.Context, d *schema.ResourceData, m interface{}) (AccountComputesList, error) { + accountComputesList := AccountComputesList{} + c := m.(*controller.ControllerCfg) + urlValues := &url.Values{} + + urlValues.Add("accountId", strconv.Itoa(d.Get("account_id").(int))) + + log.Debugf("utilityAccountComputesListCheckPresence: load account list") + accountComputesListRaw, err := c.DecortAPICall(ctx, "POST", accountListComputesAPI, urlValues) + if err != nil { + return nil, err + } + + err = json.Unmarshal([]byte(accountComputesListRaw), &accountComputesList) + if err != nil { + return nil, err + } + + return accountComputesList, nil +} diff --git a/internal/service/cloudbroker/account/utility_account_deleted_list.go b/internal/service/cloudbroker/account/utility_account_deleted_list.go new file mode 100644 index 0000000..b4537c1 --- /dev/null +++ b/internal/service/cloudbroker/account/utility_account_deleted_list.go @@ -0,0 +1,70 @@ +/* +Copyright (c) 2019-2022 Digital Energy Cloud Solutions LLC. All Rights Reserved. +Authors: +Petr Krutov, +Stanislav Solovev, + +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. +*/ + +/* +Terraform DECORT provider - manage resources provided by DECORT (Digital Energy Cloud +Orchestration Technology) with Terraform by Hashicorp. + +Source code: https://github.com/rudecs/terraform-provider-decort + +Please see README.md to learn where to place source code so that it +builds seamlessly. + +Documentation: https://github.com/rudecs/terraform-provider-decort/wiki +*/ + +package account + +import ( + "context" + "encoding/json" + "net/url" + "strconv" + + "github.com/rudecs/terraform-provider-decort/internal/controller" + log "github.com/sirupsen/logrus" + + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" +) + +func utilityAccountDeletedListCheckPresence(ctx context.Context, d *schema.ResourceData, m interface{}) (AccountList, error) { + accountDeletedList := AccountList{} + c := m.(*controller.ControllerCfg) + urlValues := &url.Values{} + + if page, ok := d.GetOk("page"); ok { + urlValues.Add("page", strconv.Itoa(page.(int))) + } + if size, ok := d.GetOk("size"); ok { + urlValues.Add("size", strconv.Itoa(size.(int))) + } + + log.Debugf("utilityAccountDeletedListCheckPresence: load") + accountDeletedListRaw, err := c.DecortAPICall(ctx, "POST", accountListDeletedAPI, urlValues) + if err != nil { + return nil, err + } + + err = json.Unmarshal([]byte(accountDeletedListRaw), &accountDeletedList) + if err != nil { + return nil, err + } + + return accountDeletedList, nil +} diff --git a/internal/service/cloudbroker/account/utility_account_disks_list.go b/internal/service/cloudbroker/account/utility_account_disks_list.go new file mode 100644 index 0000000..7cea8a2 --- /dev/null +++ b/internal/service/cloudbroker/account/utility_account_disks_list.go @@ -0,0 +1,65 @@ +/* +Copyright (c) 2019-2022 Digital Energy Cloud Solutions LLC. All Rights Reserved. +Authors: +Petr Krutov, +Stanislav Solovev, + +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. +*/ + +/* +Terraform DECORT provider - manage resources provided by DECORT (Digital Energy Cloud +Orchestration Technology) with Terraform by Hashicorp. + +Source code: https://github.com/rudecs/terraform-provider-decort + +Please see README.md to learn where to place source code so that it +builds seamlessly. + +Documentation: https://github.com/rudecs/terraform-provider-decort/wiki +*/ + +package account + +import ( + "context" + "encoding/json" + "net/url" + "strconv" + + "github.com/rudecs/terraform-provider-decort/internal/controller" + log "github.com/sirupsen/logrus" + + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" +) + +func utilityAccountDisksListCheckPresence(ctx context.Context, d *schema.ResourceData, m interface{}) (AccountDisksList, error) { + accountDisksList := AccountDisksList{} + c := m.(*controller.ControllerCfg) + urlValues := &url.Values{} + + urlValues.Add("accountId", strconv.Itoa(d.Get("account_id").(int))) + + log.Debugf("utilityAccountDisksListCheckPresence: load account list") + accountDisksListRaw, err := c.DecortAPICall(ctx, "POST", accountListDisksAPI, urlValues) + if err != nil { + return nil, err + } + + err = json.Unmarshal([]byte(accountDisksListRaw), &accountDisksList) + if err != nil { + return nil, err + } + + return accountDisksList, nil +} diff --git a/internal/service/cloudbroker/account/utility_account_flip_groups.go b/internal/service/cloudbroker/account/utility_account_flip_groups.go new file mode 100644 index 0000000..1585f6b --- /dev/null +++ b/internal/service/cloudbroker/account/utility_account_flip_groups.go @@ -0,0 +1,65 @@ +/* +Copyright (c) 2019-2022 Digital Energy Cloud Solutions LLC. All Rights Reserved. +Authors: +Petr Krutov, +Stanislav Solovev, + +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. +*/ + +/* +Terraform DECORT provider - manage resources provided by DECORT (Digital Energy Cloud +Orchestration Technology) with Terraform by Hashicorp. + +Source code: https://github.com/rudecs/terraform-provider-decort + +Please see README.md to learn where to place source code so that it +builds seamlessly. + +Documentation: https://github.com/rudecs/terraform-provider-decort/wiki +*/ + +package account + +import ( + "context" + "encoding/json" + "net/url" + "strconv" + + "github.com/rudecs/terraform-provider-decort/internal/controller" + log "github.com/sirupsen/logrus" + + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" +) + +func utilityAccountFlipGroupsListCheckPresence(ctx context.Context, d *schema.ResourceData, m interface{}) (AccountFlipGroupsList, error) { + accountFlipGroupsList := AccountFlipGroupsList{} + c := m.(*controller.ControllerCfg) + urlValues := &url.Values{} + + urlValues.Add("accountId", strconv.Itoa(d.Get("account_id").(int))) + + log.Debugf("utilityAccountFlipGroupsListCheckPresence") + accountFlipGroupsListRaw, err := c.DecortAPICall(ctx, "POST", accountListFlipGroupsAPI, urlValues) + if err != nil { + return nil, err + } + + err = json.Unmarshal([]byte(accountFlipGroupsListRaw), &accountFlipGroupsList) + if err != nil { + return nil, err + } + + return accountFlipGroupsList, nil +} diff --git a/internal/service/cloudbroker/account/utility_account_list.go b/internal/service/cloudbroker/account/utility_account_list.go new file mode 100644 index 0000000..62b3b83 --- /dev/null +++ b/internal/service/cloudbroker/account/utility_account_list.go @@ -0,0 +1,70 @@ +/* +Copyright (c) 2019-2022 Digital Energy Cloud Solutions LLC. All Rights Reserved. +Authors: +Petr Krutov, +Stanislav Solovev, + +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. +*/ + +/* +Terraform DECORT provider - manage resources provided by DECORT (Digital Energy Cloud +Orchestration Technology) with Terraform by Hashicorp. + +Source code: https://github.com/rudecs/terraform-provider-decort + +Please see README.md to learn where to place source code so that it +builds seamlessly. + +Documentation: https://github.com/rudecs/terraform-provider-decort/wiki +*/ + +package account + +import ( + "context" + "encoding/json" + "net/url" + "strconv" + + "github.com/rudecs/terraform-provider-decort/internal/controller" + log "github.com/sirupsen/logrus" + + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" +) + +func utilityAccountListCheckPresence(ctx context.Context, d *schema.ResourceData, m interface{}) (AccountList, error) { + accountList := AccountList{} + c := m.(*controller.ControllerCfg) + urlValues := &url.Values{} + + if page, ok := d.GetOk("page"); ok { + urlValues.Add("page", strconv.Itoa(page.(int))) + } + if size, ok := d.GetOk("size"); ok { + urlValues.Add("size", strconv.Itoa(size.(int))) + } + + log.Debugf("utilityAccountListCheckPresence: load account list") + accountListRaw, err := c.DecortAPICall(ctx, "POST", accountListAPI, urlValues) + if err != nil { + return nil, err + } + + err = json.Unmarshal([]byte(accountListRaw), &accountList) + if err != nil { + return nil, err + } + + return accountList, nil +} diff --git a/internal/service/cloudbroker/account/utility_account_rg_list.go b/internal/service/cloudbroker/account/utility_account_rg_list.go new file mode 100644 index 0000000..41c1a76 --- /dev/null +++ b/internal/service/cloudbroker/account/utility_account_rg_list.go @@ -0,0 +1,65 @@ +/* +Copyright (c) 2019-2022 Digital Energy Cloud Solutions LLC. All Rights Reserved. +Authors: +Petr Krutov, +Stanislav Solovev, + +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. +*/ + +/* +Terraform DECORT provider - manage resources provided by DECORT (Digital Energy Cloud +Orchestration Technology) with Terraform by Hashicorp. + +Source code: https://github.com/rudecs/terraform-provider-decort + +Please see README.md to learn where to place source code so that it +builds seamlessly. + +Documentation: https://github.com/rudecs/terraform-provider-decort/wiki +*/ + +package account + +import ( + "context" + "encoding/json" + "net/url" + "strconv" + + "github.com/rudecs/terraform-provider-decort/internal/controller" + log "github.com/sirupsen/logrus" + + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" +) + +func utilityAccountRGListCheckPresence(ctx context.Context, d *schema.ResourceData, m interface{}) (AccountRGList, error) { + accountRGList := AccountRGList{} + c := m.(*controller.ControllerCfg) + urlValues := &url.Values{} + + urlValues.Add("accountId", strconv.Itoa(d.Get("account_id").(int))) + + log.Debugf("utilityAccountRGListCheckPresence: load account list") + accountRGListRaw, err := c.DecortAPICall(ctx, "POST", accountListRGAPI, urlValues) + if err != nil { + return nil, err + } + + err = json.Unmarshal([]byte(accountRGListRaw), &accountRGList) + if err != nil { + return nil, err + } + + return accountRGList, nil +} diff --git a/internal/service/cloudbroker/account/utility_account_vins_list.go b/internal/service/cloudbroker/account/utility_account_vins_list.go new file mode 100644 index 0000000..db2e931 --- /dev/null +++ b/internal/service/cloudbroker/account/utility_account_vins_list.go @@ -0,0 +1,65 @@ +/* +Copyright (c) 2019-2022 Digital Energy Cloud Solutions LLC. All Rights Reserved. +Authors: +Petr Krutov, +Stanislav Solovev, + +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. +*/ + +/* +Terraform DECORT provider - manage resources provided by DECORT (Digital Energy Cloud +Orchestration Technology) with Terraform by Hashicorp. + +Source code: https://github.com/rudecs/terraform-provider-decort + +Please see README.md to learn where to place source code so that it +builds seamlessly. + +Documentation: https://github.com/rudecs/terraform-provider-decort/wiki +*/ + +package account + +import ( + "context" + "encoding/json" + "net/url" + "strconv" + + "github.com/rudecs/terraform-provider-decort/internal/controller" + log "github.com/sirupsen/logrus" + + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" +) + +func utilityAccountVinsListCheckPresence(ctx context.Context, d *schema.ResourceData, m interface{}) (AccountVinsList, error) { + accountVinsList := AccountVinsList{} + c := m.(*controller.ControllerCfg) + urlValues := &url.Values{} + + urlValues.Add("accountId", strconv.Itoa(d.Get("account_id").(int))) + + log.Debugf("utilityAccountVinsListCheckPresence: load account list") + accountVinsListRaw, err := c.DecortAPICall(ctx, "POST", accountListVinsAPI, urlValues) + if err != nil { + return nil, err + } + + err = json.Unmarshal([]byte(accountVinsListRaw), &accountVinsList) + if err != nil { + return nil, err + } + + return accountVinsList, nil +} diff --git a/internal/service/cloudbroker/disks/api.go b/internal/service/cloudbroker/disks/api.go new file mode 100644 index 0000000..173c25b --- /dev/null +++ b/internal/service/cloudbroker/disks/api.go @@ -0,0 +1,41 @@ +/* +Copyright (c) 2019-2022 Digital Energy Cloud Solutions LLC. All Rights Reserved. +Authors: +Petr Krutov, +Stanislav Solovev, + +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. +*/ + +/* +Terraform DECORT provider - manage resources provided by DECORT (Digital Energy Cloud +Orchestration Technology) with Terraform by Hashicorp. + +Source code: https://github.com/rudecs/terraform-provider-decort + +Please see README.md to learn where to place source code so that it +builds seamlessly. + +Documentation: https://github.com/rudecs/terraform-provider-decort/wiki +*/ + +package disks + +const disksCreateAPI = "/restmachine/cloudbroker/disks/create" +const disksGetAPI = "/restmachine/cloudbroker/disks/get" +const disksListAPI = "/restmachine/cloudbroker/disks/list" +const disksResizeAPI = "/restmachine/cloudbroker/disks/resize2" +const disksRenameAPI = "/restmachine/cloudbroker/disks/rename" +const disksDeleteAPI = "/restmachine/cloudbroker/disks/delete" +const disksIOLimitAPI = "/restmachine/cloudbroker/disks/limitIO" +const disksRestoreAPI = "/restmachine/cloudbroker/disks/restore" diff --git a/internal/service/cloudbroker/disks/data_source_disk.go b/internal/service/cloudbroker/disks/data_source_disk.go new file mode 100644 index 0000000..f5e1982 --- /dev/null +++ b/internal/service/cloudbroker/disks/data_source_disk.go @@ -0,0 +1,389 @@ +/* +Copyright (c) 2019-2022 Digital Energy Cloud Solutions LLC. All Rights Reserved. +Authors: +Petr Krutov, +Stanislav Solovev, + +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. +*/ + +/* +Terraform DECORT provider - manage resources provided by DECORT (Digital Energy Cloud +Orchestration Technology) with Terraform by Hashicorp. + +Source code: https://github.com/rudecs/terraform-provider-decort + +Please see README.md to learn where to place source code so that it +builds seamlessly. + +Documentation: https://github.com/rudecs/terraform-provider-decort/wiki +*/ + +package disks + +import ( + "context" + "encoding/json" + + // "net/url" + + "github.com/google/uuid" + "github.com/rudecs/terraform-provider-decort/internal/constants" + + "github.com/hashicorp/terraform-plugin-sdk/v2/diag" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" +) + +func dataSourceDiskRead(ctx context.Context, d *schema.ResourceData, m interface{}) diag.Diagnostics { + disk, err := utilityDiskCheckPresence(ctx, d, m) + if err != nil { + return diag.FromErr(err) + } + + id := uuid.New() + d.SetId(id.String()) + + diskAcl, _ := json.Marshal(disk.Acl) + + d.Set("account_id", disk.AccountID) + d.Set("account_name", disk.AccountName) + d.Set("acl", string(diskAcl)) + d.Set("boot_partition", disk.BootPartition) + d.Set("compute_id", disk.ComputeID) + d.Set("compute_name", disk.ComputeName) + d.Set("created_time", disk.CreatedTime) + d.Set("deleted_time", disk.DeletedTime) + d.Set("desc", disk.Desc) + d.Set("destruction_time", disk.DestructionTime) + d.Set("devicename", disk.DeviceName) + d.Set("disk_path", disk.DiskPath) + d.Set("gid", disk.GridID) + d.Set("guid", disk.GUID) + d.Set("disk_id", disk.ID) + d.Set("image_id", disk.ImageID) + d.Set("images", disk.Images) + d.Set("iotune", flattenIOTune(disk.IOTune)) + d.Set("iqn", disk.IQN) + d.Set("login", disk.Login) + d.Set("milestones", disk.Milestones) + d.Set("disk_name", disk.Name) + d.Set("order", disk.Order) + d.Set("params", disk.Params) + d.Set("parent_id", disk.ParentId) + d.Set("passwd", disk.Passwd) + d.Set("pci_slot", disk.PciSlot) + d.Set("pool", disk.Pool) + d.Set("purge_attempts", disk.PurgeAttempts) + d.Set("purge_time", disk.PurgeTime) + d.Set("reality_device_number", disk.RealityDeviceNumber) + d.Set("reference_id", disk.ReferenceId) + d.Set("res_id", disk.ResID) + d.Set("res_name", disk.ResName) + d.Set("role", disk.Role) + d.Set("sep_id", disk.SepID) + d.Set("sep_type", disk.SepType) + d.Set("size_max", disk.SizeMax) + d.Set("size_used", disk.SizeUsed) + d.Set("snapshots", flattendDiskSnapshotList(disk.Snapshots)) + d.Set("status", disk.Status) + d.Set("tech_status", disk.TechStatus) + d.Set("type", disk.Type) + d.Set("vmid", disk.VMID) + + return nil +} + +func dataSourceDiskSchemaMake() map[string]*schema.Schema { + rets := map[string]*schema.Schema{ + "disk_id": { + Type: schema.TypeInt, + Required: true, + }, + "account_id": { + Type: schema.TypeInt, + Computed: true, + }, + "account_name": { + Type: schema.TypeString, + Computed: true, + }, + "acl": { + Type: schema.TypeString, + Computed: true, + }, + "boot_partition": { + Type: schema.TypeInt, + Computed: true, + }, + "compute_id": { + Type: schema.TypeInt, + Computed: true, + }, + "compute_name": { + Type: schema.TypeString, + Computed: true, + }, + "created_time": { + Type: schema.TypeInt, + Computed: true, + }, + "deleted_time": { + Type: schema.TypeInt, + Computed: true, + }, + "desc": { + Type: schema.TypeString, + Computed: true, + }, + "destruction_time": { + Type: schema.TypeInt, + Computed: true, + }, + "devicename": { + Type: schema.TypeString, + Computed: true, + }, + "disk_path": { + Type: schema.TypeString, + Computed: true, + }, + "gid": { + Type: schema.TypeInt, + Computed: true, + }, + "guid": { + Type: schema.TypeInt, + Computed: true, + }, + "image_id": { + Type: schema.TypeInt, + Computed: true, + }, + "images": { + Type: schema.TypeList, + Computed: true, + Elem: &schema.Schema{ + Type: schema.TypeString, + }, + }, + "iotune": { + Type: schema.TypeList, + Computed: true, + Elem: &schema.Resource{ + Schema: map[string]*schema.Schema{ + "read_bytes_sec": { + Type: schema.TypeInt, + Computed: true, + }, + "read_bytes_sec_max": { + Type: schema.TypeInt, + Computed: true, + }, + "read_iops_sec": { + Type: schema.TypeInt, + Computed: true, + }, + "read_iops_sec_max": { + Type: schema.TypeInt, + Computed: true, + }, + "size_iops_sec": { + Type: schema.TypeInt, + Computed: true, + }, + "total_bytes_sec": { + Type: schema.TypeInt, + Computed: true, + }, + "total_bytes_sec_max": { + Type: schema.TypeInt, + Computed: true, + }, + "total_iops_sec": { + Type: schema.TypeInt, + Computed: true, + }, + "total_iops_sec_max": { + Type: schema.TypeInt, + Computed: true, + }, + "write_bytes_sec": { + Type: schema.TypeInt, + Computed: true, + }, + "write_bytes_sec_max": { + Type: schema.TypeInt, + Computed: true, + }, + "write_iops_sec": { + Type: schema.TypeInt, + Computed: true, + }, + "write_iops_sec_max": { + Type: schema.TypeInt, + Computed: true, + }, + }, + }, + }, + "iqn": { + Type: schema.TypeString, + Computed: true, + }, + "login": { + Type: schema.TypeString, + Computed: true, + }, + "milestones": { + Type: schema.TypeInt, + Computed: true, + }, + "disk_name": { + Type: schema.TypeString, + Computed: true, + }, + "order": { + Type: schema.TypeInt, + Computed: true, + }, + "params": { + Type: schema.TypeString, + Computed: true, + }, + "parent_id": { + Type: schema.TypeInt, + Computed: true, + }, + "passwd": { + Type: schema.TypeString, + Computed: true, + }, + "pci_slot": { + Type: schema.TypeInt, + Computed: true, + }, + "pool": { + Type: schema.TypeString, + Computed: true, + }, + "purge_attempts": { + Type: schema.TypeInt, + Computed: true, + }, + "purge_time": { + Type: schema.TypeInt, + Computed: true, + }, + "reality_device_number": { + Type: schema.TypeInt, + Computed: true, + }, + "reference_id": { + Type: schema.TypeString, + Computed: true, + }, + "res_id": { + Type: schema.TypeString, + Computed: true, + }, + "res_name": { + Type: schema.TypeString, + Computed: true, + }, + "role": { + Type: schema.TypeString, + Computed: true, + }, + "sep_id": { + Type: schema.TypeInt, + Computed: true, + }, + "sep_type": { + Type: schema.TypeString, + Computed: true, + }, + "size_max": { + Type: schema.TypeInt, + Computed: true, + }, + "size_used": { + Type: schema.TypeInt, + Computed: true, + }, + "snapshots": { + Type: schema.TypeList, + Computed: true, + Elem: &schema.Resource{ + Schema: map[string]*schema.Schema{ + "guid": { + Type: schema.TypeString, + Computed: true, + }, + "label": { + Type: schema.TypeString, + Computed: true, + }, + "res_id": { + Type: schema.TypeString, + Computed: true, + }, + "snap_set_guid": { + Type: schema.TypeString, + Computed: true, + }, + "snap_set_time": { + Type: schema.TypeInt, + Computed: true, + }, + "timestamp": { + Type: schema.TypeInt, + Computed: true, + }, + }, + }, + }, + "status": { + Type: schema.TypeString, + Computed: true, + }, + "tech_status": { + Type: schema.TypeString, + Computed: true, + }, + "type": { + Type: schema.TypeString, + Computed: true, + }, + "vmid": { + Type: schema.TypeInt, + Computed: true, + }, + } + + return rets +} + +func DataSourceDisk() *schema.Resource { + return &schema.Resource{ + SchemaVersion: 1, + + ReadContext: dataSourceDiskRead, + + Timeouts: &schema.ResourceTimeout{ + Read: &constants.Timeout30s, + Default: &constants.Timeout60s, + }, + + Schema: dataSourceDiskSchemaMake(), + } +} diff --git a/internal/service/cloudbroker/disks/data_source_disk_list.go b/internal/service/cloudbroker/disks/data_source_disk_list.go new file mode 100644 index 0000000..efe16b6 --- /dev/null +++ b/internal/service/cloudbroker/disks/data_source_disk_list.go @@ -0,0 +1,473 @@ +/* +Copyright (c) 2019-2022 Digital Energy Cloud Solutions LLC. All Rights Reserved. +Authors: +Petr Krutov, +Stanislav Solovev, + +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. +*/ + +/* +Terraform DECORT provider - manage resources provided by DECORT (Digital Energy Cloud +Orchestration Technology) with Terraform by Hashicorp. + +Source code: https://github.com/rudecs/terraform-provider-decort + +Please see README.md to learn where to place source code so that it +builds seamlessly. + +Documentation: https://github.com/rudecs/terraform-provider-decort/wiki +*/ + +package disks + +import ( + "context" + "encoding/json" + + "github.com/google/uuid" + "github.com/hashicorp/terraform-plugin-sdk/v2/diag" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" + "github.com/rudecs/terraform-provider-decort/internal/constants" +) + +func flattenIOTune(iot IOTune) []map[string]interface{} { + res := make([]map[string]interface{}, 0) + temp := map[string]interface{}{ + "read_bytes_sec": iot.ReadBytesSec, + "read_bytes_sec_max": iot.ReadBytesSecMax, + "read_iops_sec": iot.ReadIopsSec, + "read_iops_sec_max": iot.ReadIopsSecMax, + "size_iops_sec": iot.SizeIopsSec, + "total_bytes_sec": iot.TotalBytesSec, + "total_bytes_sec_max": iot.TotalBytesSecMax, + "total_iops_sec": iot.TotalIopsSec, + "total_iops_sec_max": iot.TotalIopsSecMax, + "write_bytes_sec": iot.WriteBytesSec, + "write_bytes_sec_max": iot.WriteBytesSecMax, + "write_iops_sec": iot.WriteIopsSec, + "write_iops_sec_max": iot.WriteIopsSecMax, + } + + res = append(res, temp) + return res +} + +func flattenDiskList(dl DisksList) []map[string]interface{} { + res := make([]map[string]interface{}, 0) + for _, disk := range dl { + diskAcl, _ := json.Marshal(disk.Acl) + temp := map[string]interface{}{ + "account_id": disk.AccountID, + "account_name": disk.AccountName, + "acl": string(diskAcl), + "boot_partition": disk.BootPartition, + "compute_id": disk.ComputeID, + "compute_name": disk.ComputeName, + "created_time": disk.CreatedTime, + "deleted_time": disk.DeletedTime, + "desc": disk.Desc, + "destruction_time": disk.DestructionTime, + "devicename": disk.DeviceName, + "disk_path": disk.DiskPath, + "gid": disk.GridID, + "guid": disk.GUID, + "disk_id": disk.ID, + "image_id": disk.ImageID, + "images": disk.Images, + "iotune": flattenIOTune(disk.IOTune), + "iqn": disk.IQN, + "login": disk.Login, + "machine_id": disk.MachineId, + "machine_name": disk.MachineName, + "milestones": disk.Milestones, + "disk_name": disk.Name, + "order": disk.Order, + "params": disk.Params, + "parent_id": disk.ParentId, + "passwd": disk.Passwd, + "pci_slot": disk.PciSlot, + "pool": disk.Pool, + "purge_attempts": disk.PurgeAttempts, + "purge_time": disk.PurgeTime, + "reality_device_number": disk.RealityDeviceNumber, + "reference_id": disk.ReferenceId, + "res_id": disk.ResID, + "res_name": disk.ResName, + "role": disk.Role, + "sep_id": disk.SepID, + "sep_type": disk.SepType, + "size_max": disk.SizeMax, + "size_used": disk.SizeUsed, + "snapshots": flattendDiskSnapshotList(disk.Snapshots), + "status": disk.Status, + "tech_status": disk.TechStatus, + "type": disk.Type, + "vmid": disk.VMID, + } + res = append(res, temp) + } + return res + +} + +func flattendDiskSnapshotList(sl SnapshotList) []interface{} { + res := make([]interface{}, 0) + for _, snapshot := range sl { + temp := map[string]interface{}{ + "guid": snapshot.Guid, + "label": snapshot.Label, + "res_id": snapshot.ResId, + "snap_set_guid": snapshot.SnapSetGuid, + "snap_set_time": snapshot.SnapSetTime, + "timestamp": snapshot.TimeStamp, + } + res = append(res, temp) + } + + return res + +} + +func dataSourceDiskListRead(ctx context.Context, d *schema.ResourceData, m interface{}) diag.Diagnostics { + diskList, err := utilityDiskListCheckPresence(ctx, d, m) + if err != nil { + return diag.FromErr(err) + } + + id := uuid.New() + d.SetId(id.String()) + d.Set("items", flattenDiskList(diskList)) + + return nil +} + +func dataSourceDiskListSchemaMake() map[string]*schema.Schema { + res := map[string]*schema.Schema{ + "account_id": { + Type: schema.TypeInt, + Optional: true, + Description: "ID of the account the disks belong to", + }, + "type": { + Type: schema.TypeString, + Optional: true, + Description: "type of the disks", + }, + "page": { + Type: schema.TypeInt, + Optional: true, + Description: "Page number", + }, + "size": { + Type: schema.TypeInt, + Optional: true, + Description: "Page size", + }, + "items": { + Type: schema.TypeList, + Computed: true, + Elem: &schema.Resource{ + Schema: map[string]*schema.Schema{ + "account_id": { + Type: schema.TypeInt, + Computed: true, + }, + "account_name": { + Type: schema.TypeString, + Computed: true, + }, + "acl": { + Type: schema.TypeString, + Computed: true, + }, + "boot_partition": { + Type: schema.TypeInt, + Computed: true, + }, + "compute_id": { + Type: schema.TypeInt, + Computed: true, + }, + "compute_name": { + Type: schema.TypeString, + Computed: true, + }, + "created_time": { + Type: schema.TypeInt, + Computed: true, + }, + "deleted_time": { + Type: schema.TypeInt, + Computed: true, + }, + "desc": { + Type: schema.TypeString, + Computed: true, + }, + "destruction_time": { + Type: schema.TypeInt, + Computed: true, + }, + "devicename": { + Type: schema.TypeString, + Computed: true, + }, + "disk_path": { + Type: schema.TypeString, + Computed: true, + }, + "gid": { + Type: schema.TypeInt, + Computed: true, + }, + "guid": { + Type: schema.TypeInt, + Computed: true, + }, + "disk_id": { + Type: schema.TypeInt, + Computed: true, + }, + "image_id": { + Type: schema.TypeInt, + Computed: true, + }, + "images": { + Type: schema.TypeList, + Computed: true, + Elem: &schema.Schema{ + Type: schema.TypeString, + }, + }, + "iotune": { + Type: schema.TypeList, + Computed: true, + Elem: &schema.Resource{ + Schema: map[string]*schema.Schema{ + "read_bytes_sec": { + Type: schema.TypeInt, + Computed: true, + }, + "read_bytes_sec_max": { + Type: schema.TypeInt, + Computed: true, + }, + "read_iops_sec": { + Type: schema.TypeInt, + Computed: true, + }, + "read_iops_sec_max": { + Type: schema.TypeInt, + Computed: true, + }, + "size_iops_sec": { + Type: schema.TypeInt, + Computed: true, + }, + "total_bytes_sec": { + Type: schema.TypeInt, + Computed: true, + }, + "total_bytes_sec_max": { + Type: schema.TypeInt, + Computed: true, + }, + "total_iops_sec": { + Type: schema.TypeInt, + Computed: true, + }, + "total_iops_sec_max": { + Type: schema.TypeInt, + Computed: true, + }, + "write_bytes_sec": { + Type: schema.TypeInt, + Computed: true, + }, + "write_bytes_sec_max": { + Type: schema.TypeInt, + Computed: true, + }, + "write_iops_sec": { + Type: schema.TypeInt, + Computed: true, + }, + "write_iops_sec_max": { + Type: schema.TypeInt, + Computed: true, + }, + }, + }, + }, + "iqn": { + Type: schema.TypeString, + Computed: true, + }, + "login": { + Type: schema.TypeString, + Computed: true, + }, + "machine_id": { + Type: schema.TypeInt, + Computed: true, + }, + "machine_name": { + Type: schema.TypeString, + Computed: true, + }, + "milestones": { + Type: schema.TypeInt, + Computed: true, + }, + "disk_name": { + Type: schema.TypeString, + Computed: true, + }, + "order": { + Type: schema.TypeInt, + Computed: true, + }, + "params": { + Type: schema.TypeString, + Computed: true, + }, + "parent_id": { + Type: schema.TypeInt, + Computed: true, + }, + "passwd": { + Type: schema.TypeString, + Computed: true, + }, + "pci_slot": { + Type: schema.TypeInt, + Computed: true, + }, + "pool": { + Type: schema.TypeString, + Computed: true, + }, + "purge_attempts": { + Type: schema.TypeInt, + Computed: true, + }, + "purge_time": { + Type: schema.TypeInt, + Computed: true, + }, + "reality_device_number": { + Type: schema.TypeInt, + Computed: true, + }, + "reference_id": { + Type: schema.TypeString, + Computed: true, + }, + "res_id": { + Type: schema.TypeString, + Computed: true, + }, + "res_name": { + Type: schema.TypeString, + Computed: true, + }, + "role": { + Type: schema.TypeString, + Computed: true, + }, + "sep_id": { + Type: schema.TypeInt, + Computed: true, + }, + "sep_type": { + Type: schema.TypeString, + Computed: true, + }, + "size_max": { + Type: schema.TypeInt, + Computed: true, + }, + "size_used": { + Type: schema.TypeInt, + Computed: true, + }, + "snapshots": { + Type: schema.TypeList, + Computed: true, + Elem: &schema.Resource{ + Schema: map[string]*schema.Schema{ + "guid": { + Type: schema.TypeString, + Computed: true, + }, + "label": { + Type: schema.TypeString, + Computed: true, + }, + "res_id": { + Type: schema.TypeString, + Computed: true, + }, + "snap_set_guid": { + Type: schema.TypeString, + Computed: true, + }, + "snap_set_time": { + Type: schema.TypeInt, + Computed: true, + }, + "timestamp": { + Type: schema.TypeInt, + Computed: true, + }, + }, + }, + }, + "status": { + Type: schema.TypeString, + Computed: true, + }, + "tech_status": { + Type: schema.TypeString, + Computed: true, + }, + "type": { + Type: schema.TypeString, + Computed: true, + }, + "vmid": { + Type: schema.TypeInt, + Computed: true, + }, + }, + }, + }, + } + return res +} + +func DataSourceDiskList() *schema.Resource { + return &schema.Resource{ + SchemaVersion: 1, + + ReadContext: dataSourceDiskListRead, + + Timeouts: &schema.ResourceTimeout{ + Read: &constants.Timeout30s, + Default: &constants.Timeout60s, + }, + + Schema: dataSourceDiskListSchemaMake(), + } +} diff --git a/internal/service/cloudbroker/disks/models.go b/internal/service/cloudbroker/disks/models.go new file mode 100644 index 0000000..b5298e0 --- /dev/null +++ b/internal/service/cloudbroker/disks/models.go @@ -0,0 +1,111 @@ +/* +Copyright (c) 2019-2022 Digital Energy Cloud Solutions LLC. All Rights Reserved. +Authors: +Petr Krutov, +Stanislav Solovev, + +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. +*/ + +/* +Terraform DECORT provider - manage resources provided by DECORT (Digital Energy Cloud +Orchestration Technology) with Terraform by Hashicorp. + +Source code: https://github.com/rudecs/terraform-provider-decort + +Please see README.md to learn where to place source code so that it +builds seamlessly. + +Documentation: https://github.com/rudecs/terraform-provider-decort/wiki +*/ + +package disks + +type Disk struct { + Acl map[string]interface{} `json:"acl"` + AccountID int `json:"accountId"` + AccountName string `json:"accountName"` + BootPartition int `json:"bootPartition"` + CreatedTime uint64 `json:"creationTime"` + ComputeID int `json:"computeId"` + ComputeName string `json:"computeName"` + DeletedTime uint64 `json:"deletionTime"` + DeviceName string `json:"devicename"` + Desc string `json:"desc"` + DestructionTime uint64 `json:"destructionTime"` + DiskPath string `json:"diskPath"` + GridID int `json:"gid"` + GUID int `json:"guid"` + ID uint `json:"id"` + ImageID int `json:"imageId"` + Images []int `json:"images"` + IOTune IOTune `json:"iotune"` + IQN string `json:"iqn"` + Login string `json:"login"` + Name string `json:"name"` + MachineId int `json:"machineId"` + MachineName string `json:"machineName"` + Milestones uint64 `json:"milestones"` + Order int `json:"order"` + Params string `json:"params"` + Passwd string `json:"passwd"` + ParentId int `json:"parentId"` + PciSlot int `json:"pciSlot"` + Pool string `json:"pool"` + PurgeTime uint64 `json:"purgeTime"` + PurgeAttempts uint64 `json:"purgeAttempts"` + RealityDeviceNumber int `json:"realityDeviceNumber"` + ReferenceId string `json:"referenceId"` + ResID string `json:"resId"` + ResName string `json:"resName"` + Role string `json:"role"` + SepType string `json:"sepType"` + SepID int `json:"sepId"` // NOTE: absent from compute/get output + SizeMax int `json:"sizeMax"` + SizeUsed int `json:"sizeUsed"` // sum over all snapshots of this disk to report total consumed space + Snapshots []Snapshot `json:"snapshots"` + Status string `json:"status"` + TechStatus string `json:"techStatus"` + Type string `json:"type"` + UpdateBy uint64 `json:"updateBy"` + VMID int `json:"vmid"` +} + +type Snapshot struct { + Guid string `json:"guid"` + Label string `json:"label"` + ResId string `json:"resId"` + SnapSetGuid string `json:"snapSetGuid"` + SnapSetTime uint64 `json:"snapSetTime"` + TimeStamp uint64 `json:"timestamp"` +} + +type SnapshotList []Snapshot + +type DisksList []Disk + +type IOTune struct { + ReadBytesSec int `json:"read_bytes_sec"` + ReadBytesSecMax int `json:"read_bytes_sec_max"` + ReadIopsSec int `json:"read_iops_sec"` + ReadIopsSecMax int `json:"read_iops_sec_max"` + SizeIopsSec int `json:"size_iops_sec"` + TotalBytesSec int `json:"total_bytes_sec"` + TotalBytesSecMax int `json:"total_bytes_sec_max"` + TotalIopsSec int `json:"total_iops_sec"` + TotalIopsSecMax int `json:"total_iops_sec_max"` + WriteBytesSec int `json:"write_bytes_sec"` + WriteBytesSecMax int `json:"write_bytes_sec_max"` + WriteIopsSec int `json:"write_iops_sec"` + WriteIopsSecMax int `json:"write_iops_sec_max"` +} diff --git a/internal/service/cloudbroker/disks/resource_disk.go b/internal/service/cloudbroker/disks/resource_disk.go new file mode 100644 index 0000000..9cb264b --- /dev/null +++ b/internal/service/cloudbroker/disks/resource_disk.go @@ -0,0 +1,638 @@ +/* +Copyright (c) 2019-2022 Digital Energy Cloud Solutions LLC. All Rights Reserved. +Authors: +Petr Krutov, +Stanislav Solovev, + +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. +*/ + +/* +Terraform DECORT provider - manage resources provided by DECORT (Digital Energy Cloud +Orchestration Technology) with Terraform by Hashicorp. + +Source code: https://github.com/rudecs/terraform-provider-decort + +Please see README.md to learn where to place source code so that it +builds seamlessly. + +Documentation: https://github.com/rudecs/terraform-provider-decort/wiki +*/ + +package disks + +import ( + "context" + "encoding/json" + "fmt" + "net/url" + "strconv" + "strings" + + "github.com/rudecs/terraform-provider-decort/internal/constants" + "github.com/rudecs/terraform-provider-decort/internal/controller" + log "github.com/sirupsen/logrus" + + "github.com/hashicorp/terraform-plugin-sdk/v2/diag" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/validation" +) + +func resourceDiskCreate(ctx context.Context, d *schema.ResourceData, m interface{}) diag.Diagnostics { + c := m.(*controller.ControllerCfg) + urlValues := &url.Values{} + + urlValues.Add("accountId", fmt.Sprintf("%d", d.Get("account_id").(int))) + urlValues.Add("gid", fmt.Sprintf("%d", d.Get("gid").(int))) + urlValues.Add("name", d.Get("disk_name").(string)) + urlValues.Add("size", fmt.Sprintf("%d", d.Get("size_max").(int))) + if typeRaw, ok := d.GetOk("type"); ok { + urlValues.Add("type", strings.ToUpper(typeRaw.(string))) + } else { + urlValues.Add("type", "D") + } + + if sepId, ok := d.GetOk("sep_id"); ok { + urlValues.Add("sep_id", strconv.Itoa(sepId.(int))) + } + + if poolName, ok := d.GetOk("pool"); ok { + urlValues.Add("pool", poolName.(string)) + } + + argVal, argSet := d.GetOk("desc") + if argSet { + urlValues.Add("description", argVal.(string)) + } + + diskId, err := c.DecortAPICall(ctx, "POST", disksCreateAPI, urlValues) + if err != nil { + return diag.FromErr(err) + } + + urlValues = &url.Values{} + + d.SetId(diskId) // update ID of the resource to tell Terraform that the disk resource exists + + if iotuneRaw, ok := d.GetOk("iotune"); ok { + iot := iotuneRaw.([]interface{})[0] + iotune := iot.(map[string]interface{}) + urlValues.Add("diskId", diskId) + urlValues.Add("iops", strconv.Itoa(iotune["total_iops_sec"].(int))) + urlValues.Add("read_bytes_sec", strconv.Itoa(iotune["read_bytes_sec"].(int))) + urlValues.Add("read_bytes_sec_max", strconv.Itoa(iotune["read_bytes_sec_max"].(int))) + urlValues.Add("read_iops_sec", strconv.Itoa(iotune["read_iops_sec"].(int))) + urlValues.Add("read_iops_sec_max", strconv.Itoa(iotune["read_iops_sec_max"].(int))) + urlValues.Add("size_iops_sec", strconv.Itoa(iotune["size_iops_sec"].(int))) + urlValues.Add("total_bytes_sec", strconv.Itoa(iotune["total_bytes_sec"].(int))) + urlValues.Add("total_bytes_sec_max", strconv.Itoa(iotune["total_bytes_sec_max"].(int))) + urlValues.Add("total_iops_sec_max", strconv.Itoa(iotune["total_iops_sec_max"].(int))) + urlValues.Add("write_bytes_sec", strconv.Itoa(iotune["write_bytes_sec"].(int))) + urlValues.Add("write_bytes_sec_max", strconv.Itoa(iotune["write_bytes_sec_max"].(int))) + urlValues.Add("write_iops_sec", strconv.Itoa(iotune["write_iops_sec"].(int))) + urlValues.Add("write_iops_sec_max", strconv.Itoa(iotune["write_iops_sec_max"].(int))) + + _, err := c.DecortAPICall(ctx, "POST", disksIOLimitAPI, urlValues) + if err != nil { + return diag.FromErr(err) + } + + urlValues = &url.Values{} + } + + dgn := resourceDiskRead(ctx, d, m) + if dgn != nil { + return dgn + } + + return nil +} + +func resourceDiskRead(ctx context.Context, d *schema.ResourceData, m interface{}) diag.Diagnostics { + disk, err := utilityDiskCheckPresence(ctx, d, m) + if disk == nil { + d.SetId("") + if err != nil { + return diag.FromErr(err) + } + return nil + } + + diskAcl, _ := json.Marshal(disk.Acl) + + d.Set("account_id", disk.AccountID) + d.Set("account_name", disk.AccountName) + d.Set("acl", string(diskAcl)) + d.Set("boot_partition", disk.BootPartition) + d.Set("compute_id", disk.ComputeID) + d.Set("compute_name", disk.ComputeName) + d.Set("created_time", disk.CreatedTime) + d.Set("deleted_time", disk.DeletedTime) + d.Set("desc", disk.Desc) + d.Set("destruction_time", disk.DestructionTime) + d.Set("devicename", disk.DeviceName) + d.Set("disk_path", disk.DiskPath) + d.Set("gid", disk.GridID) + d.Set("guid", disk.GUID) + d.Set("disk_id", disk.ID) + d.Set("image_id", disk.ImageID) + d.Set("images", disk.Images) + d.Set("iotune", flattenIOTune(disk.IOTune)) + d.Set("iqn", disk.IQN) + d.Set("login", disk.Login) + d.Set("milestones", disk.Milestones) + d.Set("disk_name", disk.Name) + d.Set("order", disk.Order) + d.Set("params", disk.Params) + d.Set("parent_id", disk.ParentId) + d.Set("passwd", disk.Passwd) + d.Set("pci_slot", disk.PciSlot) + d.Set("pool", disk.Pool) + d.Set("purge_attempts", disk.PurgeAttempts) + d.Set("purge_time", disk.PurgeTime) + d.Set("reality_device_number", disk.RealityDeviceNumber) + d.Set("reference_id", disk.ReferenceId) + d.Set("res_id", disk.ResID) + d.Set("res_name", disk.ResName) + d.Set("role", disk.Role) + d.Set("sep_id", disk.SepID) + d.Set("sep_type", disk.SepType) + d.Set("size_max", disk.SizeMax) + d.Set("size_used", disk.SizeUsed) + d.Set("snapshots", flattendDiskSnapshotList(disk.Snapshots)) + d.Set("status", disk.Status) + d.Set("tech_status", disk.TechStatus) + d.Set("type", disk.Type) + d.Set("vmid", disk.VMID) + + return nil +} + +func resourceDiskUpdate(ctx context.Context, d *schema.ResourceData, m interface{}) diag.Diagnostics { + + c := m.(*controller.ControllerCfg) + urlValues := &url.Values{} + + if d.HasChange("size_max") { + oldSize, newSize := d.GetChange("size_max") + if oldSize.(int) < newSize.(int) { + log.Debugf("resourceDiskUpdate: resizing disk ID %s - %d GB -> %d GB", + d.Id(), oldSize.(int), newSize.(int)) + urlValues.Add("diskId", d.Id()) + urlValues.Add("size", fmt.Sprintf("%d", newSize.(int))) + _, err := c.DecortAPICall(ctx, "POST", disksResizeAPI, urlValues) + if err != nil { + return diag.FromErr(err) + } + d.Set("size_max", newSize) + } else if oldSize.(int) > newSize.(int) { + return diag.FromErr(fmt.Errorf("resourceDiskUpdate: Disk ID %s - reducing disk size is not allowed", d.Id())) + } + urlValues = &url.Values{} + } + + if d.HasChange("disk_name") { + urlValues.Add("diskId", d.Id()) + urlValues.Add("name", d.Get("disk_name").(string)) + _, err := c.DecortAPICall(ctx, "POST", disksRenameAPI, urlValues) + if err != nil { + return diag.FromErr(err) + } + + urlValues = &url.Values{} + } + + if d.HasChange("iotune") { + iot := d.Get("iotune").([]interface{})[0] + iotune := iot.(map[string]interface{}) + urlValues.Add("diskId", d.Id()) + urlValues.Add("iops", strconv.Itoa(iotune["total_iops_sec"].(int))) + urlValues.Add("read_bytes_sec", strconv.Itoa(iotune["read_bytes_sec"].(int))) + urlValues.Add("read_bytes_sec_max", strconv.Itoa(iotune["read_bytes_sec_max"].(int))) + urlValues.Add("read_iops_sec", strconv.Itoa(iotune["read_iops_sec"].(int))) + urlValues.Add("read_iops_sec_max", strconv.Itoa(iotune["read_iops_sec_max"].(int))) + urlValues.Add("size_iops_sec", strconv.Itoa(iotune["size_iops_sec"].(int))) + urlValues.Add("total_bytes_sec", strconv.Itoa(iotune["total_bytes_sec"].(int))) + urlValues.Add("total_bytes_sec_max", strconv.Itoa(iotune["total_bytes_sec_max"].(int))) + urlValues.Add("total_iops_sec_max", strconv.Itoa(iotune["total_iops_sec_max"].(int))) + urlValues.Add("write_bytes_sec", strconv.Itoa(iotune["write_bytes_sec"].(int))) + urlValues.Add("write_bytes_sec_max", strconv.Itoa(iotune["write_bytes_sec_max"].(int))) + urlValues.Add("write_iops_sec", strconv.Itoa(iotune["write_iops_sec"].(int))) + urlValues.Add("write_iops_sec_max", strconv.Itoa(iotune["write_iops_sec_max"].(int))) + + _, err := c.DecortAPICall(ctx, "POST", disksIOLimitAPI, urlValues) + if err != nil { + return diag.FromErr(err) + } + + urlValues = &url.Values{} + } + + if d.HasChange("restore") { + if d.Get("restore").(bool) { + urlValues.Add("diskId", d.Id()) + urlValues.Add("reason", d.Get("reason").(string)) + + _, err := c.DecortAPICall(ctx, "POST", disksRestoreAPI, urlValues) + if err != nil { + return diag.FromErr(err) + } + + urlValues = &url.Values{} + } + + } + + return resourceDiskRead(ctx, d, m) +} + +func resourceDiskDelete(ctx context.Context, d *schema.ResourceData, m interface{}) diag.Diagnostics { + + disk, err := utilityDiskCheckPresence(ctx, d, m) + if disk == nil { + if err != nil { + return diag.FromErr(err) + } + return nil + } + + params := &url.Values{} + params.Add("diskId", d.Id()) + params.Add("detach", strconv.FormatBool(d.Get("detach").(bool))) + params.Add("permanently", strconv.FormatBool(d.Get("permanently").(bool))) + params.Add("reason", d.Get("reason").(string)) + + c := m.(*controller.ControllerCfg) + _, err = c.DecortAPICall(ctx, "POST", disksDeleteAPI, params) + if err != nil { + return diag.FromErr(err) + } + + return nil +} + +func resourceDiskExists(ctx context.Context, d *schema.ResourceData, m interface{}) (bool, error) { + + diskFacts, err := utilityDiskCheckPresence(ctx, d, m) + if diskFacts == nil { + if err != nil { + return false, err + } + return false, nil + } + return true, nil +} + +func resourceDiskSchemaMake() map[string]*schema.Schema { + rets := map[string]*schema.Schema{ + "account_id": { + Type: schema.TypeInt, + Required: true, + }, + "disk_name": { + Type: schema.TypeString, + Required: true, + }, + "size_max": { + Type: schema.TypeInt, + Required: true, + }, + "gid": { + Type: schema.TypeInt, + Required: true, + }, + "pool": { + Type: schema.TypeString, + Optional: true, + Computed: true, + }, + "sep_id": { + Type: schema.TypeInt, + Optional: true, + Computed: true, + }, + "desc": { + Type: schema.TypeString, + Optional: true, + Computed: true, + }, + "type": { + Type: schema.TypeString, + Optional: true, + Computed: true, + ValidateFunc: validation.StringInSlice([]string{"D", "B", "T"}, false), + }, + + "detach": { + Type: schema.TypeBool, + Optional: true, + Default: false, + Description: "detach disk from machine first", + }, + "permanently": { + Type: schema.TypeBool, + Optional: true, + Default: false, + Description: "whether to completely delete the disk, works only with non attached disks", + }, + "reason": { + Type: schema.TypeString, + Optional: true, + Default: "", + Description: "reason for an action", + }, + "restore": { + Type: schema.TypeBool, + Optional: true, + Default: false, + Description: "restore deleting disk", + }, + + "disk_id": { + Type: schema.TypeInt, + Computed: true, + }, + "account_name": { + Type: schema.TypeString, + Computed: true, + }, + "acl": { + Type: schema.TypeString, + Computed: true, + }, + "boot_partition": { + Type: schema.TypeInt, + Computed: true, + }, + "compute_id": { + Type: schema.TypeInt, + Computed: true, + }, + "compute_name": { + Type: schema.TypeString, + Computed: true, + }, + "created_time": { + Type: schema.TypeInt, + Computed: true, + }, + "deleted_time": { + Type: schema.TypeInt, + Computed: true, + }, + "destruction_time": { + Type: schema.TypeInt, + Computed: true, + }, + "devicename": { + Type: schema.TypeString, + Computed: true, + }, + "disk_path": { + Type: schema.TypeString, + Computed: true, + }, + "guid": { + Type: schema.TypeInt, + Computed: true, + }, + "image_id": { + Type: schema.TypeInt, + Computed: true, + }, + "images": { + Type: schema.TypeList, + Computed: true, + Elem: &schema.Schema{ + Type: schema.TypeString, + }, + }, + "iotune": { + Type: schema.TypeList, + Optional: true, + MaxItems: 1, + Computed: true, + Elem: &schema.Resource{ + Schema: map[string]*schema.Schema{ + "read_bytes_sec": { + Type: schema.TypeInt, + Optional: true, + Computed: true, + }, + "read_bytes_sec_max": { + Type: schema.TypeInt, + Optional: true, + Computed: true, + }, + "read_iops_sec": { + Type: schema.TypeInt, + Optional: true, + Computed: true, + }, + "read_iops_sec_max": { + Type: schema.TypeInt, + Optional: true, + Computed: true, + }, + "size_iops_sec": { + Type: schema.TypeInt, + Optional: true, + Computed: true, + }, + "total_bytes_sec": { + Type: schema.TypeInt, + Optional: true, + Computed: true, + }, + "total_bytes_sec_max": { + Type: schema.TypeInt, + Optional: true, + Computed: true, + }, + "total_iops_sec": { + Type: schema.TypeInt, + Optional: true, + Computed: true, + }, + "total_iops_sec_max": { + Type: schema.TypeInt, + Optional: true, + Computed: true, + }, + "write_bytes_sec": { + Type: schema.TypeInt, + Optional: true, + Computed: true, + }, + "write_bytes_sec_max": { + Type: schema.TypeInt, + Optional: true, + Computed: true, + }, + "write_iops_sec": { + Type: schema.TypeInt, + Optional: true, + Computed: true, + }, + "write_iops_sec_max": { + Type: schema.TypeInt, + Optional: true, + Computed: true, + }, + }, + }, + }, + "iqn": { + Type: schema.TypeString, + Computed: true, + }, + "login": { + Type: schema.TypeString, + Computed: true, + }, + "milestones": { + Type: schema.TypeInt, + Computed: true, + }, + + "order": { + Type: schema.TypeInt, + Computed: true, + }, + "params": { + Type: schema.TypeString, + Computed: true, + }, + "parent_id": { + Type: schema.TypeInt, + Computed: true, + }, + "passwd": { + Type: schema.TypeString, + Computed: true, + }, + "pci_slot": { + Type: schema.TypeInt, + Computed: true, + }, + + "purge_attempts": { + Type: schema.TypeInt, + Computed: true, + }, + "purge_time": { + Type: schema.TypeInt, + Computed: true, + }, + "reality_device_number": { + Type: schema.TypeInt, + Computed: true, + }, + "reference_id": { + Type: schema.TypeString, + Computed: true, + }, + "res_id": { + Type: schema.TypeString, + Computed: true, + }, + "res_name": { + Type: schema.TypeString, + Computed: true, + }, + "role": { + Type: schema.TypeString, + Computed: true, + }, + + "sep_type": { + Type: schema.TypeString, + Computed: true, + }, + "size_used": { + Type: schema.TypeInt, + Computed: true, + }, + "snapshots": { + Type: schema.TypeList, + Computed: true, + Elem: &schema.Resource{ + Schema: map[string]*schema.Schema{ + "guid": { + Type: schema.TypeString, + Computed: true, + }, + "label": { + Type: schema.TypeString, + Computed: true, + }, + "res_id": { + Type: schema.TypeString, + Computed: true, + }, + "snap_set_guid": { + Type: schema.TypeString, + Computed: true, + }, + "snap_set_time": { + Type: schema.TypeInt, + Computed: true, + }, + "timestamp": { + Type: schema.TypeInt, + Computed: true, + }, + }, + }, + }, + "status": { + Type: schema.TypeString, + Computed: true, + }, + "tech_status": { + Type: schema.TypeString, + Computed: true, + }, + "vmid": { + Type: schema.TypeInt, + Computed: true, + }, + } + + return rets +} + +func ResourceDisk() *schema.Resource { + return &schema.Resource{ + SchemaVersion: 1, + + CreateContext: resourceDiskCreate, + ReadContext: resourceDiskRead, + UpdateContext: resourceDiskUpdate, + DeleteContext: resourceDiskDelete, + + Importer: &schema.ResourceImporter{ + State: schema.ImportStatePassthrough, + }, + + Timeouts: &schema.ResourceTimeout{ + Create: &constants.Timeout180s, + Read: &constants.Timeout30s, + Update: &constants.Timeout180s, + Delete: &constants.Timeout60s, + Default: &constants.Timeout60s, + }, + + Schema: resourceDiskSchemaMake(), + } +} diff --git a/internal/service/cloudbroker/disks/utility_disk.go b/internal/service/cloudbroker/disks/utility_disk.go new file mode 100644 index 0000000..1fb4544 --- /dev/null +++ b/internal/service/cloudbroker/disks/utility_disk.go @@ -0,0 +1,70 @@ +/* +Copyright (c) 2019-2022 Digital Energy Cloud Solutions LLC. All Rights Reserved. +Authors: +Petr Krutov, +Stanislav Solovev, + +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. +*/ + +/* +Terraform DECORT provider - manage resources provided by DECORT (Digital Energy Cloud +Orchestration Technology) with Terraform by Hashicorp. + +Source code: https://github.com/rudecs/terraform-provider-decort + +Please see README.md to learn where to place source code so that it +builds seamlessly. + +Documentation: https://github.com/rudecs/terraform-provider-decort/wiki +*/ + +package disks + +import ( + "context" + "encoding/json" + "net/url" + "strconv" + + "github.com/rudecs/terraform-provider-decort/internal/controller" + log "github.com/sirupsen/logrus" + + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" +) + +func utilityDiskCheckPresence(ctx context.Context, d *schema.ResourceData, m interface{}) (*Disk, error) { + c := m.(*controller.ControllerCfg) + urlValues := &url.Values{} + + disk := &Disk{} + + if d.Get("disk_id").(int) == 0 { + urlValues.Add("diskId", d.Id()) + } else { + urlValues.Add("diskId", strconv.Itoa(d.Get("disk_id").(int))) + } + + log.Debugf("utilityDiskCheckPresence: load disk") + diskRaw, err := c.DecortAPICall(ctx, "POST", disksGetAPI, urlValues) + if err != nil { + return nil, err + } + + err = json.Unmarshal([]byte(diskRaw), disk) + if err != nil { + return nil, err + } + + return disk, nil +} diff --git a/internal/service/cloudbroker/disks/utility_disk_list.go b/internal/service/cloudbroker/disks/utility_disk_list.go new file mode 100644 index 0000000..1782ac3 --- /dev/null +++ b/internal/service/cloudbroker/disks/utility_disk_list.go @@ -0,0 +1,77 @@ +/* +Copyright (c) 2019-2022 Digital Energy Cloud Solutions LLC. All Rights Reserved. +Authors: +Petr Krutov, +Stanislav Solovev, + +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. +*/ + +/* +Terraform DECORT provider - manage resources provided by DECORT (Digital Energy Cloud +Orchestration Technology) with Terraform by Hashicorp. + +Source code: https://github.com/rudecs/terraform-provider-decort + +Please see README.md to learn where to place source code so that it +builds seamlessly. + +Documentation: https://github.com/rudecs/terraform-provider-decort/wiki +*/ + +package disks + +import ( + "context" + "encoding/json" + "net/url" + "strconv" + "strings" + + "github.com/rudecs/terraform-provider-decort/internal/controller" + log "github.com/sirupsen/logrus" + + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" +) + +func utilityDiskListCheckPresence(ctx context.Context, d *schema.ResourceData, m interface{}) (DisksList, error) { + diskList := DisksList{} + c := m.(*controller.ControllerCfg) + urlValues := &url.Values{} + + if page, ok := d.GetOk("page"); ok { + urlValues.Add("page", strconv.Itoa(page.(int))) + } + if size, ok := d.GetOk("size"); ok { + urlValues.Add("size", strconv.Itoa(size.(int))) + } + if diskType, ok := d.GetOk("type"); ok { + urlValues.Add("type", strings.ToUpper(diskType.(string))) + } + if accountId, ok := d.GetOk("accountId"); ok { + urlValues.Add("accountId", strconv.Itoa(accountId.(int))) + } + + log.Debugf("utilityDiskListCheckPresence: load disk list") + diskListRaw, err := c.DecortAPICall(ctx, "POST", disksListAPI, urlValues) + if err != nil { + return nil, err + } + + err = json.Unmarshal([]byte(diskListRaw), &diskList) + if err != nil { + return nil, err + } + + return diskList, nil +} diff --git a/internal/service/cloudbroker/k8s/api.go b/internal/service/cloudbroker/k8s/api.go new file mode 100644 index 0000000..125f0a2 --- /dev/null +++ b/internal/service/cloudbroker/k8s/api.go @@ -0,0 +1,49 @@ +/* +Copyright (c) 2019-2022 Digital Energy Cloud Solutions LLC. All Rights Reserved. +Authors: +Petr Krutov, +Stanislav Solovev, + +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. +*/ + +/* +Terraform DECORT provider - manage resources provided by DECORT (Digital Energy Cloud +Orchestration Technology) with Terraform by Hashicorp. + +Source code: https://github.com/rudecs/terraform-provider-decort + +Please see README.md to learn where to place source code so that it +builds seamlessly. + +Documentation: https://github.com/rudecs/terraform-provider-decort/wiki +*/ + +package k8s + +const K8sCreateAPI = "/restmachine/cloudbroker/k8s/create" +const K8sGetAPI = "/restmachine/cloudbroker/k8s/get" +const K8sUpdateAPI = "/restmachine/cloudbroker/k8s/update" +const K8sDeleteAPI = "/restmachine/cloudbroker/k8s/delete" + +const K8sWgCreateAPI = "/restmachine/cloudbroker/k8s/workersGroupAdd" +const K8sWgDeleteAPI = "/restmachine/cloudbroker/k8s/workersGroupDelete" + +const K8sWorkerAddAPI = "/restmachine/cloudbroker/k8s/workerAdd" +const K8sWorkerDeleteAPI = "/restmachine/cloudbroker/k8s/deleteWorkerFromGroup" + +const K8sGetConfigAPI = "/restmachine/cloudbroker/k8s/getConfig" + +const LbGetAPI = "/restmachine/cloudbroker/lb/get" + +const AsyncTaskGetAPI = "/restmachine/cloudbroker/tasks/get" diff --git a/internal/service/cloudbroker/k8s/models.go b/internal/service/cloudbroker/k8s/models.go new file mode 100644 index 0000000..7634dd0 --- /dev/null +++ b/internal/service/cloudbroker/k8s/models.go @@ -0,0 +1,131 @@ +/* +Copyright (c) 2019-2022 Digital Energy Cloud Solutions LLC. All Rights Reserved. +Authors: +Petr Krutov, +Stanislav Solovev, + +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. +*/ + +/* +Terraform DECORT provider - manage resources provided by DECORT (Digital Energy Cloud +Orchestration Technology) with Terraform by Hashicorp. + +Source code: https://github.com/rudecs/terraform-provider-decort + +Please see README.md to learn where to place source code so that it +builds seamlessly. + +Documentation: https://github.com/rudecs/terraform-provider-decort/wiki +*/ + +package k8s + +import ( + "encoding/json" + "fmt" + "strconv" +) + +type K8sNodeRecord struct { + ID int `json:"id"` + Name string `json:"name"` + Disk int `json:"disk"` + Cpu int `json:"cpu"` + Num int `json:"num"` + Ram int `json:"ram"` + DetailedInfo []struct { + ID int `json:"id"` + Name string `json:"name"` + } `json:"detailedInfo"` +} + +//K8sRecord represents k8s instance +type K8sRecord struct { + AccountID int `json:"accountId"` + AccountName string `json:"accountName"` + CI int `json:"ciId"` + ID int `json:"id"` + Groups struct { + Masters K8sNodeRecord `json:"masters"` + Workers []K8sNodeRecord `json:"workers"` + } `json:"k8sGroups"` + LbID int `json:"lbId"` + Name string `json:"name"` + RgID int `json:"rgId"` + RgName string `json:"rgName"` +} + +//LbRecord represents load balancer instance +type LbRecord struct { + ID int `json:"id"` + Name string `json:"name"` + RgID int `json:"rgId"` + VinsID int `json:"vinsId"` + ExtNetID int `json:"extnetId"` + PrimaryNode struct { + BackendIP string `json:"backendIp"` + ComputeID int `json:"computeId"` + FrontendIP string `json:"frontendIp"` + NetworkID int `json:"networkId"` + } `json:"primaryNode"` +} + +//Blasphemous workaround for parsing Result value +type TaskResult int + +func (r *TaskResult) UnmarshalJSON(b []byte) error { + if b[0] == '"' { + b := b[1 : len(b)-1] + if len(b) == 0 { + *r = 0 + return nil + } + n, err := strconv.Atoi(string(b)) + if err != nil { + return err + } + *r = TaskResult(n) + } else if b[0] == '[' { + res := []interface{}{} + if err := json.Unmarshal(b, &res); err != nil { + return err + } + if n, ok := res[0].(float64); ok { + *r = TaskResult(n) + } else { + return fmt.Errorf("could not unmarshal %v into int", res[0]) + } + } + + return nil +} + +//AsyncTask represents a long task completion status +type AsyncTask struct { + AuditID string `json:"auditId"` + Completed bool `json:"completed"` + Error string `json:"error"` + Log []string `json:"log"` + Result TaskResult `json:"result"` + Stage string `json:"stage"` + Status string `json:"status"` + UpdateTime uint64 `json:"updateTime"` + UpdatedTime uint64 `json:"updatedTime"` +} + +type SshKeyConfig struct { + User string + SshKey string + UserShell string +} diff --git a/internal/service/cloudbroker/k8s/node_subresource.go b/internal/service/cloudbroker/k8s/node_subresource.go new file mode 100644 index 0000000..78fc9ce --- /dev/null +++ b/internal/service/cloudbroker/k8s/node_subresource.go @@ -0,0 +1,105 @@ +/* +Copyright (c) 2019-2022 Digital Energy Cloud Solutions LLC. All Rights Reserved. +Authors: +Petr Krutov, +Stanislav Solovev, + +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. +*/ + +/* +Terraform DECORT provider - manage resources provided by DECORT (Digital Energy Cloud +Orchestration Technology) with Terraform by Hashicorp. + +Source code: https://github.com/rudecs/terraform-provider-decort + +Please see README.md to learn where to place source code so that it +builds seamlessly. + +Documentation: https://github.com/rudecs/terraform-provider-decort/wiki +*/ + +package k8s + +import "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" + +func nodeMasterDefault() K8sNodeRecord { + return K8sNodeRecord{ + Num: 1, + Cpu: 2, + Ram: 2048, + Disk: 0, + } +} + +func nodeWorkerDefault() K8sNodeRecord { + return K8sNodeRecord{ + Num: 1, + Cpu: 1, + Ram: 1024, + Disk: 0, + } +} + +func parseNode(nodeList []interface{}) K8sNodeRecord { + node := nodeList[0].(map[string]interface{}) + + return K8sNodeRecord{ + Num: node["num"].(int), + Cpu: node["cpu"].(int), + Ram: node["ram"].(int), + Disk: node["disk"].(int), + } +} + +func nodeToResource(node K8sNodeRecord) []interface{} { + mp := make(map[string]interface{}) + + mp["num"] = node.Num + mp["cpu"] = node.Cpu + mp["ram"] = node.Ram + mp["disk"] = node.Disk + + return []interface{}{mp} +} + +func nodeK8sSubresourceSchemaMake() map[string]*schema.Schema { + return map[string]*schema.Schema{ + "num": { + Type: schema.TypeInt, + Required: true, + Description: "Number of nodes to create.", + }, + + "cpu": { + Type: schema.TypeInt, + Required: true, + ForceNew: true, + Description: "Node CPU count.", + }, + + "ram": { + Type: schema.TypeInt, + Required: true, + ForceNew: true, + Description: "Node RAM in MB.", + }, + + "disk": { + Type: schema.TypeInt, + Required: true, + ForceNew: true, + Description: "Node boot disk size in GB.", + }, + } +} diff --git a/internal/service/cloudbroker/k8s/resource_k8s.go b/internal/service/cloudbroker/k8s/resource_k8s.go new file mode 100644 index 0000000..a7f6301 --- /dev/null +++ b/internal/service/cloudbroker/k8s/resource_k8s.go @@ -0,0 +1,403 @@ +/* +Copyright (c) 2019-2022 Digital Energy Cloud Solutions LLC. All Rights Reserved. +Authors: +Petr Krutov, +Stanislav Solovev, + +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. +*/ + +/* +Terraform DECORT provider - manage resources provided by DECORT (Digital Energy Cloud +Orchestration Technology) with Terraform by Hashicorp. + +Source code: https://github.com/rudecs/terraform-provider-decort + +Please see README.md to learn where to place source code so that it +builds seamlessly. + +Documentation: https://github.com/rudecs/terraform-provider-decort/wiki +*/ + +package k8s + +import ( + "context" + "encoding/json" + "fmt" + "net/url" + "strconv" + "strings" + "time" + + "github.com/hashicorp/terraform-plugin-sdk/v2/diag" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" + "github.com/rudecs/terraform-provider-decort/internal/constants" + "github.com/rudecs/terraform-provider-decort/internal/controller" + log "github.com/sirupsen/logrus" +) + +func resourceK8sCreate(ctx context.Context, d *schema.ResourceData, m interface{}) diag.Diagnostics { + log.Debugf("resourceK8sCreate: called with name %s, rg %d", d.Get("name").(string), d.Get("rg_id").(int)) + + c := m.(*controller.ControllerCfg) + urlValues := &url.Values{} + urlValues.Add("name", d.Get("name").(string)) + urlValues.Add("rgId", strconv.Itoa(d.Get("rg_id").(int))) + urlValues.Add("k8ciId", strconv.Itoa(d.Get("k8sci_id").(int))) + urlValues.Add("workerGroupName", d.Get("wg_name").(string)) + + var masterNode K8sNodeRecord + if masters, ok := d.GetOk("masters"); ok { + masterNode = parseNode(masters.([]interface{})) + } else { + masterNode = nodeMasterDefault() + } + urlValues.Add("masterNum", strconv.Itoa(masterNode.Num)) + urlValues.Add("masterCpu", strconv.Itoa(masterNode.Cpu)) + urlValues.Add("masterRam", strconv.Itoa(masterNode.Ram)) + urlValues.Add("masterDisk", strconv.Itoa(masterNode.Disk)) + + var workerNode K8sNodeRecord + if workers, ok := d.GetOk("workers"); ok { + workerNode = parseNode(workers.([]interface{})) + } else { + workerNode = nodeWorkerDefault() + } + urlValues.Add("workerNum", strconv.Itoa(workerNode.Num)) + urlValues.Add("workerCpu", strconv.Itoa(workerNode.Cpu)) + urlValues.Add("workerRam", strconv.Itoa(workerNode.Ram)) + urlValues.Add("workerDisk", strconv.Itoa(workerNode.Disk)) + + //if withLB, ok := d.GetOk("with_lb"); ok { + //urlValues.Add("withLB", strconv.FormatBool(withLB.(bool))) + //} + urlValues.Add("withLB", strconv.FormatBool(true)) + + if extNet, ok := d.GetOk("extnet_id"); ok { + urlValues.Add("extnetId", strconv.Itoa(extNet.(int))) + } else { + urlValues.Add("extnetId", "0") + } + + //if desc, ok := d.GetOk("desc"); ok { + //urlValues.Add("desc", desc.(string)) + //} + + resp, err := c.DecortAPICall(ctx, "POST", K8sCreateAPI, urlValues) + if err != nil { + return diag.FromErr(err) + } + + urlValues = &url.Values{} + urlValues.Add("auditId", strings.Trim(resp, `"`)) + + for { + resp, err := c.DecortAPICall(ctx, "POST", AsyncTaskGetAPI, urlValues) + if err != nil { + return diag.FromErr(err) + } + + task := AsyncTask{} + if err := json.Unmarshal([]byte(resp), &task); err != nil { + return diag.FromErr(err) + } + log.Debugf("resourceK8sCreate: instance creating - %s", task.Stage) + + if task.Completed { + if task.Error != "" { + return diag.FromErr(fmt.Errorf("cannot create k8s instance: %v", task.Error)) + } + + d.SetId(strconv.Itoa(int(task.Result))) + break + } + + time.Sleep(time.Second * 10) + } + + k8s, err := utilityK8sCheckPresence(ctx, d, m) + if err != nil { + return diag.FromErr(err) + } + + d.Set("default_wg_id", k8s.Groups.Workers[0].ID) + + urlValues = &url.Values{} + urlValues.Add("lbId", strconv.Itoa(k8s.LbID)) + + resp, err = c.DecortAPICall(ctx, "POST", LbGetAPI, urlValues) + if err != nil { + return diag.FromErr(err) + } + + var lb LbRecord + if err := json.Unmarshal([]byte(resp), &lb); err != nil { + return diag.FromErr(err) + } + d.Set("extnet_id", lb.ExtNetID) + d.Set("lb_ip", lb.PrimaryNode.FrontendIP) + + urlValues = &url.Values{} + urlValues.Add("k8sId", d.Id()) + kubeconfig, err := c.DecortAPICall(ctx, "POST", K8sGetConfigAPI, urlValues) + if err != nil { + log.Warnf("could not get kubeconfig: %v", err) + } + d.Set("kubeconfig", kubeconfig) + + return nil +} + +func resourceK8sRead(ctx context.Context, d *schema.ResourceData, m interface{}) diag.Diagnostics { + log.Debugf("resourceK8sRead: called with id %s, rg %d", d.Id(), d.Get("rg_id").(int)) + + k8s, err := utilityK8sCheckPresence(ctx, d, m) + if k8s == nil { + d.SetId("") + return diag.FromErr(err) + } + + d.Set("name", k8s.Name) + d.Set("rg_id", k8s.RgID) + d.Set("k8sci_id", k8s.CI) + d.Set("wg_name", k8s.Groups.Workers[0].Name) + d.Set("masters", nodeToResource(k8s.Groups.Masters)) + d.Set("workers", nodeToResource(k8s.Groups.Workers[0])) + d.Set("default_wg_id", k8s.Groups.Workers[0].ID) + + c := m.(*controller.ControllerCfg) + urlValues := &url.Values{} + urlValues.Add("lbId", strconv.Itoa(k8s.LbID)) + + resp, err := c.DecortAPICall(ctx, "POST", LbGetAPI, urlValues) + if err != nil { + return diag.FromErr(err) + } + + var lb LbRecord + if err := json.Unmarshal([]byte(resp), &lb); err != nil { + return diag.FromErr(err) + } + d.Set("extnet_id", lb.ExtNetID) + d.Set("lb_ip", lb.PrimaryNode.FrontendIP) + + urlValues = &url.Values{} + urlValues.Add("k8sId", d.Id()) + kubeconfig, err := c.DecortAPICall(ctx, "POST", K8sGetConfigAPI, urlValues) + if err != nil { + log.Warnf("could not get kubeconfig: %v", err) + } + d.Set("kubeconfig", kubeconfig) + + return nil +} + +func resourceK8sUpdate(ctx context.Context, d *schema.ResourceData, m interface{}) diag.Diagnostics { + log.Debugf("resourceK8sUpdate: called with id %s, rg %d", d.Id(), d.Get("rg_id").(int)) + + c := m.(*controller.ControllerCfg) + + if d.HasChange("name") { + urlValues := &url.Values{} + urlValues.Add("k8sId", d.Id()) + urlValues.Add("name", d.Get("name").(string)) + + _, err := c.DecortAPICall(ctx, "POST", K8sUpdateAPI, urlValues) + if err != nil { + return diag.FromErr(err) + } + } + + if d.HasChange("workers") { + k8s, err := utilityK8sCheckPresence(ctx, d, m) + if err != nil { + return diag.FromErr(err) + } + + wg := k8s.Groups.Workers[0] + urlValues := &url.Values{} + urlValues.Add("k8sId", d.Id()) + urlValues.Add("workersGroupId", strconv.Itoa(wg.ID)) + + newWorkers := parseNode(d.Get("workers").([]interface{})) + + if newWorkers.Num > wg.Num { + urlValues.Add("num", strconv.Itoa(newWorkers.Num-wg.Num)) + if _, err := c.DecortAPICall(ctx, "POST", K8sWorkerAddAPI, urlValues); err != nil { + return diag.FromErr(err) + } + } else { + for i := wg.Num - 1; i >= newWorkers.Num; i-- { + urlValues.Set("workerId", strconv.Itoa(wg.DetailedInfo[i].ID)) + if _, err := c.DecortAPICall(ctx, "POST", K8sWorkerDeleteAPI, urlValues); err != nil { + return diag.FromErr(err) + } + } + } + } + + return nil +} + +func resourceK8sDelete(ctx context.Context, d *schema.ResourceData, m interface{}) diag.Diagnostics { + log.Debugf("resourceK8sDelete: called with id %s, rg %d", d.Id(), d.Get("rg_id").(int)) + + k8s, err := utilityK8sCheckPresence(ctx, d, m) + if k8s == nil { + if err != nil { + return diag.FromErr(err) + } + return nil + } + + c := m.(*controller.ControllerCfg) + urlValues := &url.Values{} + urlValues.Add("k8sId", d.Id()) + urlValues.Add("permanently", "true") + + _, err = c.DecortAPICall(ctx, "POST", K8sDeleteAPI, urlValues) + if err != nil { + return diag.FromErr(err) + } + + return nil +} + +func resourceK8sExists(ctx context.Context, d *schema.ResourceData, m interface{}) (bool, error) { + log.Debugf("resourceK8sExists: called with id %s, rg %d", d.Id(), d.Get("rg_id").(int)) + + k8s, err := utilityK8sCheckPresence(ctx, d, m) + if k8s == nil { + return false, err + } + + return true, nil +} + +func resourceK8sSchemaMake() map[string]*schema.Schema { + return map[string]*schema.Schema{ + "name": { + Type: schema.TypeString, + Required: true, + Description: "Name of the cluster.", + }, + + "rg_id": { + Type: schema.TypeInt, + Required: true, + ForceNew: true, + Description: "Resource group ID that this instance belongs to.", + }, + + "k8sci_id": { + Type: schema.TypeInt, + Required: true, + ForceNew: true, + Description: "ID of the k8s catalog item to base this instance on.", + }, + + "wg_name": { + Type: schema.TypeString, + Required: true, + ForceNew: true, + Description: "Name for first worker group created with cluster.", + }, + + "masters": { + Type: schema.TypeList, + Optional: true, + ForceNew: true, + MaxItems: 1, + Elem: &schema.Resource{ + Schema: nodeK8sSubresourceSchemaMake(), + }, + Description: "Master node(s) configuration.", + }, + + "workers": { + Type: schema.TypeList, + Optional: true, + MaxItems: 1, + Elem: &schema.Resource{ + Schema: nodeK8sSubresourceSchemaMake(), + }, + Description: "Worker node(s) configuration.", + }, + + //"with_lb": { + //Type: schema.TypeBool, + //Optional: true, + //ForceNew: true, + //Default: true, + //Description: "Create k8s with load balancer if true.", + //}, + + "extnet_id": { + Type: schema.TypeInt, + Optional: true, + Computed: true, + ForceNew: true, + Description: "ID of the external network to connect workers to. If omitted network will be chosen by the platfom.", + }, + + //"desc": { + //Type: schema.TypeString, + //Optional: true, + //Description: "Text description of this instance.", + //}, + + "lb_ip": { + Type: schema.TypeString, + Computed: true, + Description: "IP address of default load balancer.", + }, + + "default_wg_id": { + Type: schema.TypeInt, + Computed: true, + Description: "ID of default workers group for this instace.", + }, + + "kubeconfig": { + Type: schema.TypeString, + Computed: true, + Description: "Kubeconfig for cluster access.", + }, + } +} + +func ResourceK8s() *schema.Resource { + return &schema.Resource{ + SchemaVersion: 1, + + CreateContext: resourceK8sCreate, + ReadContext: resourceK8sRead, + UpdateContext: resourceK8sUpdate, + DeleteContext: resourceK8sDelete, + + Importer: &schema.ResourceImporter{ + State: schema.ImportStatePassthrough, + }, + + Timeouts: &schema.ResourceTimeout{ + Create: &constants.Timeout20m, + Read: &constants.Timeout30s, + Update: &constants.Timeout20m, + Delete: &constants.Timeout60s, + Default: &constants.Timeout60s, + }, + + Schema: resourceK8sSchemaMake(), + } +} diff --git a/internal/service/cloudbroker/k8s/resource_k8s_wg.go b/internal/service/cloudbroker/k8s/resource_k8s_wg.go new file mode 100644 index 0000000..d1eeafb --- /dev/null +++ b/internal/service/cloudbroker/k8s/resource_k8s_wg.go @@ -0,0 +1,258 @@ +/* +Copyright (c) 2019-2022 Digital Energy Cloud Solutions LLC. All Rights Reserved. +Authors: +Petr Krutov, +Stanislav Solovev, + +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. +*/ + +/* +Terraform DECORT provider - manage resources provided by DECORT (Digital Energy Cloud +Orchestration Technology) with Terraform by Hashicorp. + +Source code: https://github.com/rudecs/terraform-provider-decort + +Please see README.md to learn where to place source code so that it +builds seamlessly. + +Documentation: https://github.com/rudecs/terraform-provider-decort/wiki +*/ + +package k8s + +import ( + "context" + "net/url" + "strconv" + + "github.com/hashicorp/terraform-plugin-sdk/v2/diag" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" + "github.com/rudecs/terraform-provider-decort/internal/constants" + "github.com/rudecs/terraform-provider-decort/internal/controller" + log "github.com/sirupsen/logrus" +) + +func resourceK8sWgCreate(ctx context.Context, d *schema.ResourceData, m interface{}) diag.Diagnostics { + log.Debugf("resourceK8sWgCreate: called with k8s id %d", d.Get("k8s_id").(int)) + + c := m.(*controller.ControllerCfg) + urlValues := &url.Values{} + urlValues.Add("k8sId", strconv.Itoa(d.Get("k8s_id").(int))) + urlValues.Add("name", d.Get("name").(string)) + urlValues.Add("workerNum", strconv.Itoa(d.Get("num").(int))) + urlValues.Add("workerCpu", strconv.Itoa(d.Get("cpu").(int))) + urlValues.Add("workerRam", strconv.Itoa(d.Get("ram").(int))) + urlValues.Add("workerDisk", strconv.Itoa(d.Get("disk").(int))) + + resp, err := c.DecortAPICall(ctx, "POST", K8sWgCreateAPI, urlValues) + if err != nil { + return diag.FromErr(err) + } + + d.SetId(resp) + + // This code is the supposed flow, but at the time of writing it's not yet implemented by the platfom + + //urlValues = &url.Values{} + //urlValues.Add("auditId", strings.Trim(resp, `"`)) + + //for { + //resp, err := controller.decortAPICall("POST", AsyncTaskGetAPI, urlValues) + //if err != nil { + //return err + //} + + //task := AsyncTask{} + //if err := json.Unmarshal([]byte(resp), &task); err != nil { + //return err + //} + //log.Debugf("resourceK8sCreate: workers group creating - %s", task.Stage) + + //if task.Completed { + //if task.Error != "" { + //return fmt.Errorf("cannot create workers group: %v", task.Error) + //} + + //d.SetId(strconv.Itoa(int(task.Result))) + //break + //} + + //time.Sleep(time.Second * 5) + //} + + return nil +} + +func resourceK8sWgRead(ctx context.Context, d *schema.ResourceData, m interface{}) diag.Diagnostics { + log.Debugf("resourceK8sWgRead: called with k8s id %d", d.Get("k8s_id").(int)) + + wg, err := utilityK8sWgCheckPresence(ctx, d, m) + if wg == nil { + d.SetId("") + return diag.FromErr(err) + } + + d.Set("name", wg.Name) + d.Set("num", wg.Num) + d.Set("cpu", wg.Cpu) + d.Set("ram", wg.Ram) + d.Set("disk", wg.Disk) + + return nil +} + +func resourceK8sWgUpdate(ctx context.Context, d *schema.ResourceData, m interface{}) diag.Diagnostics { + log.Debugf("resourceK8sWgUpdate: called with k8s id %d", d.Get("k8s_id").(int)) + + c := m.(*controller.ControllerCfg) + + wg, err := utilityK8sWgCheckPresence(ctx, d, m) + if err != nil { + return diag.FromErr(err) + } + + urlValues := &url.Values{} + urlValues.Add("k8sId", strconv.Itoa(d.Get("k8s_id").(int))) + urlValues.Add("workersGroupId", d.Id()) + + if newNum := d.Get("num").(int); newNum > wg.Num { + urlValues.Add("num", strconv.Itoa(newNum-wg.Num)) + _, err := c.DecortAPICall(ctx, "POST", K8sWorkerAddAPI, urlValues) + if err != nil { + return diag.FromErr(err) + } + } else { + for i := wg.Num - 1; i >= newNum; i-- { + urlValues.Set("workerId", strconv.Itoa(wg.DetailedInfo[i].ID)) + _, err := c.DecortAPICall(ctx, "POST", K8sWorkerDeleteAPI, urlValues) + if err != nil { + return diag.FromErr(err) + } + } + } + + return nil +} + +func resourceK8sWgDelete(ctx context.Context, d *schema.ResourceData, m interface{}) diag.Diagnostics { + log.Debugf("resourceK8sWgDelete: called with k8s id %d", d.Get("k8s_id").(int)) + + wg, err := utilityK8sWgCheckPresence(ctx, d, m) + if wg == nil { + if err != nil { + return diag.FromErr(err) + } + return nil + } + + c := m.(*controller.ControllerCfg) + urlValues := &url.Values{} + urlValues.Add("k8sId", strconv.Itoa(d.Get("k8s_id").(int))) + urlValues.Add("workersGroupId", strconv.Itoa(wg.ID)) + + _, err = c.DecortAPICall(ctx, "POST", K8sWgDeleteAPI, urlValues) + if err != nil { + return diag.FromErr(err) + } + + return nil +} + +func resourceK8sWgExists(ctx context.Context, d *schema.ResourceData, m interface{}) (bool, error) { + log.Debugf("resourceK8sWgExists: called with k8s id %d", d.Get("k8s_id").(int)) + + wg, err := utilityK8sWgCheckPresence(ctx, d, m) + if wg == nil { + if err != nil { + return false, err + } + return false, nil + } + + return true, nil +} + +func resourceK8sWgSchemaMake() map[string]*schema.Schema { + return map[string]*schema.Schema{ + "k8s_id": { + Type: schema.TypeInt, + Required: true, + ForceNew: true, + Description: "ID of k8s instance.", + }, + + "name": { + Type: schema.TypeString, + Required: true, + ForceNew: true, + Description: "Name of the worker group.", + }, + + "num": { + Type: schema.TypeInt, + Optional: true, + Default: 1, + Description: "Number of worker nodes to create.", + }, + + "cpu": { + Type: schema.TypeInt, + Optional: true, + ForceNew: true, + Default: 1, + Description: "Worker node CPU count.", + }, + + "ram": { + Type: schema.TypeInt, + Optional: true, + ForceNew: true, + Default: 1024, + Description: "Worker node RAM in MB.", + }, + + "disk": { + Type: schema.TypeInt, + Optional: true, + ForceNew: true, + Default: 0, + Description: "Worker node boot disk size. If unspecified or 0, size is defined by OS image size.", + }, + } +} + +func ResourceK8sWg() *schema.Resource { + return &schema.Resource{ + SchemaVersion: 1, + + CreateContext: resourceK8sWgCreate, + ReadContext: resourceK8sWgRead, + UpdateContext: resourceK8sWgUpdate, + DeleteContext: resourceK8sWgDelete, + + Importer: &schema.ResourceImporter{ + State: schema.ImportStatePassthrough, + }, + + Timeouts: &schema.ResourceTimeout{ + Create: &constants.Timeout20m, + Read: &constants.Timeout30s, + Update: &constants.Timeout20m, + Delete: &constants.Timeout60s, + Default: &constants.Timeout60s, + }, + + Schema: resourceK8sWgSchemaMake(), + } +} diff --git a/internal/service/cloudbroker/k8s/utility_k8s.go b/internal/service/cloudbroker/k8s/utility_k8s.go new file mode 100644 index 0000000..2c4270c --- /dev/null +++ b/internal/service/cloudbroker/k8s/utility_k8s.go @@ -0,0 +1,63 @@ +/* +Copyright (c) 2019-2022 Digital Energy Cloud Solutions LLC. All Rights Reserved. +Authors: +Petr Krutov, +Stanislav Solovev, + +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. +*/ + +/* +Terraform DECORT provider - manage resources provided by DECORT (Digital Energy Cloud +Orchestration Technology) with Terraform by Hashicorp. + +Source code: https://github.com/rudecs/terraform-provider-decort + +Please see README.md to learn where to place source code so that it +builds seamlessly. + +Documentation: https://github.com/rudecs/terraform-provider-decort/wiki +*/ + +package k8s + +import ( + "context" + "encoding/json" + "net/url" + + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" + "github.com/rudecs/terraform-provider-decort/internal/controller" +) + +func utilityK8sCheckPresence(ctx context.Context, d *schema.ResourceData, m interface{}) (*K8sRecord, error) { + c := m.(*controller.ControllerCfg) + urlValues := &url.Values{} + urlValues.Add("k8sId", d.Id()) + + resp, err := c.DecortAPICall(ctx, "POST", K8sGetAPI, urlValues) + if err != nil { + return nil, err + } + + if resp == "" { + return nil, nil + } + + var k8s K8sRecord + if err := json.Unmarshal([]byte(resp), &k8s); err != nil { + return nil, err + } + + return &k8s, nil +} diff --git a/internal/service/cloudbroker/k8s/utility_k8s_wg.go b/internal/service/cloudbroker/k8s/utility_k8s_wg.go new file mode 100644 index 0000000..9aef352 --- /dev/null +++ b/internal/service/cloudbroker/k8s/utility_k8s_wg.go @@ -0,0 +1,75 @@ +/* +Copyright (c) 2019-2022 Digital Energy Cloud Solutions LLC. All Rights Reserved. +Authors: +Petr Krutov, +Stanislav Solovev, + +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. +*/ + +/* +Terraform DECORT provider - manage resources provided by DECORT (Digital Energy Cloud +Orchestration Technology) with Terraform by Hashicorp. + +Source code: https://github.com/rudecs/terraform-provider-decort + +Please see README.md to learn where to place source code so that it +builds seamlessly. + +Documentation: https://github.com/rudecs/terraform-provider-decort/wiki +*/ + +package k8s + +import ( + "context" + "encoding/json" + "net/url" + "strconv" + + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" + "github.com/rudecs/terraform-provider-decort/internal/controller" +) + +func utilityK8sWgCheckPresence(ctx context.Context, d *schema.ResourceData, m interface{}) (*K8sNodeRecord, error) { + c := m.(*controller.ControllerCfg) + urlValues := &url.Values{} + urlValues.Add("k8sId", strconv.Itoa(d.Get("k8s_id").(int))) + + resp, err := c.DecortAPICall(ctx, "POST", K8sGetAPI, urlValues) + if err != nil { + return nil, err + } + + if resp == "" { + return nil, nil + } + + var k8s K8sRecord + if err := json.Unmarshal([]byte(resp), &k8s); err != nil { + return nil, err + } + + id, err := strconv.Atoi(d.Id()) + if err != nil { + return nil, err + } + + for _, wg := range k8s.Groups.Workers { + if wg.ID == id { + return &wg, nil + } + } + + return nil, nil +} diff --git a/internal/service/cloudbroker/kvmvm/api.go b/internal/service/cloudbroker/kvmvm/api.go new file mode 100644 index 0000000..493d461 --- /dev/null +++ b/internal/service/cloudbroker/kvmvm/api.go @@ -0,0 +1,46 @@ +/* +Copyright (c) 2019-2022 Digital Energy Cloud Solutions LLC. All Rights Reserved. +Authors: +Petr Krutov, +Stanislav Solovev, + +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. +*/ + +/* +Terraform DECORT provider - manage resources provided by DECORT (Digital Energy Cloud +Orchestration Technology) with Terraform by Hashicorp. + +Source code: https://github.com/rudecs/terraform-provider-decort + +Please see README.md to learn where to place source code so that it +builds seamlessly. + +Documentation: https://github.com/rudecs/terraform-provider-decort/wiki +*/ + +package kvmvm + +const KvmX86CreateAPI = "/restmachine/cloudbroker/kvmx86/create" +const KvmPPCCreateAPI = "/restmachine/cloudbroker/kvmppc/create" +const ComputeGetAPI = "/restmachine/cloudbroker/compute/get" +const RgListComputesAPI = "/restmachine/cloudbroker/rg/listComputes" +const ComputeNetAttachAPI = "/restmachine/cloudbroker/compute/netAttach" +const ComputeNetDetachAPI = "/restmachine/cloudbroker/compute/netDetach" +const ComputeDiskAttachAPI = "/restmachine/cloudbroker/compute/diskAttach" +const ComputeDiskDetachAPI = "/restmachine/cloudbroker/compute/diskDetach" +const ComputeStartAPI = "/restmachine/cloudbroker/compute/start" +const ComputeStopAPI = "/restmachine/cloudbroker/compute/stop" +const ComputeResizeAPI = "/restmachine/cloudbroker/compute/resize" +const DisksResizeAPI = "/restmachine/cloudbroker/disks/resize2" +const ComputeDeleteAPI = "/restmachine/cloudbroker/compute/delete" diff --git a/internal/service/cloudbroker/kvmvm/data_source_compute.go b/internal/service/cloudbroker/kvmvm/data_source_compute.go new file mode 100644 index 0000000..4622b2b --- /dev/null +++ b/internal/service/cloudbroker/kvmvm/data_source_compute.go @@ -0,0 +1,385 @@ +/* +Copyright (c) 2019-2022 Digital Energy Cloud Solutions LLC. All Rights Reserved. +Authors: +Petr Krutov, +Stanislav Solovev, + +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. +*/ + +/* +Terraform DECORT provider - manage resources provided by DECORT (Digital Energy Cloud +Orchestration Technology) with Terraform by Hashicorp. + +Source code: https://github.com/rudecs/terraform-provider-decort + +Please see README.md to learn where to place source code so that it +builds seamlessly. + +Documentation: https://github.com/rudecs/terraform-provider-decort/wiki +*/ + +package kvmvm + +import ( + "context" + "encoding/json" + "errors" + "fmt" + + // "net/url" + + "github.com/rudecs/terraform-provider-decort/internal/constants" + log "github.com/sirupsen/logrus" + + "github.com/hashicorp/terraform-plugin-sdk/v2/diag" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" + // "github.com/hashicorp/terraform-plugin-sdk/helper/validation" +) + +// Parse list of all disks from API compute/get into a list of "extra disks" attached to this compute +// Extra disks are all compute disks but a boot disk. +func parseComputeDisksToExtraDisks(disks []DiskRecord) []interface{} { + // this return value will be used to d.Set("extra_disks",) item of dataSourceCompute schema, + // which is a simple list of integer disk IDs excluding boot disk ID + length := len(disks) + log.Debugf("parseComputeDisksToExtraDisks: called for %d disks", length) + + if length == 0 || (length == 1 && disks[0].Type == "B") { + // the disk list is empty (which is kind of strange - diskless compute?), or + // there is only one disk in the list and it is a boot disk; + // as we skip boot disks, the result will be of 0 length anyway + return make([]interface{}, 0) + } + + result := make([]interface{}, length-1) + idx := 0 + for _, value := range disks { + if value.Type == "B" { + // skip boot disk when iterating over the list of disks + continue + } + + result[idx] = value.ID + idx++ + } + + return result +} + +func parseBootDiskSize(disks []DiskRecord) int { + // this return value will be used to d.Set("boot_disk_size",) item of dataSourceCompute schema + if len(disks) == 0 { + return 0 + } + + for _, value := range disks { + if value.Type == "B" { + return value.SizeMax + } + } + + return 0 +} + +func parseBootDiskId(disks []DiskRecord) uint { + // this return value will be used to d.Set("boot_disk_id",) item of dataSourceCompute schema + if len(disks) == 0 { + return 0 + } + + for _, value := range disks { + if value.Type == "B" { + return value.ID + } + } + + return 0 +} + +func findBootDisk(disks []DiskRecord) (*DiskRecord, error) { + for _, d := range disks { + if d.Type == "B" { + return &d, nil + } + } + + return nil, errors.New("boot disk not found") +} + +// Parse the list of interfaces from compute/get response into a list of networks +// attached to this compute +func parseComputeInterfacesToNetworks(ifaces []InterfaceRecord) []interface{} { + // return value will be used to d.Set("network") item of dataSourceCompute schema + length := len(ifaces) + log.Debugf("parseComputeInterfacesToNetworks: called for %d ifaces", length) + + result := []interface{}{} + + for _, value := range ifaces { + elem := make(map[string]interface{}) + // Keys in this map should correspond to the Schema definition + // as returned by networkSubresourceSchemaMake() + elem["net_id"] = value.NetID + elem["net_type"] = value.NetType + elem["ip_address"] = value.IPAddress + elem["mac"] = value.MAC + + // log.Debugf(" element %d: net_id=%d, net_type=%s", i, value.NetID, value.NetType) + + result = append(result, elem) + } + + return result +} + +func flattenCompute(d *schema.ResourceData, compFacts string) error { + // This function expects that compFacts string contains response from API compute/get, + // i.e. detailed information about compute instance. + // + // NOTE: this function modifies ResourceData argument - as such it should never be called + // from resourceComputeExists(...) method + model := ComputeGetResp{} + log.Debugf("flattenCompute: ready to unmarshal string %s", compFacts) + err := json.Unmarshal([]byte(compFacts), &model) + if err != nil { + return err + } + + log.Debugf("flattenCompute: ID %d, RG ID %d", model.ID, model.RgID) + + d.SetId(fmt.Sprintf("%d", model.ID)) + // d.Set("compute_id", model.ID) - we should NOT set compute_id in the schema here: if it was set - it is already set, if it wasn't - we shouldn't + d.Set("name", model.Name) + d.Set("rg_id", model.RgID) + d.Set("rg_name", model.RgName) + d.Set("account_id", model.AccountID) + d.Set("account_name", model.AccountName) + d.Set("driver", model.Driver) + d.Set("cpu", model.Cpu) + d.Set("ram", model.Ram) + // d.Set("boot_disk_size", model.BootDiskSize) - bootdiskSize key in API compute/get is always zero, so we set boot_disk_size in another way + d.Set("image_id", model.ImageID) + d.Set("description", model.Desc) + d.Set("cloud_init", "applied") // NOTE: for existing compute we hard-code this value as an indicator for DiffSuppress fucntion + // d.Set("status", model.Status) + // d.Set("tech_status", model.TechStatus) + + if model.TechStatus == "STARTED" { + d.Set("started", true) + } else { + d.Set("started", false) + } + + bootDisk, err := findBootDisk(model.Disks) + if err != nil { + return err + } + + d.Set("boot_disk_size", bootDisk.SizeMax) + d.Set("boot_disk_id", bootDisk.ID) // we may need boot disk ID in resize operations + d.Set("sep_id", bootDisk.SepID) + d.Set("pool", bootDisk.Pool) + + if len(model.Disks) > 0 { + log.Debugf("flattenCompute: calling parseComputeDisksToExtraDisks for %d disks", len(model.Disks)) + if err = d.Set("extra_disks", parseComputeDisksToExtraDisks(model.Disks)); err != nil { + return err + } + } + + if len(model.Interfaces) > 0 { + log.Debugf("flattenCompute: calling parseComputeInterfacesToNetworks for %d interfaces", len(model.Interfaces)) + if err = d.Set("network", parseComputeInterfacesToNetworks(model.Interfaces)); err != nil { + return err + } + } + + if len(model.OsUsers) > 0 { + log.Debugf("flattenCompute: calling parseOsUsers for %d logins", len(model.OsUsers)) + if err = d.Set("os_users", parseOsUsers(model.OsUsers)); err != nil { + return err + } + } + + return nil +} + +func dataSourceComputeRead(ctx context.Context, d *schema.ResourceData, m interface{}) diag.Diagnostics { + compFacts, err := utilityComputeCheckPresence(ctx, d, m) + if compFacts == "" { + // if empty string is returned from utilityComputeCheckPresence then there is no + // such Compute and err tells so - just return it to the calling party + d.SetId("") // ensure ID is empty + return diag.FromErr(err) + } + + if err = flattenCompute(d, compFacts); err != nil { + return diag.FromErr(err) + } + + return nil +} + +func DataSourceCompute() *schema.Resource { + return &schema.Resource{ + SchemaVersion: 1, + + ReadContext: dataSourceComputeRead, + + Timeouts: &schema.ResourceTimeout{ + Read: &constants.Timeout30s, + Default: &constants.Timeout60s, + }, + + Schema: map[string]*schema.Schema{ + "name": { + Type: schema.TypeString, + Optional: true, + Description: "Name of this compute instance. NOTE: this parameter is case sensitive.", + }, + + // TODO: consider removing compute_id from the schema, as it not practical to call this data provider if + // corresponding compute ID is already known + "compute_id": { + Type: schema.TypeInt, + Optional: true, + Description: "ID of the compute instance. If ID is specified, name and resource group ID are ignored.", + }, + + "rg_id": { + Type: schema.TypeInt, + Optional: true, + Description: "ID of the resource group where this compute instance is located.", + }, + + "rg_name": { + Type: schema.TypeString, + Computed: true, + Description: "Name of the resource group where this compute instance is located.", + }, + + "account_id": { + Type: schema.TypeInt, + Computed: true, + Description: "ID of the account this compute instance belongs to.", + }, + + "account_name": { + Type: schema.TypeString, + Computed: true, + Description: "Name of the account this compute instance belongs to.", + }, + + "driver": { + Type: schema.TypeString, + Computed: true, + Description: "Hardware architecture of this compute instance.", + }, + + "cpu": { + Type: schema.TypeInt, + Computed: true, + Description: "Number of CPUs allocated for this compute instance.", + }, + + "ram": { + Type: schema.TypeInt, + Computed: true, + Description: "Amount of RAM in MB allocated for this compute instance.", + }, + + "image_id": { + Type: schema.TypeInt, + Computed: true, + Description: "ID of the OS image this compute instance is based on.", + }, + + "image_name": { + Type: schema.TypeString, + Computed: true, + Description: "Name of the OS image this compute instance is based on.", + }, + + "boot_disk_size": { + Type: schema.TypeInt, + Computed: true, + Description: "This compute instance boot disk size in GB.", + }, + + "boot_disk_id": { + Type: schema.TypeInt, + Computed: true, + Description: "This compute instance boot disk ID.", + }, + + "extra_disks": { + Type: schema.TypeSet, + Computed: true, + Elem: &schema.Schema{ + Type: schema.TypeInt, + }, + Description: "IDs of the extra disk(s) attached to this compute.", + }, + + /* + "disks": { + Type: schema.TypeList, + Computed: true, + Elem: &schema.Resource{ + Schema: dataSourceDiskSchemaMake(), // ID, type, name, size, account ID, SEP ID, SEP type, pool, status, tech status, compute ID, image ID + }, + Description: "Detailed specification for all disks attached to this compute instance (including bood disk).", + }, + */ + + "network": { + Type: schema.TypeSet, + Optional: true, + MaxItems: constants.MaxNetworksPerCompute, + Elem: &schema.Resource{ + Schema: networkSubresourceSchemaMake(), + }, + Description: "Network connection(s) for this compute.", + }, + + "os_users": { + Type: schema.TypeList, + Computed: true, + Elem: &schema.Resource{ + Schema: osUsersSubresourceSchemaMake(), + }, + Description: "Guest OS users provisioned on this compute instance.", + }, + + "description": { + Type: schema.TypeString, + Computed: true, + Description: "User-defined text description of this compute instance.", + }, + + "cloud_init": { + Type: schema.TypeString, + Computed: true, + Description: "Placeholder for cloud_init parameters.", + }, + + "started": { + Type: schema.TypeBool, + Optional: true, + Default: true, + Description: "Is compute started.", + }, + }, + } +} diff --git a/internal/service/cloudbroker/kvmvm/models.go b/internal/service/cloudbroker/kvmvm/models.go new file mode 100644 index 0000000..220fafd --- /dev/null +++ b/internal/service/cloudbroker/kvmvm/models.go @@ -0,0 +1,190 @@ +/* +Copyright (c) 2019-2022 Digital Energy Cloud Solutions LLC. All Rights Reserved. +Authors: +Petr Krutov, +Stanislav Solovev, + +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. +*/ + +/* +Terraform DECORT provider - manage resources provided by DECORT (Digital Energy Cloud +Orchestration Technology) with Terraform by Hashicorp. + +Source code: https://github.com/rudecs/terraform-provider-decort + +Please see README.md to learn where to place source code so that it +builds seamlessly. + +Documentation: https://github.com/rudecs/terraform-provider-decort/wiki +*/ + +package kvmvm + +type DiskRecord struct { + Acl map[string]interface{} `json:"acl"` + AccountID int `json:"accountId"` + AccountName string `json:"accountName"` + BootPartition int `json:"bootPartition"` + CreatedTime uint64 `json:"creationTime"` + ComputeID int `json:"computeId"` + ComputeName string `json:"computeName"` + DeletedTime uint64 `json:"deletionTime"` + DeviceName string `json:"devicename"` + Desc string `json:"desc"` + DestructionTime uint64 `json:"destructionTime"` + DiskPath string `json:"diskPath"` + GridID int `json:"gid"` + GUID int `json:"guid"` + ID uint `json:"id"` + ImageID int `json:"imageId"` + Images []int `json:"images"` + IOTune map[string]interface{} `json:"iotune"` + IQN string `json:"iqn"` + Login string `json:"login"` + Name string `json:"name"` + MachineId int `json:"machineId"` + MachineName string `json:"machineName"` + Milestones uint64 `json:"milestones"` + Order int `json:"order"` + Params string `json:"params"` + Passwd string `json:"passwd"` + ParentId int `json:"parentId"` + PciSlot int `json:"pciSlot"` + Pool string `json:"pool"` + PurgeTime uint64 `json:"purgeTime"` + PurgeAttempts uint64 `json:"purgeAttempts"` + RealityDeviceNumber int `json:"realityDeviceNumber"` + ReferenceId string `json:"referenceId"` + ResID string `json:"resId"` + ResName string `json:"resName"` + Role string `json:"role"` + SepType string `json:"sepType"` + SepID int `json:"sepId"` // NOTE: absent from compute/get output + SizeMax int `json:"sizeMax"` + SizeUsed int `json:"sizeUsed"` // sum over all snapshots of this disk to report total consumed space + Snapshots []SnapshotRecord `json:"snapshots"` + Status string `json:"status"` + TechStatus string `json:"techStatus"` + Type string `json:"type"` + UpdateBy uint64 `json:"updateBy"` + VMID int `json:"vmid"` +} + +type InterfaceRecord struct { + ConnID int `json:"connId"` // This is VLAN ID or VxLAN ID, depending on ConnType + ConnType string `json:"connType"` // Either "VLAN" or "VXLAN" tag + DefaultGW string `json:"defGw"` + Guid string `json:"guid"` + IPAddress string `json:"ipAddress"` // without trailing network mask, i.e. "192.168.1.3" + MAC string `json:"mac"` + Name string `json:"name"` + NetID int `json:"netId"` // This is either ExtNet ID or ViNS ID, depending on NetType + NetMask int `json:"netMask"` + NetType string `json:"netType"` // Either "EXTNET" or "VINS" tag + PciSlot int `json:"pciSlot"` + Target string `json:"target"` + Type string `json:"type"` + VNFs []int `json:"vnfs"` + QOS InterfaceQosRecord `json:"qos"` +} + +type InterfaceQosRecord struct { + ERate int `json:"eRate"` + Guid string `json:"guid"` + InBurst int `json:"inBurst"` + InRate int `json:"inRate"` +} + +type SnapshotRecord struct { + Guid string `json:"guid"` + Label string `json:"label"` + ResId string `json:"resId"` + SnapSetGuid string `json:"snapSetGuid"` + SnapSetTime uint64 `json:"snapSetTime"` + TimeStamp uint64 `json:"timestamp"` +} + +type SnapshotRecordList []SnapshotRecord + +type ComputeGetResp struct { + // ACLs `json:"ACL"` - it is a dictionary, special parsing required + AccountID int `json:"accountId"` + AccountName string `json:"accountName"` + Arch string `json:"arch"` + BootDiskSize int `json:"bootdiskSize"` + CloneReference int `json:"cloneReference"` + Clones []int `json:"clones"` + Cpu int `json:"cpus"` + Desc string `json:"desc"` + Disks []DiskRecord `json:"disks"` + Driver string `json:"driver"` + GridID int `json:"gid"` + ID uint `json:"id"` + ImageID int `json:"imageId"` + ImageName string `json:"imageName"` + Interfaces []InterfaceRecord `json:"interfaces"` + LockStatus string `json:"lockStatus"` + ManagerID int `json:"managerId"` + ManagerType string `json:"manageType"` + Name string `json:"name"` + NatableVinsID int `json:"natableVinsId"` + NatableVinsIP string `json:"natableVinsIp"` + NatableVinsName string `json:"natableVinsName"` + NatableVinsNet string `json:"natableVinsNetwork"` + NatableVinsNetName string `json:"natableVinsNetworkName"` + OsUsers []OsUserRecord `json:"osUsers"` + Ram int `json:"ram"` + RgID int `json:"rgId"` + RgName string `json:"rgName"` + SnapSets []SnapSetRecord `json:"snapSets"` + Status string `json:"status"` + // Tags []string `json:"tags"` // Tags were reworked since DECORT 3.7.1 + TechStatus string `json:"techStatus"` + TotalDiskSize int `json:"totalDiskSize"` + UpdatedBy string `json:"updatedBy"` + UpdateTime uint64 `json:"updateTime"` + UserManaged bool `json:"userManaged"` + Vgpus []int `json:"vgpus"` + VinsConnected int `json:"vinsConnected"` + VirtualImageID int `json:"virtualImageId"` +} + +type OsUserRecord struct { + Guid string `json:"guid"` + Login string `json:"login"` + Password string `json:"password"` + PubKey string `json:"pubkey"` +} + +type SnapSetRecord struct { + Disks []int `json:"disks"` + Guid string `json:"guid"` + Label string `json:"label"` + TimeStamp uint64 `json:"timestamp"` +} + +type ComputeBriefRecord struct { // this is a brief compute specifiaction as returned by API rg/listComputes + // we do not even include here all fields as returned by this API, but only the most important that + // are really necessary to identify and distinguish computes + AccountID int `json:"accountId"` + AccountName string `json:"accountName"` + Name string `json:"name"` + ID uint `json:"id"` + RgID int `json:"rgId"` + RgName string `json:"rgName"` + Status string `json:"status"` + TechStatus string `json:"techStatus"` +} + +type RgListComputesResp []ComputeBriefRecord diff --git a/internal/service/cloudbroker/kvmvm/network_subresource.go b/internal/service/cloudbroker/kvmvm/network_subresource.go new file mode 100644 index 0000000..9bc94b4 --- /dev/null +++ b/internal/service/cloudbroker/kvmvm/network_subresource.go @@ -0,0 +1,154 @@ +/* +Copyright (c) 2019-2022 Digital Energy Cloud Solutions LLC. All Rights Reserved. +Authors: +Petr Krutov, +Stanislav Solovev, + +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. +*/ + +/* +Terraform DECORT provider - manage resources provided by DECORT (Digital Energy Cloud +Orchestration Technology) with Terraform by Hashicorp. + +Source code: https://github.com/rudecs/terraform-provider-decort + +Please see README.md to learn where to place source code so that it +builds seamlessly. + +Documentation: https://github.com/rudecs/terraform-provider-decort/wiki +*/ + +package kvmvm + +import ( + "bytes" + "hash/fnv" + + "github.com/rudecs/terraform-provider-decort/internal/statefuncs" + log "github.com/sirupsen/logrus" + + "sort" + + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/validation" +) + +// This is subresource of compute resource used when creating/managing compute network connections + +func networkSubresIPAddreDiffSupperss(key, oldVal, newVal string, d *schema.ResourceData) bool { + if newVal != "" && newVal != oldVal { + log.Debugf("networkSubresIPAddreDiffSupperss: key=%s, oldVal=%q, newVal=%q -> suppress=FALSE", key, oldVal, newVal) + return false + } + log.Debugf("networkSubresIPAddreDiffSupperss: key=%s, oldVal=%q, newVal=%q -> suppress=TRUE", key, oldVal, newVal) + return true // suppress difference +} + +// This function is based on the original Terraform SerializeResourceForHash found +// in helper/schema/serialize.go +// It skips network subresource attributes, which are irrelevant for identification +// of unique network blocks +func networkSubresourceSerialize(output *bytes.Buffer, val interface{}, resource *schema.Resource) { + if val == nil { + return + } + + rs := resource.Schema + m := val.(map[string]interface{}) + + keys := make([]string, 0, len(rs)) + allComputed := true + + for k, val := range rs { + if val.Optional || val.Required { + allComputed = false + } + + keys = append(keys, k) + } + + sort.Strings(keys) + for _, k := range keys { + // explicitly ignore "ip_address" when hashing + if k == "ip_address" { + continue + } + + subSchema := rs[k] + // Skip attributes that are not user-provided. Computed attributes + // do not contribute to the hash since their ultimate value cannot + // be known at plan/diff time. + if !allComputed && !(subSchema.Required || subSchema.Optional) { + continue + } + + output.WriteString(k) + output.WriteRune(':') + value := m[k] + schema.SerializeValueForHash(output, value, subSchema) + } +} + +// HashNetworkSubresource hashes network subresource of compute resource. It uses +// specially designed networkSubresourceSerialize (see above) to make sure hashing +// does not involve attributes that we deem irrelevant to the uniqueness of network +// subresource definitions. +// It is this function that should be specified as SchemaSetFunc when creating Set +// from network subresource (e.g. in flattenCompute) +// +// This function is based on the original Terraform function HashResource from +// helper/schema/set.go +func HashNetworkSubresource(resource *schema.Resource) schema.SchemaSetFunc { + return func(v interface{}) int { + var serialized bytes.Buffer + networkSubresourceSerialize(&serialized, v, resource) + + hs := fnv.New32a() + hs.Write(serialized.Bytes()) + return int(hs.Sum32()) + } +} + +func networkSubresourceSchemaMake() map[string]*schema.Schema { + rets := map[string]*schema.Schema{ + "net_type": { + Type: schema.TypeString, + Required: true, + StateFunc: statefuncs.StateFuncToUpper, + ValidateFunc: validation.StringInSlice([]string{"EXTNET", "VINS"}, false), // observe case while validating + Description: "Type of the network for this connection, either EXTNET or VINS.", + }, + + "net_id": { + Type: schema.TypeInt, + Required: true, + Description: "ID of the network for this connection.", + }, + + "ip_address": { + Type: schema.TypeString, + Optional: true, + Computed: true, + DiffSuppressFunc: networkSubresIPAddreDiffSupperss, + Description: "Optional IP address to assign to this connection. This IP should belong to the selected network and free for use.", + }, + + "mac": { + Type: schema.TypeString, + Computed: true, + Description: "MAC address associated with this connection. MAC address is assigned automatically.", + }, + } + return rets +} diff --git a/internal/service/cloudbroker/kvmvm/osusers_subresource.go b/internal/service/cloudbroker/kvmvm/osusers_subresource.go new file mode 100644 index 0000000..2e6787f --- /dev/null +++ b/internal/service/cloudbroker/kvmvm/osusers_subresource.go @@ -0,0 +1,86 @@ +/* +Copyright (c) 2019-2022 Digital Energy Cloud Solutions LLC. All Rights Reserved. +Authors: +Petr Krutov, +Stanislav Solovev, + +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. +*/ + +/* +Terraform DECORT provider - manage resources provided by DECORT (Digital Energy Cloud +Orchestration Technology) with Terraform by Hashicorp. + +Source code: https://github.com/rudecs/terraform-provider-decort + +Please see README.md to learn where to place source code so that it +builds seamlessly. + +Documentation: https://github.com/rudecs/terraform-provider-decort/wiki +*/ + +package kvmvm + +import ( + log "github.com/sirupsen/logrus" + + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" +) + +func parseOsUsers(logins []OsUserRecord) []interface{} { + var result = make([]interface{}, len(logins)) + + for index, value := range logins { + elem := make(map[string]interface{}) + + elem["guid"] = value.Guid + elem["login"] = value.Login + elem["password"] = value.Password + elem["public_key"] = value.PubKey + result[index] = elem + log.Debugf("parseOsUsers: parsed element %d - login %q", index, value.Login) + } + + return result +} + +func osUsersSubresourceSchemaMake() map[string]*schema.Schema { + rets := map[string]*schema.Schema{ + "guid": { + Type: schema.TypeString, + Computed: true, + Description: "GUID of this guest OS user.", + }, + + "login": { + Type: schema.TypeString, + Computed: true, + Description: "Login name of this guest OS user.", + }, + + "password": { + Type: schema.TypeString, + Computed: true, + Sensitive: true, + Description: "Password of this guest OS user.", + }, + + "public_key": { + Type: schema.TypeString, + Computed: true, + Description: "SSH public key of this guest OS user.", + }, + } + + return rets +} diff --git a/internal/service/cloudbroker/kvmvm/resource_compute.go b/internal/service/cloudbroker/kvmvm/resource_compute.go new file mode 100644 index 0000000..2d6c2a3 --- /dev/null +++ b/internal/service/cloudbroker/kvmvm/resource_compute.go @@ -0,0 +1,542 @@ +/* +Copyright (c) 2019-2022 Digital Energy Cloud Solutions LLC. All Rights Reserved. +Authors: +Petr Krutov, +Stanislav Solovev, + +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. +*/ + +/* +Terraform DECORT provider - manage resources provided by DECORT (Digital Energy Cloud +Orchestration Technology) with Terraform by Hashicorp. + +Source code: https://github.com/rudecs/terraform-provider-decort + +Please see README.md to learn where to place source code so that it +builds seamlessly. + +Documentation: https://github.com/rudecs/terraform-provider-decort/wiki +*/ + +package kvmvm + +import ( + "context" + "encoding/json" + "fmt" + "net/url" + "strconv" + + "github.com/rudecs/terraform-provider-decort/internal/constants" + "github.com/rudecs/terraform-provider-decort/internal/controller" + "github.com/rudecs/terraform-provider-decort/internal/statefuncs" + log "github.com/sirupsen/logrus" + + "github.com/hashicorp/terraform-plugin-sdk/v2/diag" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/validation" +) + +func cloudInitDiffSupperss(key, oldVal, newVal string, d *schema.ResourceData) bool { + if oldVal == "" && newVal != "applied" { + // if old value for "cloud_init" resource is empty string, it means that we are creating new compute + // and there is a chance that the user will want custom cloud init parameters - so we check if + // cloud_init is explicitly set in TF file by making sure that its new value is different from "applied", + // which is a reserved key word. + log.Debugf("cloudInitDiffSupperss: key=%s, oldVal=%q, newVal=%q -> suppress=FALSE", key, oldVal, newVal) + return false // there is a difference between stored and new value + } + log.Debugf("cloudInitDiffSupperss: key=%s, oldVal=%q, newVal=%q -> suppress=TRUE", key, oldVal, newVal) + return true // suppress difference +} + +func resourceComputeCreate(ctx context.Context, d *schema.ResourceData, m interface{}) diag.Diagnostics { + // we assume all mandatory parameters it takes to create a comptue instance are properly + // specified - we rely on schema "Required" attributes to let Terraform validate them for us + + log.Debugf("resourceComputeCreate: called for Compute name %q, RG ID %d", d.Get("name").(string), d.Get("rg_id").(int)) + + // create basic Compute (i.e. without extra disks and network connections - those will be attached + // by subsequent individual API calls). + c := m.(*controller.ControllerCfg) + urlValues := &url.Values{} + urlValues.Add("rgId", fmt.Sprintf("%d", d.Get("rg_id").(int))) + urlValues.Add("name", d.Get("name").(string)) + urlValues.Add("cpu", fmt.Sprintf("%d", d.Get("cpu").(int))) + urlValues.Add("ram", fmt.Sprintf("%d", d.Get("ram").(int))) + urlValues.Add("imageId", fmt.Sprintf("%d", d.Get("image_id").(int))) + urlValues.Add("bootDisk", fmt.Sprintf("%d", d.Get("boot_disk_size").(int))) + urlValues.Add("netType", "NONE") // at the 1st step create isolated compute + urlValues.Add("start", "0") // at the 1st step create compute in a stopped state + + argVal, argSet := d.GetOk("description") + if argSet { + urlValues.Add("desc", argVal.(string)) + } + + if sepID, ok := d.GetOk("sep_id"); ok { + urlValues.Add("sepId", strconv.Itoa(sepID.(int))) + } + + if pool, ok := d.GetOk("pool"); ok { + urlValues.Add("pool", pool.(string)) + } + + /* + sshKeysVal, sshKeysSet := d.GetOk("ssh_keys") + if sshKeysSet { + // process SSH Key settings and set API values accordingly + log.Debugf("resourceComputeCreate: calling makeSshKeysArgString to setup SSH keys for guest login(s)") + urlValues.Add("userdata", makeSshKeysArgString(sshKeysVal.([]interface{}))) + } + */ + + computeCreateAPI := KvmX86CreateAPI + driver := d.Get("driver").(string) + if driver == "KVM_PPC" { + computeCreateAPI = KvmPPCCreateAPI + log.Debugf("resourceComputeCreate: creating Compute of type KVM VM PowerPC") + } else { // note that we do not validate arch value for explicit "KVM_X86" here + log.Debugf("resourceComputeCreate: creating Compute of type KVM VM x86") + } + + argVal, argSet = d.GetOk("cloud_init") + if argSet { + // userdata must not be empty string and must not be a reserved keyword "applied" + userdata := argVal.(string) + if userdata != "" && userdata != "applied" { + urlValues.Add("userdata", userdata) + } + } + + apiResp, err := c.DecortAPICall(ctx, "POST", computeCreateAPI, urlValues) + if err != nil { + return diag.FromErr(err) + } + // Compute create API returns ID of the new Compute instance on success + + d.SetId(apiResp) // update ID of the resource to tell Terraform that the resource exists, albeit partially + compId, _ := strconv.Atoi(apiResp) + + log.Debugf("resourceComputeCreate: new simple Compute ID %d, name %s created", compId, d.Get("name").(string)) + + // Configure data disks if any + argVal, argSet = d.GetOk("extra_disks") + if argSet && argVal.(*schema.Set).Len() > 0 { + // urlValues.Add("desc", argVal.(string)) + log.Debugf("resourceComputeCreate: calling utilityComputeExtraDisksConfigure to attach %d extra disk(s)", argVal.(*schema.Set).Len()) + err = utilityComputeExtraDisksConfigure(ctx, d, m, false) // do_delta=false, as we are working on a new compute + if err != nil { + log.Errorf("resourceComputeCreate: error when attaching extra disk(s) to a new Compute ID %d: %v", compId, err) + return diag.FromErr(err) + } + } + // Configure external networks if any + argVal, argSet = d.GetOk("network") + if argSet && argVal.(*schema.Set).Len() > 0 { + log.Debugf("resourceComputeCreate: calling utilityComputeNetworksConfigure to attach %d network(s)", argVal.(*schema.Set).Len()) + err = utilityComputeNetworksConfigure(ctx, d, m, false) // do_delta=false, as we are working on a new compute + if err != nil { + log.Errorf("resourceComputeCreate: error when attaching networks to a new Compute ID %d: %s", compId, err) + return diag.FromErr(err) + } + } + + // Note bene: we created compute in a STOPPED state (this is required to properly attach 1st network interface), + // now we need to start it before we report the sequence complete + if d.Get("started").(bool) { + reqValues := &url.Values{} + reqValues.Add("computeId", fmt.Sprintf("%d", compId)) + log.Debugf("resourceComputeCreate: starting Compute ID %d after completing its resource configuration", compId) + if _, err := c.DecortAPICall(ctx, "POST", ComputeStartAPI, reqValues); err != nil { + return diag.FromErr(err) + } + } + + log.Debugf("resourceComputeCreate: new Compute ID %d, name %s creation sequence complete", compId, d.Get("name").(string)) + + // We may reuse dataSourceComputeRead here as we maintain similarity + // between Compute resource and Compute data source schemas + // Compute read function will also update resource ID on success, so that Terraform + // will know the resource exists + return dataSourceComputeRead(ctx, d, m) +} + +func resourceComputeRead(ctx context.Context, d *schema.ResourceData, m interface{}) diag.Diagnostics { + log.Debugf("resourceComputeRead: called for Compute name %s, RG ID %d", + d.Get("name").(string), d.Get("rg_id").(int)) + + compFacts, err := utilityComputeCheckPresence(ctx, d, m) + if compFacts == "" { + if err != nil { + return diag.FromErr(err) + } + // Compute with such name and RG ID was not found + return nil + } + + if err = flattenCompute(d, compFacts); err != nil { + return diag.FromErr(err) + } + + log.Debugf("resourceComputeRead: after flattenCompute: Compute ID %s, name %q, RG ID %d", + d.Id(), d.Get("name").(string), d.Get("rg_id").(int)) + + return nil +} + +func resourceComputeUpdate(ctx context.Context, d *schema.ResourceData, m interface{}) diag.Diagnostics { + log.Debugf("resourceComputeUpdate: called for Compute ID %s / name %s, RGID %d", + d.Id(), d.Get("name").(string), d.Get("rg_id").(int)) + + c := m.(*controller.ControllerCfg) + + /* + 1. Resize CPU/RAM + 2. Resize (grow) boot disk + 3. Update extra disks + 4. Update networks + 5. Start/stop + */ + + // 1. Resize CPU/RAM + params := &url.Values{} + doUpdate := false + params.Add("computeId", d.Id()) + + oldCpu, newCpu := d.GetChange("cpu") + if oldCpu.(int) != newCpu.(int) { + params.Add("cpu", fmt.Sprintf("%d", newCpu.(int))) + doUpdate = true + } else { + params.Add("cpu", "0") // no change to CPU allocation + } + + oldRam, newRam := d.GetChange("ram") + if oldRam.(int) != newRam.(int) { + params.Add("ram", fmt.Sprintf("%d", newRam.(int))) + doUpdate = true + } else { + params.Add("ram", "0") + } + + if doUpdate { + log.Debugf("resourceComputeUpdate: changing CPU %d -> %d and/or RAM %d -> %d", + oldCpu.(int), newCpu.(int), + oldRam.(int), newRam.(int)) + params.Add("force", "true") + _, err := c.DecortAPICall(ctx, "POST", ComputeResizeAPI, params) + if err != nil { + return diag.FromErr(err) + } + } + + // 2. Resize (grow) Boot disk + oldSize, newSize := d.GetChange("boot_disk_size") + if oldSize.(int) < newSize.(int) { + bdsParams := &url.Values{} + bdsParams.Add("diskId", fmt.Sprintf("%d", d.Get("boot_disk_id").(int))) + bdsParams.Add("size", fmt.Sprintf("%d", newSize.(int))) + log.Debugf("resourceComputeUpdate: compute ID %s, boot disk ID %d resize %d -> %d", + d.Id(), d.Get("boot_disk_id").(int), oldSize.(int), newSize.(int)) + _, err := c.DecortAPICall(ctx, "POST", DisksResizeAPI, bdsParams) + if err != nil { + return diag.FromErr(err) + } + } else if oldSize.(int) > newSize.(int) { + log.Warnf("resourceComputeUpdate: compute ID %s - shrinking boot disk is not allowed", d.Id()) + } + + // 3. Calculate and apply changes to data disks + err := utilityComputeExtraDisksConfigure(ctx, d, m, true) // pass do_delta = true to apply changes, if any + if err != nil { + return diag.FromErr(err) + } + + // 4. Calculate and apply changes to network connections + err = utilityComputeNetworksConfigure(ctx, d, m, true) // pass do_delta = true to apply changes, if any + if err != nil { + return diag.FromErr(err) + } + + if d.HasChange("started") { + params := &url.Values{} + params.Add("computeId", d.Id()) + if d.Get("started").(bool) { + if _, err := c.DecortAPICall(ctx, "POST", ComputeStartAPI, params); err != nil { + return diag.FromErr(err) + } + } else { + if _, err := c.DecortAPICall(ctx, "POST", ComputeStopAPI, params); err != nil { + return diag.FromErr(err) + } + } + } + + // we may reuse dataSourceComputeRead here as we maintain similarity + // between Compute resource and Compute data source schemas + return dataSourceComputeRead(ctx, d, m) +} + +func resourceComputeDelete(ctx context.Context, d *schema.ResourceData, m interface{}) diag.Diagnostics { + // NOTE: this function destroys target Compute instance "permanently", so + // there is no way to restore it. + // If compute being destroyed has some extra disks attached, they are + // detached from the compute + log.Debugf("resourceComputeDelete: called for Compute name %s, RG ID %d", + d.Get("name").(string), d.Get("rg_id").(int)) + + compFacts, err := utilityComputeCheckPresence(ctx, d, m) + if compFacts == "" { + if err != nil { + return diag.FromErr(err) + } + // the target Compute does not exist - in this case according to Terraform best practice + // we exit from Destroy method without error + return nil + } + + c := m.(*controller.ControllerCfg) + + model := ComputeGetResp{} + log.Debugf("resourceComputeDelete: ready to unmarshal string %s", compFacts) + err = json.Unmarshal([]byte(compFacts), &model) + if err == nil && len(model.Disks) > 0 { + // prepare to detach data disks from compute - do it only if compFacts unmarshalled + // properly and the resulting model contains non-empty Disks list + for _, diskFacts := range model.Disks { + if diskFacts.Type == "B" { + // boot disk is never detached on compute delete + continue + } + + log.Debugf("resourceComputeDelete: ready to detach data disk ID %d from compute ID %s", diskFacts.ID, d.Id()) + + detachParams := &url.Values{} + detachParams.Add("computeId", d.Id()) + detachParams.Add("diskId", fmt.Sprintf("%d", diskFacts.ID)) + + _, err = c.DecortAPICall(ctx, "POST", ComputeDiskDetachAPI, detachParams) + if err != nil { + // We do not fail compute deletion on data disk detach errors + log.Errorf("resourceComputeDelete: error when detaching Disk ID %d: %s", diskFacts.ID, err) + } + } + } + + params := &url.Values{} + params.Add("computeId", d.Id()) + params.Add("permanently", "1") + // TODO: this is for the upcoming API update - params.Add("detachdisks", "1") + + _, err = c.DecortAPICall(ctx, "POST", ComputeDeleteAPI, params) + if err != nil { + return diag.FromErr(err) + } + + return nil +} + +func resourceComputeExists(ctx context.Context, d *schema.ResourceData, m interface{}) (bool, error) { + // Reminder: according to Terraform rules, this function should not modify its ResourceData argument + log.Debugf("resourceComputeExist: called for Compute name %s, RG ID %d", + d.Get("name").(string), d.Get("rg_id").(int)) + + compFacts, err := utilityComputeCheckPresence(ctx, d, m) + if compFacts == "" { + if err != nil { + return false, err + } + return false, nil + } + return true, nil +} + +func ResourceCompute() *schema.Resource { + return &schema.Resource{ + SchemaVersion: 1, + + CreateContext: resourceComputeCreate, + ReadContext: resourceComputeRead, + UpdateContext: resourceComputeUpdate, + DeleteContext: resourceComputeDelete, + + Importer: &schema.ResourceImporter{ + State: schema.ImportStatePassthrough, + }, + + Timeouts: &schema.ResourceTimeout{ + Create: &constants.Timeout180s, + Read: &constants.Timeout30s, + Update: &constants.Timeout180s, + Delete: &constants.Timeout60s, + Default: &constants.Timeout60s, + }, + + Schema: map[string]*schema.Schema{ + "name": { + Type: schema.TypeString, + Required: true, + Description: "Name of this compute. Compute names are case sensitive and must be unique in the resource group.", + }, + + "rg_id": { + Type: schema.TypeInt, + Required: true, + ValidateFunc: validation.IntAtLeast(1), + Description: "ID of the resource group where this compute should be deployed.", + }, + + "driver": { + Type: schema.TypeString, + Required: true, + ForceNew: true, + StateFunc: statefuncs.StateFuncToUpper, + ValidateFunc: validation.StringInSlice([]string{"KVM_X86", "KVM_PPC"}, false), // observe case while validating + Description: "Hardware architecture of this compute instance.", + }, + + "cpu": { + Type: schema.TypeInt, + Required: true, + ValidateFunc: validation.IntBetween(1, constants.MaxCpusPerCompute), + Description: "Number of CPUs to allocate to this compute instance.", + }, + + "ram": { + Type: schema.TypeInt, + Required: true, + ValidateFunc: validation.IntAtLeast(constants.MinRamPerCompute), + Description: "Amount of RAM in MB to allocate to this compute instance.", + }, + + "image_id": { + Type: schema.TypeInt, + Required: true, + ForceNew: true, + ValidateFunc: validation.IntAtLeast(1), + Description: "ID of the OS image to base this compute instance on.", + }, + + "boot_disk_size": { + Type: schema.TypeInt, + Required: true, + Description: "This compute instance boot disk size in GB. Make sure it is large enough to accomodate selected OS image.", + }, + + "sep_id": { + Type: schema.TypeInt, + Optional: true, + Computed: true, + ForceNew: true, + Description: "ID of SEP to create bootDisk on. Uses image's sepId if not set.", + }, + + "pool": { + Type: schema.TypeString, + Optional: true, + Computed: true, + ForceNew: true, + Description: "Pool to use if sepId is set, can be also empty if needed to be chosen by system.", + }, + + "extra_disks": { + Type: schema.TypeSet, + Optional: true, + MaxItems: constants.MaxExtraDisksPerCompute, + Elem: &schema.Schema{ + Type: schema.TypeInt, + }, + Description: "Optional list of IDs of extra disks to attach to this compute. You may specify several extra disks.", + }, + + "network": { + Type: schema.TypeSet, + Optional: true, + MaxItems: constants.MaxNetworksPerCompute, + Elem: &schema.Resource{ + Schema: networkSubresourceSchemaMake(), + }, + Description: "Optional network connection(s) for this compute. You may specify several network blocks, one for each connection.", + }, + + /* + "ssh_keys": { + Type: schema.TypeList, + Optional: true, + MaxItems: MaxSshKeysPerCompute, + Elem: &schema.Resource{ + Schema: sshSubresourceSchemaMake(), + }, + Description: "SSH keys to authorize on this compute instance.", + }, + */ + + "description": { + Type: schema.TypeString, + Optional: true, + Description: "Optional text description of this compute instance.", + }, + + "cloud_init": { + Type: schema.TypeString, + Optional: true, + Default: "applied", + DiffSuppressFunc: cloudInitDiffSupperss, + Description: "Optional cloud_init parameters. Applied when creating new compute instance only, ignored in all other cases.", + }, + + // The rest are Compute properties, which are "computed" once it is created + "rg_name": { + Type: schema.TypeString, + Computed: true, + Description: "Name of the resource group where this compute instance is located.", + }, + + "account_id": { + Type: schema.TypeInt, + Computed: true, + Description: "ID of the account this compute instance belongs to.", + }, + + "account_name": { + Type: schema.TypeString, + Computed: true, + Description: "Name of the account this compute instance belongs to.", + }, + + "boot_disk_id": { + Type: schema.TypeInt, + Computed: true, + Description: "This compute instance boot disk ID.", + }, + + "os_users": { + Type: schema.TypeList, + Computed: true, + Elem: &schema.Resource{ + Schema: osUsersSubresourceSchemaMake(), + }, + Description: "Guest OS users provisioned on this compute instance.", + }, + + "started": { + Type: schema.TypeBool, + Optional: true, + Default: true, + Description: "Is compute started.", + }, + }, + } +} diff --git a/internal/service/cloudbroker/kvmvm/utility_compute.go b/internal/service/cloudbroker/kvmvm/utility_compute.go new file mode 100644 index 0000000..0bf64ea --- /dev/null +++ b/internal/service/cloudbroker/kvmvm/utility_compute.go @@ -0,0 +1,310 @@ +/* +Copyright (c) 2019-2022 Digital Energy Cloud Solutions LLC. All Rights Reserved. +Authors: +Petr Krutov, +Stanislav Solovev, + +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. +*/ + +/* +Terraform DECORT provider - manage resources provided by DECORT (Digital Energy Cloud +Orchestration Technology) with Terraform by Hashicorp. + +Source code: https://github.com/rudecs/terraform-provider-decort + +Please see README.md to learn where to place source code so that it +builds seamlessly. + +Documentation: https://github.com/rudecs/terraform-provider-decort/wiki +*/ + +package kvmvm + +import ( + "context" + "encoding/json" + "fmt" + "net/url" + "strconv" + + "github.com/rudecs/terraform-provider-decort/internal/controller" + log "github.com/sirupsen/logrus" + + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" +) + +func utilityComputeExtraDisksConfigure(ctx context.Context, d *schema.ResourceData, m interface{}, do_delta bool) error { + // d is filled with data according to computeResource schema, so extra disks config is retrieved via "extra_disks" key + // If do_delta is true, this function will identify changes between new and existing specs for extra disks and try to + // update compute configuration accordingly + // Otherwise it will apply whatever is found in the new set of "extra_disks" right away. + // Primary use of do_delta=false is when calling this function from compute Create handler. + + // Note that this function will not abort on API errors, but will continue to configure (attach / detach) other individual + // disks via atomic API calls. However, it will not retry failed manipulation on the same disk. + c := m.(*controller.ControllerCfg) + + log.Debugf("utilityComputeExtraDisksConfigure: called for Compute ID %s with do_delta = %t", d.Id(), do_delta) + + // NB: as of rc-1.25 "extra_disks" are TypeSet with the elem of TypeInt + old_set, new_set := d.GetChange("extra_disks") + + apiErrCount := 0 + var lastSavedError error + + if !do_delta { + if new_set.(*schema.Set).Len() < 1 { + return nil + } + + for _, disk := range new_set.(*schema.Set).List() { + urlValues := &url.Values{} + urlValues.Add("computeId", d.Id()) + urlValues.Add("diskId", fmt.Sprintf("%d", disk.(int))) + _, err := c.DecortAPICall(ctx, "POST", ComputeDiskAttachAPI, urlValues) + if err != nil { + // failed to attach extra disk - partial resource update + apiErrCount++ + lastSavedError = err + } + } + + if apiErrCount > 0 { + log.Errorf("utilityComputeExtraDisksConfigure: there were %d error(s) when attaching disks to Compute ID %s. Last error was: %s", + apiErrCount, d.Id(), lastSavedError) + return lastSavedError + } + + return nil + } + + detach_set := old_set.(*schema.Set).Difference(new_set.(*schema.Set)) + log.Debugf("utilityComputeExtraDisksConfigure: detach set has %d items for Compute ID %s", detach_set.Len(), d.Id()) + for _, diskId := range detach_set.List() { + urlValues := &url.Values{} + urlValues.Add("computeId", d.Id()) + urlValues.Add("diskId", fmt.Sprintf("%d", diskId.(int))) + _, err := c.DecortAPICall(ctx, "POST", ComputeDiskDetachAPI, urlValues) + if err != nil { + // failed to detach disk - there will be partial resource update + log.Errorf("utilityComputeExtraDisksConfigure: failed to detach disk ID %d from Compute ID %s: %s", diskId.(int), d.Id(), err) + apiErrCount++ + lastSavedError = err + } + } + + attach_set := new_set.(*schema.Set).Difference(old_set.(*schema.Set)) + log.Debugf("utilityComputeExtraDisksConfigure: attach set has %d items for Compute ID %s", attach_set.Len(), d.Id()) + for _, diskId := range attach_set.List() { + urlValues := &url.Values{} + urlValues.Add("computeId", d.Id()) + urlValues.Add("diskId", fmt.Sprintf("%d", diskId.(int))) + _, err := c.DecortAPICall(ctx, "POST", ComputeDiskAttachAPI, urlValues) + if err != nil { + // failed to attach disk - there will be partial resource update + log.Errorf("utilityComputeExtraDisksConfigure: failed to attach disk ID %d to Compute ID %s: %s", diskId.(int), d.Id(), err) + apiErrCount++ + lastSavedError = err + } + } + + if apiErrCount > 0 { + log.Errorf("utilityComputeExtraDisksConfigure: there were %d error(s) when managing disks of Compute ID %s. Last error was: %s", + apiErrCount, d.Id(), lastSavedError) + return lastSavedError + } + + return nil +} + +func utilityComputeNetworksConfigure(ctx context.Context, d *schema.ResourceData, m interface{}, do_delta bool) error { + // "d" is filled with data according to computeResource schema, so extra networks config is retrieved via "network" key + // If do_delta is true, this function will identify changes between new and existing specs for network and try to + // update compute configuration accordingly + // Otherwise it will apply whatever is found in the new set of "network" right away. + // Primary use of do_delta=false is when calling this function from compute Create handler. + + c := m.(*controller.ControllerCfg) + + old_set, new_set := d.GetChange("network") + + apiErrCount := 0 + var lastSavedError error + + if !do_delta { + if new_set.(*schema.Set).Len() < 1 { + return nil + } + + for _, runner := range new_set.(*schema.Set).List() { + urlValues := &url.Values{} + net_data := runner.(map[string]interface{}) + urlValues.Add("computeId", d.Id()) + urlValues.Add("netType", net_data["net_type"].(string)) + urlValues.Add("netId", fmt.Sprintf("%d", net_data["net_id"].(int))) + ipaddr, ipSet := net_data["ip_address"] // "ip_address" key is optional + if ipSet { + urlValues.Add("ipAddr", ipaddr.(string)) + } + _, err := c.DecortAPICall(ctx, "POST", ComputeNetAttachAPI, urlValues) + if err != nil { + // failed to attach network - partial resource update + apiErrCount++ + lastSavedError = err + } + } + + if apiErrCount > 0 { + log.Errorf("utilityComputeNetworksConfigure: there were %d error(s) when managing networks of Compute ID %s. Last error was: %s", + apiErrCount, d.Id(), lastSavedError) + return lastSavedError + } + return nil + } + + detach_set := old_set.(*schema.Set).Difference(new_set.(*schema.Set)) + log.Debugf("utilityComputeNetworksConfigure: detach set has %d items for Compute ID %s", detach_set.Len(), d.Id()) + for _, runner := range detach_set.List() { + urlValues := &url.Values{} + net_data := runner.(map[string]interface{}) + urlValues.Add("computeId", d.Id()) + urlValues.Add("ipAddr", net_data["ip_address"].(string)) + urlValues.Add("mac", net_data["mac"].(string)) + _, err := c.DecortAPICall(ctx, "POST", ComputeNetDetachAPI, urlValues) + if err != nil { + // failed to detach this network - there will be partial resource update + log.Errorf("utilityComputeNetworksConfigure: failed to detach net ID %d of type %s from Compute ID %s: %s", + net_data["net_id"].(int), net_data["net_type"].(string), d.Id(), err) + apiErrCount++ + lastSavedError = err + } + } + + attach_set := new_set.(*schema.Set).Difference(old_set.(*schema.Set)) + log.Debugf("utilityComputeNetworksConfigure: attach set has %d items for Compute ID %s", attach_set.Len(), d.Id()) + for _, runner := range attach_set.List() { + urlValues := &url.Values{} + net_data := runner.(map[string]interface{}) + urlValues.Add("computeId", d.Id()) + urlValues.Add("netId", fmt.Sprintf("%d", net_data["net_id"].(int))) + urlValues.Add("netType", net_data["net_type"].(string)) + if net_data["ip_address"].(string) != "" { + urlValues.Add("ipAddr", net_data["ip_address"].(string)) + } + _, err := c.DecortAPICall(ctx, "POST", ComputeNetAttachAPI, urlValues) + if err != nil { + // failed to attach this network - there will be partial resource update + log.Errorf("utilityComputeNetworksConfigure: failed to attach net ID %d of type %s to Compute ID %s: %s", + net_data["net_id"].(int), net_data["net_type"].(string), d.Id(), err) + apiErrCount++ + lastSavedError = err + } + } + + if apiErrCount > 0 { + log.Errorf("utilityComputeNetworksConfigure: there were %d error(s) when managing networks of Compute ID %s. Last error was: %s", + apiErrCount, d.Id(), lastSavedError) + return lastSavedError + } + + return nil +} + +func utilityComputeCheckPresence(ctx context.Context, d *schema.ResourceData, m interface{}) (string, error) { + // This function tries to locate Compute by one of the following approaches: + // - if compute_id is specified - locate by compute ID + // - if compute_name is specified - locate by a combination of compute name and resource + // group ID + // + // If succeeded, it returns non-empty string that contains JSON formatted facts about the + // Compute as returned by compute/get API call. + // Otherwise it returns empty string and meaningful error. + // + // This function does not modify its ResourceData argument, so it is safe to use it as core + // method for resource's Exists method. + // + + c := m.(*controller.ControllerCfg) + urlValues := &url.Values{} + + // make it possible to use "read" & "check presence" functions with compute ID set so + // that Import of Compute resource is possible + idSet := false + theId, err := strconv.Atoi(d.Id()) + if err != nil || theId <= 0 { + computeId, argSet := d.GetOk("compute_id") // NB: compute_id is NOT present in computeResource schema! + if argSet { + theId = computeId.(int) + idSet = true + } + } else { + idSet = true + } + + if idSet { + // compute ID is specified, try to get compute instance straight by this ID + log.Debugf("utilityComputeCheckPresence: locating compute by its ID %d", theId) + urlValues.Add("computeId", fmt.Sprintf("%d", theId)) + computeFacts, err := c.DecortAPICall(ctx, "POST", ComputeGetAPI, urlValues) + if err != nil { + return "", err + } + return computeFacts, nil + } + + // ID was not set in the schema upon entering this function - work through Compute name + // and RG ID + computeName, argSet := d.GetOk("name") + if !argSet { + return "", fmt.Errorf("Cannot locate compute instance if name is empty and no compute ID specified") + } + + rgId, argSet := d.GetOk("rg_id") + if !argSet { + return "", fmt.Errorf("Cannot locate compute by name %s if no resource group ID is set", computeName.(string)) + } + + urlValues.Add("rgId", fmt.Sprintf("%d", rgId)) + apiResp, err := c.DecortAPICall(ctx, "POST", RgListComputesAPI, urlValues) + if err != nil { + return "", err + } + + log.Debugf("utilityComputeCheckPresence: ready to unmarshal string %s", apiResp) + + computeList := RgListComputesResp{} + err = json.Unmarshal([]byte(apiResp), &computeList) + if err != nil { + return "", err + } + + // log.Printf("%#v", computeList) + log.Debugf("utilityComputeCheckPresence: traversing decoded JSON of length %d", len(computeList)) + for index, item := range computeList { + // need to match Compute by name, skip Computes with the same name in DESTROYED satus + if item.Name == computeName.(string) && item.Status != "DESTROYED" { + log.Debugf("utilityComputeCheckPresence: index %d, matched name %s", index, item.Name) + // we found the Compute we need - now get detailed information via compute/get API + cgetValues := &url.Values{} + cgetValues.Add("computeId", fmt.Sprintf("%d", item.ID)) + apiResp, err = c.DecortAPICall(ctx, "POST", ComputeGetAPI, cgetValues) + if err != nil { + return "", err + } + return apiResp, nil + } + } + + return "", nil // there should be no error if Compute does not exist +} diff --git a/internal/service/cloudbroker/pcidevice/resource_pcidevice.go b/internal/service/cloudbroker/pcidevice/resource_pcidevice.go index dbf033c..ebcd5dc 100644 --- a/internal/service/cloudbroker/pcidevice/resource_pcidevice.go +++ b/internal/service/cloudbroker/pcidevice/resource_pcidevice.go @@ -47,22 +47,6 @@ import ( func resourcePcideviceCreate(ctx context.Context, d *schema.ResourceData, m interface{}) diag.Diagnostics { log.Debugf("resourcePcideviceCreate: called for pcidevice %s", d.Get("name").(string)) - if deviceId, ok := d.GetOk("device_id"); ok { - if exists, err := resourcePcideviceExists(ctx, d, m); exists { - if err != nil { - return diag.FromErr(err) - } - d.SetId(strconv.Itoa(deviceId.(int))) - diagnostics := resourcePcideviceRead(ctx, d, m) - if diagnostics != nil { - return diagnostics - } - - return nil - } - return diag.Errorf("provided device id does not exist") - } - c := m.(*controller.ControllerCfg) urlValues := &url.Values{} urlValues.Add("name", d.Get("name").(string)) diff --git a/internal/service/cloudbroker/pfw/api.go b/internal/service/cloudbroker/pfw/api.go new file mode 100644 index 0000000..6268336 --- /dev/null +++ b/internal/service/cloudbroker/pfw/api.go @@ -0,0 +1,36 @@ +/* +Copyright (c) 2019-2022 Digital Energy Cloud Solutions LLC. All Rights Reserved. +Authors: +Petr Krutov, +Stanislav Solovev, + +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. +*/ + +/* +Terraform DECORT provider - manage resources provided by DECORT (Digital Energy Cloud +Orchestration Technology) with Terraform by Hashicorp. + +Source code: https://github.com/rudecs/terraform-provider-decort + +Please see README.md to learn where to place source code so that it +builds seamlessly. + +Documentation: https://github.com/rudecs/terraform-provider-decort/wiki +*/ + +package pfw + +const ComputePfwListAPI = "/restmachine/cloudbroker/compute/pfwList" +const ComputePfwAddAPI = "/restmachine/cloudbroker/compute/pfwAdd" +const ComputePfwDelAPI = "/restmachine/cloudbroker/compute/pfwDel" diff --git a/internal/service/cloudbroker/pfw/models.go b/internal/service/cloudbroker/pfw/models.go new file mode 100644 index 0000000..e74524b --- /dev/null +++ b/internal/service/cloudbroker/pfw/models.go @@ -0,0 +1,45 @@ +/* +Copyright (c) 2019-2022 Digital Energy Cloud Solutions LLC. All Rights Reserved. +Authors: +Petr Krutov, +Stanislav Solovev, + +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. +*/ + +/* +Terraform DECORT provider - manage resources provided by DECORT (Digital Energy Cloud +Orchestration Technology) with Terraform by Hashicorp. + +Source code: https://github.com/rudecs/terraform-provider-decort + +Please see README.md to learn where to place source code so that it +builds seamlessly. + +Documentation: https://github.com/rudecs/terraform-provider-decort/wiki +*/ + +package pfw +type PfwRecord struct { + ID int `json:"id"` + LocalIP string `json:"localIp"` + LocalPort int `json:"localPort"` + Protocol string `json:"protocol"` + PublicPortEnd int `json:"publicPortEnd"` + PublicPortStart int `json:"publicPortStart"` + ComputeID int `json:"vmId"` +} + +type ComputePfwListResp []PfwRecord + + diff --git a/internal/service/cloudbroker/pfw/resource_pfw.go b/internal/service/cloudbroker/pfw/resource_pfw.go new file mode 100644 index 0000000..199187b --- /dev/null +++ b/internal/service/cloudbroker/pfw/resource_pfw.go @@ -0,0 +1,211 @@ +/* +Copyright (c) 2019-2022 Digital Energy Cloud Solutions LLC. All Rights Reserved. +Authors: +Petr Krutov, +Stanislav Solovev, + +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. +*/ + +/* +Terraform DECORT provider - manage resources provided by DECORT (Digital Energy Cloud +Orchestration Technology) with Terraform by Hashicorp. + +Source code: https://github.com/rudecs/terraform-provider-decort + +Please see README.md to learn where to place source code so that it +builds seamlessly. + +Documentation: https://github.com/rudecs/terraform-provider-decort/wiki +*/ + +package pfw + +import ( + "context" + "fmt" + "net/url" + "strconv" + + "github.com/hashicorp/terraform-plugin-sdk/v2/diag" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/validation" + "github.com/rudecs/terraform-provider-decort/internal/constants" + "github.com/rudecs/terraform-provider-decort/internal/controller" + log "github.com/sirupsen/logrus" +) + +func resourcePfwCreate(ctx context.Context, d *schema.ResourceData, m interface{}) diag.Diagnostics { + log.Debugf("resourcePfwCreate: called for compute %d", d.Get("compute_id").(int)) + + c := m.(*controller.ControllerCfg) + urlValues := &url.Values{} + urlValues.Add("computeId", strconv.Itoa(d.Get("compute_id").(int))) + urlValues.Add("publicPortStart", strconv.Itoa(d.Get("public_port_start").(int))) + urlValues.Add("localBasePort", strconv.Itoa(d.Get("local_base_port").(int))) + urlValues.Add("proto", d.Get("proto").(string)) + + if portEnd, ok := d.GetOk("public_port_end"); ok { + urlValues.Add("publicPortEnd", strconv.Itoa(portEnd.(int))) + } + + pfwId, err := c.DecortAPICall(ctx, "POST", ComputePfwAddAPI, urlValues) + if err != nil { + return diag.FromErr(err) + } + + d.SetId(fmt.Sprintf("%d-%s", d.Get("compute_id").(int), pfwId)) + + pfw, err := utilityPfwCheckPresence(ctx, d, m) + if err != nil { + return diag.FromErr(err) + } + + d.Set("local_ip", pfw.LocalIP) + if _, ok := d.GetOk("public_port_end"); !ok { + d.Set("public_port_end", pfw.PublicPortEnd) + } + + return nil +} + +func resourcePfwRead(ctx context.Context, d *schema.ResourceData, m interface{}) diag.Diagnostics { + log.Debugf("resourcePfwRead: called for compute %d, rule %s", d.Get("compute_id").(int), d.Id()) + + pfw, err := utilityPfwCheckPresence(ctx, d, m) + if pfw == nil { + d.SetId("") + return diag.FromErr(err) + } + + d.Set("compute_id", pfw.ComputeID) + d.Set("public_port_start", pfw.PublicPortStart) + d.Set("public_port_end", pfw.PublicPortEnd) + d.Set("local_ip", pfw.LocalIP) + d.Set("local_base_port", pfw.LocalPort) + d.Set("proto", pfw.Protocol) + + return nil +} + +func resourcePfwDelete(ctx context.Context, d *schema.ResourceData, m interface{}) diag.Diagnostics { + log.Debugf("resourcePfwDelete: called for compute %d, rule %s", d.Get("compute_id").(int), d.Id()) + + pfw, err := utilityPfwCheckPresence(ctx, d, m) + if pfw == nil { + if err != nil { + return diag.FromErr(err) + } + return nil + } + + c := m.(*controller.ControllerCfg) + urlValues := &url.Values{} + urlValues.Add("computeId", strconv.Itoa(d.Get("compute_id").(int))) + urlValues.Add("ruleId", strconv.Itoa(pfw.ID)) + + _, err = c.DecortAPICall(ctx, "POST", ComputePfwDelAPI, urlValues) + if err != nil { + return diag.FromErr(err) + } + + return nil +} + +func resourcePfwExists(ctx context.Context, d *schema.ResourceData, m interface{}) (bool, error) { + log.Debugf("resourcePfwExists: called for compute %d, rule %s", d.Get("compute_id").(int), d.Id()) + + pfw, err := utilityPfwCheckPresence(ctx, d, m) + if pfw == nil { + if err != nil { + return false, err + } + return false, nil + } + + return true, nil +} + +func resourcePfwSchemaMake() map[string]*schema.Schema { + return map[string]*schema.Schema{ + "compute_id": { + Type: schema.TypeInt, + Required: true, + ForceNew: true, + Description: "ID of compute instance.", + }, + + "public_port_start": { + Type: schema.TypeInt, + Required: true, + ForceNew: true, + ValidateFunc: validation.IntBetween(1, 65535), + Description: "External start port number for the rule.", + }, + + "public_port_end": { + Type: schema.TypeInt, + Optional: true, + Computed: true, + ForceNew: true, + ValidateFunc: validation.IntBetween(1, 65535), + Description: "End port number (inclusive) for the ranged rule.", + }, + + "local_ip": { + Type: schema.TypeString, + Computed: true, + Description: "IP address of compute instance.", + }, + + "local_base_port": { + Type: schema.TypeInt, + Required: true, + ForceNew: true, + ValidateFunc: validation.IntBetween(1, 65535), + Description: "Internal base port number.", + }, + + "proto": { + Type: schema.TypeString, + Required: true, + ForceNew: true, + ValidateFunc: validation.StringInSlice([]string{"tcp", "udp"}, false), + Description: "Network protocol, either 'tcp' or 'udp'.", + }, + } +} + +func ResourcePfw() *schema.Resource { + return &schema.Resource{ + SchemaVersion: 1, + + CreateContext: resourcePfwCreate, + ReadContext: resourcePfwRead, + DeleteContext: resourcePfwDelete, + + Importer: &schema.ResourceImporter{ + State: schema.ImportStatePassthrough, + }, + + Timeouts: &schema.ResourceTimeout{ + Create: &constants.Timeout60s, + Read: &constants.Timeout30s, + Update: &constants.Timeout60s, + Delete: &constants.Timeout60s, + Default: &constants.Timeout60s, + }, + + Schema: resourcePfwSchemaMake(), + } +} diff --git a/internal/service/cloudbroker/pfw/utility_pfw.go b/internal/service/cloudbroker/pfw/utility_pfw.go new file mode 100644 index 0000000..0f5729f --- /dev/null +++ b/internal/service/cloudbroker/pfw/utility_pfw.go @@ -0,0 +1,77 @@ +/* +Copyright (c) 2019-2022 Digital Energy Cloud Solutions LLC. All Rights Reserved. +Authors: +Petr Krutov, +Stanislav Solovev, + +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. +*/ + +/* +Terraform DECORT provider - manage resources provided by DECORT (Digital Energy Cloud +Orchestration Technology) with Terraform by Hashicorp. + +Source code: https://github.com/rudecs/terraform-provider-decort + +Please see README.md to learn where to place source code so that it +builds seamlessly. + +Documentation: https://github.com/rudecs/terraform-provider-decort/wiki +*/ + +package pfw + +import ( + "context" + "encoding/json" + "net/url" + "strconv" + "strings" + + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" + "github.com/rudecs/terraform-provider-decort/internal/controller" +) + +func utilityPfwCheckPresence(ctx context.Context, d *schema.ResourceData, m interface{}) (*PfwRecord, error) { + c := m.(*controller.ControllerCfg) + urlValues := &url.Values{} + + urlValues.Add("computeId", strconv.Itoa(d.Get("compute_id").(int))) + resp, err := c.DecortAPICall(ctx, "POST", ComputePfwListAPI, urlValues) + if err != nil { + return nil, err + } + + if resp == "" { + return nil, nil + } + + idS := strings.Split(d.Id(), "-")[1] + id, err := strconv.Atoi(idS) + if err != nil { + return nil, err + } + + var pfws []PfwRecord + if err := json.Unmarshal([]byte(resp), &pfws); err != nil { + return nil, err + } + + for _, pfw := range pfws { + if pfw.ID == id { + return &pfw, nil + } + } + + return nil, nil +} diff --git a/internal/service/cloudbroker/rg/api.go b/internal/service/cloudbroker/rg/api.go new file mode 100644 index 0000000..0d098bc --- /dev/null +++ b/internal/service/cloudbroker/rg/api.go @@ -0,0 +1,39 @@ +/* +Copyright (c) 2019-2022 Digital Energy Cloud Solutions LLC. All Rights Reserved. +Authors: +Petr Krutov, +Stanislav Solovev, + +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. +*/ + +/* +Terraform DECORT provider - manage resources provided by DECORT (Digital Energy Cloud +Orchestration Technology) with Terraform by Hashicorp. + +Source code: https://github.com/rudecs/terraform-provider-decort + +Please see README.md to learn where to place source code so that it +builds seamlessly. + +Documentation: https://github.com/rudecs/terraform-provider-decort/wiki +*/ + +package rg + +const ResgroupCreateAPI = "/restmachine/cloudbroker/rg/create" +const ResgroupUpdateAPI = "/restmachine/cloudbroker/rg/update" +const ResgroupListAPI = "/restmachine/cloudbroker/rg/list" +const ResgroupGetAPI = "/restmachine/cloudbroker/rg/get" +const ResgroupDeleteAPI = "/restmachine/cloudbroker/rg/delete" +const RgListComputesAPI = "/restmachine/cloudbroker/rg/listComputes" diff --git a/internal/service/cloudbroker/rg/data_source_rg.go b/internal/service/cloudbroker/rg/data_source_rg.go new file mode 100644 index 0000000..3afdb69 --- /dev/null +++ b/internal/service/cloudbroker/rg/data_source_rg.go @@ -0,0 +1,196 @@ +/* +Copyright (c) 2019-2022 Digital Energy Cloud Solutions LLC. All Rights Reserved. +Authors: +Petr Krutov, +Stanislav Solovev, + +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. +*/ + +/* +Terraform DECORT provider - manage resources provided by DECORT (Digital Energy Cloud +Orchestration Technology) with Terraform by Hashicorp. + +Source code: https://github.com/rudecs/terraform-provider-decort + +Please see README.md to learn where to place source code so that it +builds seamlessly. + +Documentation: https://github.com/rudecs/terraform-provider-decort/wiki +*/ + +package rg + +import ( + "context" + "encoding/json" + "fmt" + + "github.com/rudecs/terraform-provider-decort/internal/constants" + log "github.com/sirupsen/logrus" + + // "net/url" + + "github.com/hashicorp/terraform-plugin-sdk/v2/diag" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" +) + +func flattenResgroup(d *schema.ResourceData, rg_facts string) error { + // NOTE: this function modifies ResourceData argument - as such it should never be called + // from resourceRsgroupExists(...) method + // log.Debugf("%s", rg_facts) + log.Debugf("flattenResgroup: ready to decode response body from API") + details := ResgroupGetResp{} + err := json.Unmarshal([]byte(rg_facts), &details) + if err != nil { + return err + } + + log.Debugf("flattenResgroup: decoded RG name %q / ID %d, account ID %d", + details.Name, details.ID, details.AccountID) + + d.SetId(fmt.Sprintf("%d", details.ID)) + d.Set("rg_id", details.ID) + d.Set("name", details.Name) + d.Set("account_name", details.AccountName) + d.Set("account_id", details.AccountID) + // d.Set("grid_id", details.GridID) + d.Set("description", details.Desc) + d.Set("status", details.Status) + d.Set("def_net_type", details.DefaultNetType) + d.Set("def_net_id", details.DefaultNetID) + /* + d.Set("vins", details.Vins) + d.Set("computes", details.Computes) + */ + + log.Debugf("flattenResgroup: calling flattenQuota()") + if err = d.Set("quota", parseQuota(details.Quota)); err != nil { + return err + } + + return nil +} + +func dataSourceResgroupRead(ctx context.Context, d *schema.ResourceData, m interface{}) diag.Diagnostics { + rg_facts, err := utilityResgroupCheckPresence(ctx, d, m) + if rg_facts == "" { + // if empty string is returned from utilityResgroupCheckPresence then there is no + // such resource group and err tells so - just return it to the calling party + d.SetId("") // ensure ID is empty in this case + return diag.FromErr(err) + } + + return diag.FromErr(flattenResgroup(d, rg_facts)) +} + +func DataSourceResgroup() *schema.Resource { + return &schema.Resource{ + SchemaVersion: 1, + + ReadContext: dataSourceResgroupRead, + + Timeouts: &schema.ResourceTimeout{ + Read: &constants.Timeout30s, + Default: &constants.Timeout60s, + }, + + Schema: map[string]*schema.Schema{ + "name": { + Type: schema.TypeString, + Optional: true, + Description: "Name of the resource group. Names are case sensitive and unique within the context of an account.", + }, + + "rg_id": { + Type: schema.TypeInt, + Optional: true, + Description: "Unique ID of the resource group. If this ID is specified, then resource group name is ignored.", + }, + + "account_name": { + Type: schema.TypeString, + Computed: true, + Description: "Name of the account, which this resource group belongs to.", + }, + + "account_id": { + Type: schema.TypeInt, + Required: true, + Description: "Unique ID of the account, which this resource group belongs to.", + }, + + "description": { + Type: schema.TypeString, + Computed: true, + Description: "User-defined text description of this resource group.", + }, + + /* commented out, as in this version of provider we use default Grid ID + "grid_id": { + Type: schema.TypeInt, + Computed: true, + Description: "Unique ID of the grid, where this resource group is deployed.", + }, + */ + + "quota": { + Type: schema.TypeList, + Computed: true, + Elem: &schema.Resource{ + Schema: quotaRgSubresourceSchemaMake(), // this is a dictionary + }, + Description: "Quota settings for this resource group.", + }, + + "def_net_type": { + Type: schema.TypeString, + Computed: true, + Description: "Type of the default network for this resource group.", + }, + + "def_net_id": { + Type: schema.TypeInt, + Computed: true, + Description: "ID of the default network for this resource group (if any).", + }, + + /* + "status": { + Type: schema.TypeString, + Computed: true, + Description: "Current status of this resource group.", + }, + + "vins": { + Type: schema.TypeList, // this is a list of ints + Computed: true, + MaxItems: LimitMaxVinsPerResgroup, + Elem: &schema.Schema{ + Type: schema.TypeInt, + }, + Description: "List of VINs deployed in this resource group.", + }, + + "computes": { + Type: schema.TypeList, //t his is a list of ints + Computed: true, + Elem: &schema.Schema{ + Type: schema.TypeInt, + }, + Description: "List of computes deployed in this resource group.", + }, + */ + }, + } +} diff --git a/internal/service/cloudbroker/rg/data_source_rg_list.go b/internal/service/cloudbroker/rg/data_source_rg_list.go new file mode 100644 index 0000000..dfbb888 --- /dev/null +++ b/internal/service/cloudbroker/rg/data_source_rg_list.go @@ -0,0 +1,324 @@ +/* +Copyright (c) 2019-2022 Digital Energy Cloud Solutions LLC. All Rights Reserved. +Authors: +Petr Krutov, +Stanislav Solovev, + +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. +*/ + +/* +Terraform DECORT provider - manage resources provided by DECORT (Digital Energy Cloud +Orchestration Technology) with Terraform by Hashicorp. + +Source code: https://github.com/rudecs/terraform-provider-decort + +Please see README.md to learn where to place source code so that it +builds seamlessly. + +Documentation: https://github.com/rudecs/terraform-provider-decort/wiki +*/ + +package rg + +import ( + "context" + + "github.com/google/uuid" + "github.com/hashicorp/terraform-plugin-sdk/v2/diag" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" + "github.com/rudecs/terraform-provider-decort/internal/constants" +) + +func flattenRgList(rgl ResgroupListResp) []map[string]interface{} { + res := make([]map[string]interface{}, 0) + for _, rg := range rgl { + temp := map[string]interface{}{ + "account_id": rg.AccountID, + "account_name": rg.AccountName, + "acl": flattenRgAcl(rg.ACLs), + "created_by": rg.CreatedBy, + "created_time": rg.CreatedTime, + "def_net_id": rg.DefaultNetID, + "def_net_type": rg.DefaultNetType, + "deleted_by": rg.DeletedBy, + "deleted_time": rg.DeletedTime, + "desc": rg.Decsription, + "gid": rg.GridID, + "guid": rg.GUID, + "rg_id": rg.ID, + "lock_status": rg.LockStatus, + "milestones": rg.Milestones, + "name": rg.Name, + "register_computes": rg.RegisterComputes, + "resource_limits": flattenRgResourceLimits(rg.ResourceLimits), + "secret": rg.Secret, + "status": rg.Status, + "updated_by": rg.UpdatedBy, + "updated_time": rg.UpdatedTime, + "vins": rg.Vins, + "vms": rg.Computes, + } + res = append(res, temp) + } + return res + +} + +func flattenRgAcl(rgAcls []AccountAclRecord) []map[string]interface{} { + res := make([]map[string]interface{}, 0) + for _, rgAcl := range rgAcls { + temp := map[string]interface{}{ + "explicit": rgAcl.IsExplicit, + "guid": rgAcl.Guid, + "right": rgAcl.Rights, + "status": rgAcl.Status, + "type": rgAcl.Type, + "user_group_id": rgAcl.UgroupID, + } + res = append(res, temp) + } + return res +} + +func flattenRgResourceLimits(rl ResourceLimits) []map[string]interface{} { + res := make([]map[string]interface{}, 0) + temp := map[string]interface{}{ + "cu_c": rl.CUC, + "cu_d": rl.CUD, + "cu_i": rl.CUI, + "cu_m": rl.CUM, + "cu_np": rl.CUNP, + "gpu_units": rl.GpuUnits, + } + res = append(res, temp) + + return res + +} + +func dataSourceRgListRead(ctx context.Context, d *schema.ResourceData, m interface{}) diag.Diagnostics { + rgList, err := utilityRgListCheckPresence(ctx, d, m) + if err != nil { + return diag.FromErr(err) + } + + id := uuid.New() + d.SetId(id.String()) + d.Set("items", flattenRgList(rgList)) + + return nil +} + +func dataSourceRgListSchemaMake() map[string]*schema.Schema { + res := map[string]*schema.Schema{ + "includedeleted": { + Type: schema.TypeBool, + Optional: true, + Default: false, + Description: "included deleted resource groups", + }, + "page": { + Type: schema.TypeInt, + Optional: true, + Description: "Page number", + }, + "size": { + Type: schema.TypeInt, + Optional: true, + Description: "Page size", + }, + "items": { + Type: schema.TypeList, + Computed: true, + Elem: &schema.Resource{ + Schema: map[string]*schema.Schema{ + "account_id": { + Type: schema.TypeInt, + Computed: true, + }, + "account_name": { + Type: schema.TypeString, + Computed: true, + }, + "acl": { + Type: schema.TypeList, + Computed: true, + Elem: &schema.Resource{ + Schema: map[string]*schema.Schema{ + "explicit": { + Type: schema.TypeBool, + Computed: true, + }, + "guid": { + Type: schema.TypeString, + Computed: true, + }, + "right": { + Type: schema.TypeString, + Computed: true, + }, + "status": { + Type: schema.TypeString, + Computed: true, + }, + "type": { + Type: schema.TypeString, + Computed: true, + }, + "user_group_id": { + Type: schema.TypeString, + Computed: true, + }, + }, + }, + }, + "created_by": { + Type: schema.TypeString, + Computed: true, + }, + "created_time": { + Type: schema.TypeInt, + Computed: true, + }, + "def_net_id": { + Type: schema.TypeInt, + Computed: true, + }, + "def_net_type": { + Type: schema.TypeString, + Computed: true, + }, + "deleted_by": { + Type: schema.TypeString, + Computed: true, + }, + "deleted_time": { + Type: schema.TypeInt, + Computed: true, + }, + "desc": { + Type: schema.TypeString, + Computed: true, + }, + "gid": { + Type: schema.TypeInt, + Computed: true, + }, + "guid": { + Type: schema.TypeInt, + Computed: true, + }, + "rg_id": { + Type: schema.TypeInt, + Computed: true, + }, + "lock_status": { + Type: schema.TypeString, + Computed: true, + }, + "milestones": { + Type: schema.TypeInt, + Computed: true, + }, + "name": { + Type: schema.TypeString, + Computed: true, + }, + "register_computes": { + Type: schema.TypeBool, + Computed: true, + }, + "resource_limits": { + Type: schema.TypeList, + Computed: true, + Elem: &schema.Resource{ + Schema: map[string]*schema.Schema{ + "cu_c": { + Type: schema.TypeFloat, + Computed: true, + }, + "cu_d": { + Type: schema.TypeFloat, + Computed: true, + }, + "cu_i": { + Type: schema.TypeFloat, + Computed: true, + }, + "cu_m": { + Type: schema.TypeFloat, + Computed: true, + }, + "cu_np": { + Type: schema.TypeFloat, + Computed: true, + }, + "gpu_units": { + Type: schema.TypeFloat, + Computed: true, + }, + }, + }, + }, + "secret": { + Type: schema.TypeString, + Computed: true, + }, + "status": { + Type: schema.TypeString, + Computed: true, + }, + "updated_by": { + Type: schema.TypeString, + Computed: true, + }, + "updated_time": { + Type: schema.TypeInt, + Computed: true, + }, + "vins": { + Type: schema.TypeList, + Computed: true, + Elem: &schema.Schema{ + Type: schema.TypeInt, + }, + }, + "vms": { + Type: schema.TypeList, + Computed: true, + Elem: &schema.Schema{ + Type: schema.TypeInt, + }, + }, + }, + }, + }, + } + return res +} + +func DataSourceRgList() *schema.Resource { + return &schema.Resource{ + SchemaVersion: 1, + + ReadContext: dataSourceRgListRead, + + Timeouts: &schema.ResourceTimeout{ + Read: &constants.Timeout30s, + Default: &constants.Timeout60s, + }, + + Schema: dataSourceRgListSchemaMake(), + } +} diff --git a/internal/service/cloudbroker/rg/models.go b/internal/service/cloudbroker/rg/models.go new file mode 100644 index 0000000..f1f6e05 --- /dev/null +++ b/internal/service/cloudbroker/rg/models.go @@ -0,0 +1,149 @@ +/* +Copyright (c) 2019-2022 Digital Energy Cloud Solutions LLC. All Rights Reserved. +Authors: +Petr Krutov, +Stanislav Solovev, + +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. +*/ + +/* +Terraform DECORT provider - manage resources provided by DECORT (Digital Energy Cloud +Orchestration Technology) with Terraform by Hashicorp. + +Source code: https://github.com/rudecs/terraform-provider-decort + +Please see README.md to learn where to place source code so that it +builds seamlessly. + +Documentation: https://github.com/rudecs/terraform-provider-decort/wiki +*/ + +package rg + +type ResourceLimits struct { + CUC float64 `json:"CU_C"` + CUD float64 `json:"CU_D"` + CUI float64 `json:"CU_I"` + CUM float64 `json:"CU_M"` + CUNP float64 `json:"CU_NP"` + GpuUnits float64 `json:"gpu_units"` +} + +type ResgroupRecord struct { + ACLs []AccountAclRecord `json:"acl"` + AccountID int `json:"accountId"` + AccountName string `json:"accountName"` + CreatedBy string `json:"createdBy"` + CreatedTime uint64 `json:"createdTime"` + DefaultNetID int `json:"def_net_id"` + DefaultNetType string `json:"def_net_type"` + DeletedBy string `json:"deletedBy"` + DeletedTime int `json:"deletedTime"` + Decsription string `json:"desc"` + GridID int `json:"gid"` + GUID int `json:"guid"` + ID uint `json:"id"` + LockStatus string `json:"lockStatus"` + Milestones int `json:"milestones"` + Name string `json:"name"` + RegisterComputes bool `json:"registerComputes"` + ResourceLimits ResourceLimits `json:"resourceLimits"` + Secret string `json:"secret"` + Status string `json:"status"` + UpdatedBy string `json:"updatedBy"` + UpdatedTime uint64 `json:"updatedTime"` + Vins []int `json:"vins"` + Computes []int `json:"vms"` +} + +type ResgroupListResp []ResgroupRecord + +type ResgroupUpdateParam struct { + RgId int `json:"rgId"` + Name string `json:"name"` + Desc string `json:"decs"` + Ram int `json:"maxMemoryCapacity"` + Disk int `json:"maxVDiskCapacity"` + Cpu int `json:"maxCPUCapacity"` + NetTraffic int `json:"maxNetworkPeerTransfer"` + Reason string `json:"reason"` +} + +type AccountAclRecord struct { + IsExplicit bool `json:"explicit"` + Guid string `json:"guid"` + Rights string `json:"right"` + Status string `json:"status"` + Type string `json:"type"` + UgroupID string `json:"userGroupId"` + CanBeDeleted bool `json:"canBeDeleted"` +} + +type ResgroupGetResp struct { + ACLs []UserAclRecord `json:"ACLs"` + Usage UsageRecord `json:"Resources"` + AccountID int `json:"accountId"` + AccountName string `json:"accountName"` + GridID int `json:"gid"` + CreatedBy string `json:"createdBy"` + CreatedTime uint64 `json:"createdTime"` + DefaultNetID int `json:"def_net_id"` + DefaultNetType string `json:"def_net_type"` + DeletedBy string `json:"deletedBy"` + DeletedTime uint64 `json:"deletedTime"` + Desc string `json:"desc"` + ID uint `json:"id"` + LockStatus string `json:"lockStatus"` + Name string `json:"name"` + Quota QuotaRecord `json:"resourceLimits"` + Status string `json:"status"` + UpdatedBy string `json:"updatedBy"` + UpdatedTime uint64 `json:"updatedTime"` + Vins []int `json:"vins"` + Computes []int `json:"vms"` + + Ignored map[string]interface{} `json:"-"` +} + +type UserAclRecord struct { + IsExplicit bool `json:"explicit"` + Rights string `json:"right"` + Status string `json:"status"` + Type string `json:"type"` + UgroupID string `json:"userGroupId"` + // CanBeDeleted bool `json:"canBeDeleted"` +} + +type QuotaRecord struct { // this is how quota is reported by /api/.../rg/get + Cpu int `json:"CU_C"` // CPU count in pcs + Ram float64 `json:"CU_M"` // RAM volume in MB, it is STILL reported as FLOAT + Disk int `json:"CU_D"` // Disk capacity in GB + ExtIPs int `json:"CU_I"` // Ext IPs count + ExtTraffic int `json:"CU_NP"` // Ext network traffic + GpuUnits int `json:"gpu_units"` // GPU count +} + +type ResourceRecord struct { // this is how actual usage is reported by /api/.../rg/get + Cpu int `json:"cpu"` + Disk int `json:"disksize"` + ExtIPs int `json:"extips"` + ExtTraffic int `json:"exttraffic"` + Gpu int `json:"gpu"` + Ram int `json:"ram"` +} + +type UsageRecord struct { + Current ResourceRecord `json:"Current"` + Reserved ResourceRecord `json:"Reserved"` +} diff --git a/internal/service/cloudbroker/rg/quota_subresource.go b/internal/service/cloudbroker/rg/quota_subresource.go new file mode 100644 index 0000000..6da4300 --- /dev/null +++ b/internal/service/cloudbroker/rg/quota_subresource.go @@ -0,0 +1,137 @@ +/* +Copyright (c) 2019-2022 Digital Energy Cloud Solutions LLC. All Rights Reserved. +Authors: +Petr Krutov, +Stanislav Solovev, + +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. +*/ + +/* +Terraform DECORT provider - manage resources provided by DECORT (Digital Energy Cloud +Orchestration Technology) with Terraform by Hashicorp. + +Source code: https://github.com/rudecs/terraform-provider-decort + +Please see README.md to learn where to place source code so that it +builds seamlessly. + +Documentation: https://github.com/rudecs/terraform-provider-decort/wiki +*/ + +package rg + +import ( + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" +) + +func makeQuotaRecord(arg_list []interface{}) QuotaRecord { + quota := QuotaRecord{ + Cpu: -1, + Ram: -1., // this is float64, but may change in the future + Disk: -1, + ExtTraffic: -1, + ExtIPs: -1, + GpuUnits: -1, + } + subres_data := arg_list[0].(map[string]interface{}) + + if subres_data["cpu"].(int) > 0 { + quota.Cpu = subres_data["cpu"].(int) + } + + if subres_data["disk"].(int) > 0 { + quota.Disk = subres_data["disk"].(int) // Disk capacity ib GB + } + + if subres_data["ram"].(float64) > 0 { + quota.Ram = subres_data["ram"].(float64) // RAM volume in MB, as float64! + } + + if subres_data["ext_traffic"].(int) > 0 { + quota.ExtTraffic = subres_data["ext_traffic"].(int) + } + + if subres_data["ext_ips"].(int) > 0 { + quota.ExtIPs = subres_data["ext_ips"].(int) + } + + if subres_data["gpu_units"].(int) > 0 { + quota.GpuUnits = subres_data["gpu_units"].(int) + } + + return quota +} + +func parseQuota(quota QuotaRecord) []interface{} { + quota_map := make(map[string]interface{}) + + quota_map["cpu"] = quota.Cpu + quota_map["ram"] = quota.Ram // NB: this is float64, unlike the rest of values + quota_map["disk"] = quota.Disk + quota_map["ext_traffic"] = quota.ExtTraffic + quota_map["ext_ips"] = quota.ExtIPs + quota_map["gpu_units"] = quota.GpuUnits + + result := make([]interface{}, 1) + result[0] = quota_map + + return result // this result will be used to d.Set("quota,") of dataSourceResgroup schema +} + +func quotaRgSubresourceSchemaMake() map[string]*schema.Schema { + rets := map[string]*schema.Schema{ + "cpu": { + Type: schema.TypeInt, + Optional: true, + Default: -1, + Description: "Limit on the total number of CPUs in this resource group.", + }, + + "ram": { + Type: schema.TypeFloat, // NB: API expects and returns this as float in units of MB! This may be changed in the future. + Optional: true, + Default: -1., + Description: "Limit on the total amount of RAM in this resource group, specified in MB.", + }, + + "disk": { + Type: schema.TypeInt, + Optional: true, + Default: -1, + Description: "Limit on the total volume of storage resources in this resource group, specified in GB.", + }, + + "ext_traffic": { + Type: schema.TypeInt, + Optional: true, + Default: -1, + Description: "Limit on the total ingress network traffic for this resource group, specified in GB.", + }, + + "ext_ips": { + Type: schema.TypeInt, + Optional: true, + Default: -1, + Description: "Limit on the total number of external IP addresses this resource group can use.", + }, + + "gpu_units": { + Type: schema.TypeInt, + Optional: true, + Default: -1, + Description: "Limit on the total number of virtual GPUs this resource group can use.", + }, + } + return rets +} diff --git a/internal/service/cloudbroker/rg/resource_rg.go b/internal/service/cloudbroker/rg/resource_rg.go new file mode 100644 index 0000000..d893334 --- /dev/null +++ b/internal/service/cloudbroker/rg/resource_rg.go @@ -0,0 +1,442 @@ +/* +Copyright (c) 2019-2022 Digital Energy Cloud Solutions LLC. All Rights Reserved. +Authors: +Petr Krutov, +Stanislav Solovev, + +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. +*/ + +/* +Terraform DECORT provider - manage resources provided by DECORT (Digital Energy Cloud +Orchestration Technology) with Terraform by Hashicorp. + +Source code: https://github.com/rudecs/terraform-provider-decort + +Please see README.md to learn where to place source code so that it +builds seamlessly. + +Documentation: https://github.com/rudecs/terraform-provider-decort/wiki +*/ + +package rg + +import ( + "context" + "encoding/json" + "fmt" + "net/url" + + "github.com/rudecs/terraform-provider-decort/internal/constants" + "github.com/rudecs/terraform-provider-decort/internal/controller" + "github.com/rudecs/terraform-provider-decort/internal/location" + log "github.com/sirupsen/logrus" + + "github.com/hashicorp/terraform-plugin-sdk/v2/diag" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/validation" +) + +func resourceResgroupCreate(ctx context.Context, d *schema.ResourceData, m interface{}) diag.Diagnostics { + // First validate that we have all parameters required to create the new Resource Group + + // Valid account ID is required to create new resource group + // obtain Account ID by account name - it should not be zero on success + + rg_name, arg_set := d.GetOk("name") + if !arg_set { + return diag.FromErr(fmt.Errorf("Cannot create new RG: missing name.")) + } + + /* Current version of provider works with default grid id (same is true for disk resources) + grid_id, arg_set := d.GetOk("grid_id") + if !arg_set { + return fmt.Errorf("Cannot create new RG %q in account ID %d: missing Grid ID.", + rg_name.(string), validated_account_id) + } + if grid_id.(int) < 1 { + grid_id = DefaultGridID + } + */ + + // all required parameters are set in the schema - we can continue with RG creation + log.Debugf("resourceResgroupCreate: called for RG name %s, account ID %d", + rg_name.(string), d.Get("account_id").(int)) + + // quota settings are optional + set_quota := false + var quota_record QuotaRecord + arg_value, arg_set := d.GetOk("quota") + if arg_set { + log.Debugf("resourceResgroupCreate: setting Quota on RG requested") + quota_record = makeQuotaRecord(arg_value.([]interface{})) + set_quota = true + } + + c := m.(*controller.ControllerCfg) + log.Debugf("resourceResgroupCreate: called by user %q for RG name %s, account ID %d", + c.GetDecortUsername(), + rg_name.(string), d.Get("account_id").(int)) + + url_values := &url.Values{} + url_values.Add("accountId", fmt.Sprintf("%d", d.Get("account_id").(int))) + url_values.Add("name", rg_name.(string)) + url_values.Add("gid", fmt.Sprintf("%d", location.DefaultGridID)) // use default Grid ID, similar to disk resource mgmt convention + url_values.Add("owner", c.GetDecortUsername()) + + // pass quota values as set + if set_quota { + url_values.Add("maxCPUCapacity", fmt.Sprintf("%d", quota_record.Cpu)) + url_values.Add("maxVDiskCapacity", fmt.Sprintf("%d", quota_record.Disk)) + url_values.Add("maxMemoryCapacity", fmt.Sprintf("%f", quota_record.Ram)) // RAM quota is float; this may change in the future + url_values.Add("maxNetworkPeerTransfer", fmt.Sprintf("%d", quota_record.ExtTraffic)) + url_values.Add("maxNumPublicIP", fmt.Sprintf("%d", quota_record.ExtIPs)) + // url_values.Add("???", fmt.Sprintf("%d", quota_record.GpuUnits)) + } + + // parse and handle network settings + def_net_type, arg_set := d.GetOk("def_net_type") + if arg_set { + url_values.Add("def_net", def_net_type.(string)) // NOTE: in API default network type is set by "def_net" parameter + } + + ipcidr, arg_set := d.GetOk("ipcidr") + if arg_set { + url_values.Add("ipcidr", ipcidr.(string)) + } + + ext_net_id, arg_set := d.GetOk("ext_net_id") + if arg_set { + url_values.Add("extNetId", fmt.Sprintf("%d", ext_net_id.(int))) + } + + ext_ip, arg_set := d.GetOk("ext_ip") + if arg_set { + url_values.Add("extIp", ext_ip.(string)) + } + + api_resp, err := c.DecortAPICall(ctx, "POST", ResgroupCreateAPI, url_values) + if err != nil { + return diag.FromErr(err) + } + + d.SetId(api_resp) // rg/create API returns ID of the newly creted resource group on success + // rg.ID, _ = strconv.Atoi(api_resp) + if !set_quota { + resp, err := utilityResgroupCheckPresence(ctx, d, m) + if err != nil { + return diag.FromErr(err) + } + + rg := ResgroupGetResp{} + if err := json.Unmarshal([]byte(resp), &rg); err != nil { + return diag.FromErr(err) + } + + d.Set("quota", parseQuota(rg.Quota)) + } + + // re-read newly created RG to make sure schema contains complete and up to date set of specifications + return resourceResgroupRead(ctx, d, m) +} + +func resourceResgroupRead(ctx context.Context, d *schema.ResourceData, m interface{}) diag.Diagnostics { + log.Debugf("resourceResgroupRead: called for RG name %s, account ID %d", + d.Get("name").(string), d.Get("account_id").(int)) + + rg_facts, err := utilityResgroupCheckPresence(ctx, d, m) + if rg_facts == "" { + // if empty string is returned from utilityResgroupCheckPresence then there is no + // such resource group and err tells so - just return it to the calling party + d.SetId("") // ensure ID is empty + return diag.FromErr(err) + } + + return diag.FromErr(flattenResgroup(d, rg_facts)) +} + +func resourceResgroupUpdate(ctx context.Context, d *schema.ResourceData, m interface{}) diag.Diagnostics { + log.Debugf("resourceResgroupUpdate: called for RG name %s, account ID %d", + d.Get("name").(string), d.Get("account_id").(int)) + + /* NOTE: we do not allow changing the following attributes of an existing RG via terraform: + - def_net_type + - ipcidr + - ext_net_id + - ext_ip + + The following code fragment checks if any of these have been changed and generates error. + */ + for _, attr := range []string{"def_net_type", "ipcidr", "ext_ip"} { + attr_new, attr_old := d.GetChange("def_net_type") + if attr_new.(string) != attr_old.(string) { + return diag.FromErr(fmt.Errorf("resourceResgroupUpdate: RG ID %s: changing %s for existing RG is not allowed", d.Id(), attr)) + } + } + + attr_new, attr_old := d.GetChange("ext_net_id") + if attr_new.(int) != attr_old.(int) { + return diag.FromErr(fmt.Errorf("resourceResgroupUpdate: RG ID %s: changing ext_net_id for existing RG is not allowed", d.Id())) + } + + do_general_update := false // will be true if general RG update is necessary (API rg/update) + + c := m.(*controller.ControllerCfg) + url_values := &url.Values{} + url_values.Add("rgId", d.Id()) + + name_new, name_set := d.GetOk("name") + if name_set { + log.Debugf("resourceResgroupUpdate: name specified - looking for deltas from the old settings.") + name_old, _ := d.GetChange("name") + if name_old.(string) != name_new.(string) { + do_general_update = true + url_values.Add("name", name_new.(string)) + } + } + + quota_value, quota_set := d.GetOk("quota") + if quota_set { + log.Debugf("resourceResgroupUpdate: quota specified - looking for deltas from the old quota.") + quotarecord_new := makeQuotaRecord(quota_value.([]interface{})) + quota_value_old, _ := d.GetChange("quota") // returns old as 1st, new as 2nd return value + quotarecord_old := makeQuotaRecord(quota_value_old.([]interface{})) + + if quotarecord_new.Cpu != quotarecord_old.Cpu { + do_general_update = true + log.Debugf("resourceResgroupUpdate: Cpu diff %d <- %d", quotarecord_new.Cpu, quotarecord_old.Cpu) + url_values.Add("maxCPUCapacity", fmt.Sprintf("%d", quotarecord_new.Cpu)) + } + + if quotarecord_new.Disk != quotarecord_old.Disk { + do_general_update = true + log.Debugf("resourceResgroupUpdate: Disk diff %d <- %d", quotarecord_new.Disk, quotarecord_old.Disk) + url_values.Add("maxVDiskCapacity", fmt.Sprintf("%d", quotarecord_new.Disk)) + } + + if quotarecord_new.Ram != quotarecord_old.Ram { // NB: quota on RAM is stored as float32, in units of MB + do_general_update = true + log.Debugf("resourceResgroupUpdate: Ram diff %f <- %f", quotarecord_new.Ram, quotarecord_old.Ram) + url_values.Add("maxMemoryCapacity", fmt.Sprintf("%f", quotarecord_new.Ram)) + } + + if quotarecord_new.ExtTraffic != quotarecord_old.ExtTraffic { + do_general_update = true + log.Debugf("resourceResgroupUpdate: ExtTraffic diff %d <- %d", quotarecord_new.ExtTraffic, quotarecord_old.ExtTraffic) + url_values.Add("maxNetworkPeerTransfer", fmt.Sprintf("%d", quotarecord_new.ExtTraffic)) + } + + if quotarecord_new.ExtIPs != quotarecord_old.ExtIPs { + do_general_update = true + log.Debugf("resourceResgroupUpdate: ExtIPs diff %d <- %d", quotarecord_new.ExtIPs, quotarecord_old.ExtIPs) + url_values.Add("maxNumPublicIP", fmt.Sprintf("%d", quotarecord_new.ExtIPs)) + } + } + + desc_new, desc_set := d.GetOk("description") + if desc_set { + log.Debugf("resourceResgroupUpdate: description specified - looking for deltas from the old settings.") + desc_old, _ := d.GetChange("description") + if desc_old.(string) != desc_new.(string) { + do_general_update = true + url_values.Add("desc", desc_new.(string)) + } + } + + if do_general_update { + log.Debugf("resourceResgroupUpdate: detected delta between new and old RG specs - updating the RG") + _, err := c.DecortAPICall(ctx, "POST", ResgroupUpdateAPI, url_values) + if err != nil { + return diag.FromErr(err) + } + } else { + log.Debugf("resourceResgroupUpdate: no difference between old and new state - no update on the RG will be done") + } + + return resourceResgroupRead(ctx, d, m) +} + +func resourceResgroupDelete(ctx context.Context, d *schema.ResourceData, m interface{}) diag.Diagnostics { + // NOTE: this method forcibly destroys target resource group with flag "permanently", so there is no way to + // restore the destroyed resource group as well all Computes & VINSes that existed in it + log.Debugf("resourceResgroupDelete: called for RG name %s, account ID %d", + d.Get("name").(string), d.Get("account_id").(int)) + + rg_facts, err := utilityResgroupCheckPresence(ctx, d, m) + if rg_facts == "" { + if err != nil { + return diag.FromErr(err) + } + // the target RG does not exist - in this case according to Terraform best practice + // we exit from Destroy method without error + return nil + } + + url_values := &url.Values{} + url_values.Add("rgId", d.Id()) + url_values.Add("force", "1") + url_values.Add("permanently", "1") + url_values.Add("reason", "Destroyed by DECORT Terraform provider") + + c := m.(*controller.ControllerCfg) + _, err = c.DecortAPICall(ctx, "POST", ResgroupDeleteAPI, url_values) + if err != nil { + return diag.FromErr(err) + } + + return nil +} + +func resourceResgroupExists(ctx context.Context, d *schema.ResourceData, m interface{}) (bool, error) { + // Reminder: according to Terraform rules, this function should NOT modify ResourceData argument + rg_facts, err := utilityResgroupCheckPresence(ctx, d, m) + if rg_facts == "" { + if err != nil { + return false, err + } + return false, nil + } + return true, nil +} + +func ResourceResgroup() *schema.Resource { + return &schema.Resource{ + SchemaVersion: 1, + + CreateContext: resourceResgroupCreate, + ReadContext: resourceResgroupRead, + UpdateContext: resourceResgroupUpdate, + DeleteContext: resourceResgroupDelete, + + Importer: &schema.ResourceImporter{ + State: schema.ImportStatePassthrough, + }, + + Timeouts: &schema.ResourceTimeout{ + Create: &constants.Timeout180s, + Read: &constants.Timeout30s, + Update: &constants.Timeout180s, + Delete: &constants.Timeout60s, + Default: &constants.Timeout60s, + }, + + Schema: map[string]*schema.Schema{ + "name": { + Type: schema.TypeString, + Required: true, + Description: "Name of this resource group. Names are case sensitive and unique within the context of a account.", + }, + + "account_id": { + Type: schema.TypeInt, + Required: true, + ValidateFunc: validation.IntAtLeast(1), + Description: "Unique ID of the account, which this resource group belongs to.", + }, + + "def_net_type": { + Type: schema.TypeString, + Optional: true, + Default: "PRIVATE", + ValidateFunc: validation.StringInSlice([]string{"PRIVATE", "PUBLIC", "NONE"}, false), + Description: "Type of the network, which this resource group will use as default for its computes - PRIVATE or PUBLIC or NONE.", + }, + + "def_net_id": { + Type: schema.TypeInt, + Computed: true, + Description: "ID of the default network for this resource group (if any).", + }, + + "ipcidr": { + Type: schema.TypeString, + Optional: true, + Description: "Address of the netowrk inside the private network segment (aka ViNS) if def_net_type=PRIVATE", + }, + + "ext_net_id": { + Type: schema.TypeInt, + Optional: true, + Default: 0, + Description: "ID of the external network for default ViNS. Pass 0 if def_net_type=PUBLIC or no external connection required for the defult ViNS when def_net_type=PRIVATE", + }, + + "ext_ip": { + Type: schema.TypeString, + Optional: true, + Description: "IP address on the external netowrk to request when def_net_type=PRIVATE and ext_net_id is not 0", + }, + + /* commented out, as in this version of provider we use default Grid ID + "grid_id": { + Type: schema.TypeInt, + Optional: true, + Default: 0, // if 0 is passed, default Grid ID will be used + // DefaultFunc: utilityResgroupGetDefaultGridID, + ForceNew: true, // change of Grid ID will require new RG + Description: "Unique ID of the grid, where this resource group is deployed.", + }, + */ + + "quota": { + Type: schema.TypeList, + Optional: true, + Computed: true, + MaxItems: 1, + Elem: &schema.Resource{ + Schema: quotaRgSubresourceSchemaMake(), + }, + Description: "Quota settings for this resource group.", + }, + + "description": { + Type: schema.TypeString, + Optional: true, + Description: "User-defined text description of this resource group.", + }, + + "account_name": { + Type: schema.TypeString, + Computed: true, + Description: "Name of the account, which this resource group belongs to.", + }, + + /* + "status": { + Type: schema.TypeString, + Computed: true, + Description: "Current status of this resource group.", + }, + + "vins": { + Type: schema.TypeList, // this is a list of ints + Computed: true, + MaxItems: LimitMaxVinsPerResgroup, + Elem: &schema.Schema{ + Type: schema.TypeInt, + }, + Description: "List of VINs deployed in this resource group.", + }, + + "computes": { + Type: schema.TypeList, // this is a list of ints + Computed: true, + Elem: &schema.Schema{ + Type: schema.TypeInt, + }, + Description: "List of computes deployed in this resource group.", + }, + */ + }, + } +} diff --git a/internal/service/cloudbroker/rg/utility_rg.go b/internal/service/cloudbroker/rg/utility_rg.go new file mode 100644 index 0000000..c7c3b94 --- /dev/null +++ b/internal/service/cloudbroker/rg/utility_rg.go @@ -0,0 +1,139 @@ +/* +Copyright (c) 2019-2022 Digital Energy Cloud Solutions LLC. All Rights Reserved. +Authors: +Petr Krutov, +Stanislav Solovev, + +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. +*/ + +/* +Terraform DECORT provider - manage resources provided by DECORT (Digital Energy Cloud +Orchestration Technology) with Terraform by Hashicorp. + +Source code: https://github.com/rudecs/terraform-provider-decort + +Please see README.md to learn where to place source code so that it +builds seamlessly. + +Documentation: https://github.com/rudecs/terraform-provider-decort/wiki +*/ + +package rg + +import ( + "context" + "encoding/json" + "fmt" + "net/url" + "strconv" + + "github.com/rudecs/terraform-provider-decort/internal/controller" + log "github.com/sirupsen/logrus" + + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" +) + +// On success this function returns a string, as returned by API rg/get, which could be unmarshalled +// into ResgroupGetResp structure +func utilityResgroupCheckPresence(ctx context.Context, d *schema.ResourceData, m interface{}) (string, error) { + // This function tries to locate resource group by one of the following algorithms depending + // on the parameters passed: + // - if resource group ID is specified -> by RG ID + // - if resource group name is specifeid -> by RG name and either account ID or account name + // + // If succeeded, it returns non empty string that contains JSON formatted facts about the + // resource group as returned by rg/get API call. + // Otherwise it returns empty string and a meaningful error. + // + // NOTE: As our provider always deletes RGs permanently, there is no "restore" method and + // consequently we are not interested in matching RGs in DELETED state. Hence, we call + // .../rg/list API with includedeleted=false + // + // This function does not modify its ResourceData argument, so it is safe to use it as core + // method for the Terraform resource Exists method. + // + + c := m.(*controller.ControllerCfg) + urlValues := &url.Values{} + + // make it possible to use "read" & "check presence" functions with RG ID set so + // that Import of RG resource is possible + idSet := false + theId, err := strconv.Atoi(d.Id()) + if err != nil || theId <= 0 { + rgId, argSet := d.GetOk("rg_id") + if argSet { + theId = rgId.(int) + idSet = true + } + } else { + idSet = true + } + + if idSet { + // go straight for the RG by its ID + log.Debugf("utilityResgroupCheckPresence: locating RG by its ID %d", theId) + urlValues.Add("rgId", fmt.Sprintf("%d", theId)) + rgFacts, err := c.DecortAPICall(ctx, "POST", ResgroupGetAPI, urlValues) + if err != nil { + return "", err + } + return rgFacts, nil + } + + rgName, argSet := d.GetOk("name") + if !argSet { + // no RG ID and no RG name - we cannot locate resource group in this case + return "", fmt.Errorf("Cannot check resource group presence if name is empty and no resource group ID specified") + } + + // Valid account ID is required to locate a resource group + // obtain Account ID by account name - it should not be zero on success + + urlValues.Add("includedeleted", "false") + apiResp, err := c.DecortAPICall(ctx, "POST", ResgroupListAPI, urlValues) + if err != nil { + return "", err + } + // log.Debugf("%s", apiResp) + log.Debugf("utilityResgroupCheckPresence: ready to decode response body from %s", ResgroupListAPI) + model := ResgroupListResp{} + err = json.Unmarshal([]byte(apiResp), &model) + if err != nil { + return "", err + } + + log.Debugf("utilityResgroupCheckPresence: traversing decoded Json of length %d", len(model)) + for index, item := range model { + // match by RG name & account ID + if item.Name == rgName.(string) && item.AccountID == d.Get("account_id").(int) { + log.Debugf("utilityResgroupCheckPresence: match RG name %s / ID %d, account ID %d at index %d", + item.Name, item.ID, item.AccountID, index) + + // not all required information is returned by rg/list API, so we need to initiate one more + // call to rg/get to obtain extra data to complete Resource population. + // Namely, we need resource quota settings + reqValues := &url.Values{} + reqValues.Add("rgId", fmt.Sprintf("%d", item.ID)) + apiResp, err := c.DecortAPICall(ctx, "POST", ResgroupGetAPI, reqValues) + if err != nil { + return "", err + } + + return apiResp, nil + } + } + + return "", fmt.Errorf("Cannot find RG name %s owned by account ID %d", rgName, d.Get("account_id").(int)) +} diff --git a/internal/service/cloudbroker/rg/utility_rg_list.go b/internal/service/cloudbroker/rg/utility_rg_list.go new file mode 100644 index 0000000..3342105 --- /dev/null +++ b/internal/service/cloudbroker/rg/utility_rg_list.go @@ -0,0 +1,74 @@ +/* +Copyright (c) 2019-2022 Digital Energy Cloud Solutions LLC. All Rights Reserved. +Authors: +Petr Krutov, +Stanislav Solovev, + +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. +*/ + +/* +Terraform DECORT provider - manage resources provided by DECORT (Digital Energy Cloud +Orchestration Technology) with Terraform by Hashicorp. + +Source code: https://github.com/rudecs/terraform-provider-decort + +Please see README.md to learn where to place source code so that it +builds seamlessly. + +Documentation: https://github.com/rudecs/terraform-provider-decort/wiki +*/ + +package rg + +import ( + "context" + "encoding/json" + "net/url" + "strconv" + + "github.com/rudecs/terraform-provider-decort/internal/controller" + log "github.com/sirupsen/logrus" + + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" +) + +func utilityRgListCheckPresence(ctx context.Context, d *schema.ResourceData, m interface{}) (ResgroupListResp, error) { + c := m.(*controller.ControllerCfg) + urlValues := &url.Values{} + + rgList := ResgroupListResp{} + + if size, ok := d.GetOk("size"); ok { + urlValues.Add("size", strconv.Itoa(size.(int))) + } + if page, ok := d.GetOk("page"); ok { + urlValues.Add("page", strconv.Itoa(page.(int))) + } + if includedeleted, ok := d.GetOk("includedeleted"); ok { + urlValues.Add("includedeleted", strconv.FormatBool(includedeleted.(bool))) + } + + log.Debugf("utilityRgListCheckPresence: load rg list") + rgListRaw, err := c.DecortAPICall(ctx, "POST", ResgroupListAPI, urlValues) + if err != nil { + return nil, err + } + + err = json.Unmarshal([]byte(rgListRaw), &rgList) + if err != nil { + return nil, err + } + + return rgList, nil +} diff --git a/internal/service/cloudbroker/sep/resource_sep.go b/internal/service/cloudbroker/sep/resource_sep.go index 25b54cf..f6561f7 100644 --- a/internal/service/cloudbroker/sep/resource_sep.go +++ b/internal/service/cloudbroker/sep/resource_sep.go @@ -38,7 +38,6 @@ import ( "net/url" "strconv" - "github.com/google/uuid" "github.com/hashicorp/terraform-plugin-sdk/v2/diag" "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" "github.com/rudecs/terraform-provider-decort/internal/constants" @@ -50,22 +49,6 @@ import ( func resourceSepCreate(ctx context.Context, d *schema.ResourceData, m interface{}) diag.Diagnostics { log.Debugf("resourceSepCreate: called for sep %s", d.Get("name").(string)) - if sepId, ok := d.GetOk("sep_id"); ok { - if exists, err := resourceSepExists(ctx, d, m); exists { - if err != nil { - return diag.FromErr(err) - } - d.SetId(strconv.Itoa(sepId.(int))) - diagnostics := resourceSepRead(ctx, d, m) - if diagnostics != nil { - return diagnostics - } - - return nil - } - return diag.Errorf("provided sep id does not exist") - } - c := m.(*controller.ControllerCfg) urlValues := &url.Values{} @@ -114,7 +97,6 @@ func resourceSepCreate(ctx context.Context, d *schema.ResourceData, m interface{ return diag.FromErr(err) } - id := uuid.New() d.SetId(sepId) d.Set("sep_id", sepId) @@ -123,8 +105,6 @@ func resourceSepCreate(ctx context.Context, d *schema.ResourceData, m interface{ return diagnostics } - d.SetId(id.String()) - return nil } diff --git a/internal/service/cloudbroker/snapshot/api.go b/internal/service/cloudbroker/snapshot/api.go new file mode 100644 index 0000000..a974cca --- /dev/null +++ b/internal/service/cloudbroker/snapshot/api.go @@ -0,0 +1,37 @@ +/* +Copyright (c) 2019-2022 Digital Energy Cloud Solutions LLC. All Rights Reserved. +Authors: +Petr Krutov, +Stanislav Solovev, + +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. +*/ + +/* +Terraform DECORT provider - manage resources provided by DECORT (Digital Energy Cloud +Orchestration Technology) with Terraform by Hashicorp. + +Source code: https://github.com/rudecs/terraform-provider-decort + +Please see README.md to learn where to place source code so that it +builds seamlessly. + +Documentation: https://github.com/rudecs/terraform-provider-decort/wiki +*/ + +package snapshot + +const snapshotCreateAPI = "/restmachine/cloudbroker/compute/snapshotCreate" +const snapshotDeleteAPI = "/restmachine/cloudbroker/compute/snapshotDelete" +const snapshotRollbackAPI = "/restmachine/cloudbroker/compute/snapshotRollback" +const snapshotListAPI = "/restmachine/cloudbroker/compute/snapshotList" diff --git a/internal/service/cloudbroker/snapshot/data_source_snapshot_list.go b/internal/service/cloudbroker/snapshot/data_source_snapshot_list.go new file mode 100644 index 0000000..0fe01c1 --- /dev/null +++ b/internal/service/cloudbroker/snapshot/data_source_snapshot_list.go @@ -0,0 +1,131 @@ +/* +Copyright (c) 2019-2022 Digital Energy Cloud Solutions LLC. All Rights Reserved. +Authors: +Petr Krutov, +Stanislav Solovev, + +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. +*/ + +/* +Terraform DECORT provider - manage resources provided by DECORT (Digital Energy Cloud +Orchestration Technology) with Terraform by Hashicorp. + +Source code: https://github.com/rudecs/terraform-provider-decort + +Please see README.md to learn where to place source code so that it +builds seamlessly. + +Documentation: https://github.com/rudecs/terraform-provider-decort/wiki +*/ + +package snapshot + +import ( + "context" + + "github.com/google/uuid" + "github.com/hashicorp/terraform-plugin-sdk/v2/diag" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" + "github.com/rudecs/terraform-provider-decort/internal/constants" +) + +func flattenSnapshotList(gl SnapshotList) []map[string]interface{} { + res := make([]map[string]interface{}, 0) + for _, item := range gl { + temp := map[string]interface{}{ + "label": item.Label, + "guid": item.Guid, + "disks": item.Disks, + "timestamp": item.Timestamp, + } + + res = append(res, temp) + } + return res +} + +func dataSourceSnapshotListRead(ctx context.Context, d *schema.ResourceData, m interface{}) diag.Diagnostics { + snapshotList, err := utilitySnapshotListCheckPresence(ctx, d, m) + if err != nil { + return diag.FromErr(err) + } + id := uuid.New() + d.SetId(id.String()) + d.Set("items", flattenSnapshotList(snapshotList)) + + return nil +} + +func dataSourceSnapshotListSchemaMake() map[string]*schema.Schema { + rets := map[string]*schema.Schema{ + "compute_id": { + Type: schema.TypeInt, + Required: true, + ForceNew: true, + Description: "ID of the compute instance to create snapshot for.", + }, + "items": { + Type: schema.TypeList, + Computed: true, + Description: "snapshot list", + Elem: &schema.Resource{ + Schema: dataSourceSnapshotSchemaMake(), + }, + }, + } + + return rets +} + +func dataSourceSnapshotSchemaMake() map[string]*schema.Schema { + return map[string]*schema.Schema{ + "label": { + Type: schema.TypeString, + Computed: true, + Description: "text label for snapshot. Must be unique among this compute snapshots.", + }, + "disks": { + Type: schema.TypeList, + Computed: true, + Elem: &schema.Schema{ + Type: schema.TypeInt, + }, + }, + "guid": { + Type: schema.TypeString, + Computed: true, + Description: "guid of the snapshot", + }, + "timestamp": { + Type: schema.TypeInt, + Computed: true, + Description: "timestamp", + }, + } +} + +func DataSourceSnapshotList() *schema.Resource { + return &schema.Resource{ + SchemaVersion: 1, + + ReadContext: dataSourceSnapshotListRead, + + Timeouts: &schema.ResourceTimeout{ + Read: &constants.Timeout30s, + Default: &constants.Timeout60s, + }, + + Schema: dataSourceSnapshotListSchemaMake(), + } +} diff --git a/internal/service/cloudbroker/snapshot/models.go b/internal/service/cloudbroker/snapshot/models.go new file mode 100644 index 0000000..0152191 --- /dev/null +++ b/internal/service/cloudbroker/snapshot/models.go @@ -0,0 +1,41 @@ +/* +Copyright (c) 2019-2022 Digital Energy Cloud Solutions LLC. All Rights Reserved. +Authors: +Petr Krutov, +Stanislav Solovev, + +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. +*/ + +/* +Terraform DECORT provider - manage resources provided by DECORT (Digital Energy Cloud +Orchestration Technology) with Terraform by Hashicorp. + +Source code: https://github.com/rudecs/terraform-provider-decort + +Please see README.md to learn where to place source code so that it +builds seamlessly. + +Documentation: https://github.com/rudecs/terraform-provider-decort/wiki +*/ + +package snapshot + +type Snapshot struct { + Disks []int `json:"disks"` + Guid string `json:"guid"` + Label string `json:"label"` + Timestamp uint64 `json:"timestamp"` +} + +type SnapshotList []Snapshot diff --git a/internal/service/cloudbroker/snapshot/resource_snapshot.go b/internal/service/cloudbroker/snapshot/resource_snapshot.go new file mode 100644 index 0000000..9a8fbc7 --- /dev/null +++ b/internal/service/cloudbroker/snapshot/resource_snapshot.go @@ -0,0 +1,206 @@ +/* +Copyright (c) 2019-2022 Digital Energy Cloud Solutions LLC. All Rights Reserved. +Authors: +Petr Krutov, +Stanislav Solovev, + +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. +*/ + +/* +Terraform DECORT provider - manage resources provided by DECORT (Digital Energy Cloud +Orchestration Technology) with Terraform by Hashicorp. + +Source code: https://github.com/rudecs/terraform-provider-decort + +Please see README.md to learn where to place source code so that it +builds seamlessly. + +Documentation: https://github.com/rudecs/terraform-provider-decort/wiki +*/ + +package snapshot + +import ( + "context" + "net/url" + "strconv" + "strings" + + "github.com/hashicorp/terraform-plugin-sdk/v2/diag" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" + "github.com/rudecs/terraform-provider-decort/internal/constants" + "github.com/rudecs/terraform-provider-decort/internal/controller" + log "github.com/sirupsen/logrus" +) + +func resourceSnapshotCreate(ctx context.Context, d *schema.ResourceData, m interface{}) diag.Diagnostics { + log.Debugf("resourceSnapshotCreate: called for snapshot %s", d.Get("label").(string)) + + c := m.(*controller.ControllerCfg) + urlValues := &url.Values{} + urlValues.Add("label", d.Get("label").(string)) + urlValues.Add("computeId", strconv.Itoa(d.Get("compute_id").(int))) + + snapshotId, err := c.DecortAPICall(ctx, "POST", snapshotCreateAPI, urlValues) + if err != nil { + return diag.FromErr(err) + } + + snapshotId = strings.ReplaceAll(snapshotId, "\"", "") + + d.SetId(snapshotId) + d.Set("guid", snapshotId) + + diagnostics := resourceSnapshotRead(ctx, d, m) + if diagnostics != nil { + return diagnostics + } + + return nil +} + +func resourceSnapshotRead(ctx context.Context, d *schema.ResourceData, m interface{}) diag.Diagnostics { + snapshot, err := utilitySnapshotCheckPresence(ctx, d, m) + if err != nil { + return diag.FromErr(err) + } + + d.Set("timestamp", snapshot.Timestamp) + d.Set("guid", snapshot.Guid) + d.Set("disks", snapshot.Disks) + d.Set("label", snapshot.Label) + + return nil +} + +func resourceSnapshotDelete(ctx context.Context, d *schema.ResourceData, m interface{}) diag.Diagnostics { + log.Debugf("resourceSnapshotDelete: called for %s, id: %s", d.Get("label").(string), d.Id()) + + c := m.(*controller.ControllerCfg) + urlValues := &url.Values{} + urlValues.Add("computeId", strconv.Itoa(d.Get("compute_id").(int))) + urlValues.Add("label", d.Get("label").(string)) + + _, err := c.DecortAPICall(ctx, "POST", snapshotDeleteAPI, urlValues) + if err != nil { + return diag.FromErr(err) + } + d.SetId("") + + return nil +} + +func resourceSnapshotExists(ctx context.Context, d *schema.ResourceData, m interface{}) (bool, error) { + snapshot, err := utilitySnapshotCheckPresence(ctx, d, m) + if err != nil { + return false, err + } + if snapshot == nil { + return false, nil + } + + return true, nil +} + +func resourceSnapshotEdit(ctx context.Context, d *schema.ResourceData, m interface{}) diag.Diagnostics { + if d.HasChange("rollback") { + if d.Get("rollback").(bool) { + err := resourceSnapshotRollback(ctx, d, m) + if err != nil { + return diag.FromErr(err) + } + } + } + + return nil +} + +func resourceSnapshotRollback(ctx context.Context, d *schema.ResourceData, m interface{}) error { + c := m.(*controller.ControllerCfg) + urlValues := &url.Values{} + + urlValues.Add("computeId", strconv.Itoa(d.Get("compute_id").(int))) + urlValues.Add("label", d.Get("label").(string)) + + _, err := c.DecortAPICall(ctx, "POST", snapshotRollbackAPI, urlValues) + if err != nil { + return err + } + return nil +} + +func resourceSnapshotSchemaMake() map[string]*schema.Schema { + return map[string]*schema.Schema{ + "compute_id": { + Type: schema.TypeInt, + Required: true, + ForceNew: true, + Description: "ID of the compute instance to create snapshot for.", + }, + "label": { + Type: schema.TypeString, + Required: true, + ForceNew: true, + Description: "text label for snapshot. Must be unique among this compute snapshots.", + }, + "rollback": { + Type: schema.TypeBool, + Optional: true, + Default: false, + Description: "is rollback the snapshot", + }, + "disks": { + Type: schema.TypeList, + Computed: true, + Elem: &schema.Schema{ + Type: schema.TypeInt, + }, + }, + "guid": { + Type: schema.TypeString, + Computed: true, + Description: "guid of the snapshot", + }, + "timestamp": { + Type: schema.TypeInt, + Computed: true, + Description: "timestamp", + }, + } +} + +func ResourceSnapshot() *schema.Resource { + return &schema.Resource{ + SchemaVersion: 1, + + CreateContext: resourceSnapshotCreate, + ReadContext: resourceSnapshotRead, + UpdateContext: resourceSnapshotEdit, + DeleteContext: resourceSnapshotDelete, + + Importer: &schema.ResourceImporter{ + State: schema.ImportStatePassthrough, + }, + + Timeouts: &schema.ResourceTimeout{ + Create: &constants.Timeout60s, + Read: &constants.Timeout30s, + Update: &constants.Timeout60s, + Delete: &constants.Timeout60s, + Default: &constants.Timeout60s, + }, + + Schema: resourceSnapshotSchemaMake(), + } +} diff --git a/internal/service/cloudbroker/snapshot/utility_snapshot.go b/internal/service/cloudbroker/snapshot/utility_snapshot.go new file mode 100644 index 0000000..b99509b --- /dev/null +++ b/internal/service/cloudbroker/snapshot/utility_snapshot.go @@ -0,0 +1,63 @@ +/* +Copyright (c) 2019-2022 Digital Energy Cloud Solutions LLC. All Rights Reserved. +Authors: +Petr Krutov, +Stanislav Solovev, + +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. +*/ + +/* +Terraform DECORT provider - manage resources provided by DECORT (Digital Energy Cloud +Orchestration Technology) with Terraform by Hashicorp. + +Source code: https://github.com/rudecs/terraform-provider-decort + +Please see README.md to learn where to place source code so that it +builds seamlessly. + +Documentation: https://github.com/rudecs/terraform-provider-decort/wiki +*/ + +package snapshot + +import ( + "context" + "errors" + + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" +) + +func utilitySnapshotCheckPresence(ctx context.Context, d *schema.ResourceData, m interface{}) (*Snapshot, error) { + snapShotList, err := utilitySnapshotListCheckPresence(ctx, d, m) + if err != nil { + return nil, err + } + + findId := "" + + if (d.Get("guid").(string)) != "" { + findId = d.Get("guid").(string) + } else { + findId = d.Id() + } + + for _, s := range snapShotList { + if s.Guid == findId { + return &s, nil + } + } + + return nil, errors.New("snapshot not found") + +} diff --git a/internal/service/cloudbroker/snapshot/utility_snapshot_list.go b/internal/service/cloudbroker/snapshot/utility_snapshot_list.go new file mode 100644 index 0000000..e06ac5b --- /dev/null +++ b/internal/service/cloudbroker/snapshot/utility_snapshot_list.go @@ -0,0 +1,65 @@ +/* +Copyright (c) 2019-2022 Digital Energy Cloud Solutions LLC. All Rights Reserved. +Authors: +Petr Krutov, +Stanislav Solovev, + +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. +*/ + +/* +Terraform DECORT provider - manage resources provided by DECORT (Digital Energy Cloud +Orchestration Technology) with Terraform by Hashicorp. + +Source code: https://github.com/rudecs/terraform-provider-decort + +Please see README.md to learn where to place source code so that it +builds seamlessly. + +Documentation: https://github.com/rudecs/terraform-provider-decort/wiki +*/ + +package snapshot + +import ( + "context" + "encoding/json" + "net/url" + "strconv" + + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" + "github.com/rudecs/terraform-provider-decort/internal/controller" +) + +func utilitySnapshotListCheckPresence(ctx context.Context, d *schema.ResourceData, m interface{}) (SnapshotList, error) { + c := m.(*controller.ControllerCfg) + urlValues := &url.Values{} + urlValues.Add("computeId", strconv.Itoa(d.Get("compute_id").(int))) + + resp, err := c.DecortAPICall(ctx, "POST", snapshotListAPI, urlValues) + if err != nil { + return nil, err + } + + if resp == "" { + return nil, nil + } + + snapshotList := SnapshotList{} + if err := json.Unmarshal([]byte(resp), &snapshotList); err != nil { + + return nil, err + } + + return snapshotList, nil +} diff --git a/internal/service/cloudbroker/vins/api.go b/internal/service/cloudbroker/vins/api.go new file mode 100644 index 0000000..bfdefe4 --- /dev/null +++ b/internal/service/cloudbroker/vins/api.go @@ -0,0 +1,44 @@ +/* +Copyright (c) 2019-2022 Digital Energy Cloud Solutions LLC. All Rights Reserved. +Authors: +Petr Krutov, +Stanislav Solovev, + +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. +*/ + +/* +Terraform DECORT provider - manage resources provided by DECORT (Digital Energy Cloud +Orchestration Technology) with Terraform by Hashicorp. + +Source code: https://github.com/rudecs/terraform-provider-decort + +Please see README.md to learn where to place source code so that it +builds seamlessly. + +Documentation: https://github.com/rudecs/terraform-provider-decort/wiki +*/ + +package vins + +const VinsListAPI = "/restmachine/cloudbroker/vins/list" +const VinsGetAPI = "/restmachine/cloudbroker/vins/get" +const VinsSearchAPI = "/restmachine/cloudbroker/vins/search" + +const VinsCreateInAccountAPI = "/restmachine/cloudbroker/vins/createInAccount" +const VinsCreateInRgAPI = "/restmachine/cloudbroker/vins/createInRG" + +const VinsExtNetConnectAPI = "/restmachine/cloudbroker/vins/extNetConnect" +const VinsExtNetDisconnectAPI = "/restmachine/cloudbroker/vins/extNetDisconnect" + +const VinsDeleteAPI = "/restmachine/cloudbroker/vins/delete" diff --git a/internal/service/cloudbroker/vins/data_source_vins.go b/internal/service/cloudbroker/vins/data_source_vins.go new file mode 100644 index 0000000..2bcd362 --- /dev/null +++ b/internal/service/cloudbroker/vins/data_source_vins.go @@ -0,0 +1,181 @@ +/* +Copyright (c) 2019-2022 Digital Energy Cloud Solutions LLC. All Rights Reserved. +Authors: +Petr Krutov, +Stanislav Solovev, + +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. +*/ + +/* +Terraform DECORT provider - manage resources provided by DECORT (Digital Energy Cloud +Orchestration Technology) with Terraform by Hashicorp. + +Source code: https://github.com/rudecs/terraform-provider-decort + +Please see README.md to learn where to place source code so that it +builds seamlessly. + +Documentation: https://github.com/rudecs/terraform-provider-decort/wiki +*/ + +package vins + +import ( + "context" + "encoding/json" + "fmt" + + "github.com/rudecs/terraform-provider-decort/internal/constants" + log "github.com/sirupsen/logrus" + + // "net/url" + + "github.com/hashicorp/terraform-plugin-sdk/v2/diag" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" + // "github.com/hashicorp/terraform-plugin-sdk/helper/validation" +) + +// vins_facts is a response string from API vins/get +func flattenVins(d *schema.ResourceData, vins_facts string) diag.Diagnostics { + // NOTE: this function modifies ResourceData argument - as such it should never be called + // from resourceVinsExists(...) method + // log.Debugf("flattenVins: ready to decode response body from API %s", vins_facts) + vinsRecord := VinsRecord{} + err := json.Unmarshal([]byte(vins_facts), &vinsRecord) + if err != nil { + return diag.FromErr(err) + } + + log.Debugf("flattenVins: decoded ViNS name:ID %s:%d, account ID %d, RG ID %d", + vinsRecord.Name, vinsRecord.ID, vinsRecord.AccountID, vinsRecord.RgID) + + d.SetId(fmt.Sprintf("%d", vinsRecord.ID)) + d.Set("name", vinsRecord.Name) + d.Set("account_id", vinsRecord.AccountID) + d.Set("account_name", vinsRecord.AccountName) + d.Set("rg_id", vinsRecord.RgID) + d.Set("description", vinsRecord.Desc) + d.Set("ipcidr", vinsRecord.IPCidr) + + noExtNetConnection := true + for _, value := range vinsRecord.VNFs { + if value.Type == "GW" { + log.Debugf("flattenVins: discovered GW VNF ID %d in ViNS ID %d", value.ID, vinsRecord.ID) + extNetID, idOk := value.Config["ext_net_id"] // NOTE: unknown numbers are unmarshalled to float64. This is by design! + extNetIP, ipOk := value.Config["ext_net_ip"] + if idOk && ipOk { + log.Debugf("flattenVins: ViNS ext_net_id=%d, ext_net_ip=%s", int(extNetID.(float64)), extNetIP.(string)) + d.Set("ext_ip_addr", extNetIP.(string)) + d.Set("ext_net_id", int(extNetID.(float64))) + } else { + return diag.Errorf("Failed to unmarshal VNF GW Config - structure is invalid.") + } + noExtNetConnection = false + break + } + } + + if noExtNetConnection { + d.Set("ext_ip_addr", "") + d.Set("ext_net_id", 0) + } + + log.Debugf("flattenVins: EXTRA CHECK - schema rg_id=%d, ext_net_id=%d", d.Get("rg_id").(int), d.Get("ext_net_id").(int)) + + return nil +} + +func dataSourceVinsRead(ctx context.Context, d *schema.ResourceData, m interface{}) diag.Diagnostics { + vinsFacts, err := utilityVinsCheckPresence(ctx, d, m) + if vinsFacts == "" { + // if empty string is returned from utilityVinsCheckPresence then there is no + // such ViNS and err tells so - just return it to the calling party + d.SetId("") // ensure ID is empty in this case + return diag.FromErr(err) + } + + return flattenVins(d, vinsFacts) +} + +func DataSourceVins() *schema.Resource { + return &schema.Resource{ + SchemaVersion: 1, + + ReadContext: dataSourceVinsRead, + + Timeouts: &schema.ResourceTimeout{ + Read: &constants.Timeout30s, + Default: &constants.Timeout60s, + }, + + Schema: map[string]*schema.Schema{ + "name": { + Type: schema.TypeString, + Required: true, + Description: "Name of the ViNS. Names are case sensitive and unique within the context of an account or resource group.", + }, + + /* + "vins_id": { + Type: schema.TypeInt, + Optional: true, + Description: "Unique ID of the ViNS. If ViNS ID is specified, then ViNS name, rg_id and account_id are ignored.", + }, + */ + + "rg_id": { + Type: schema.TypeInt, + Optional: true, + Description: "Unique ID of the resource group, where this ViNS is belongs to (for ViNS created at resource group level, 0 otherwise).", + }, + + "account_id": { + Type: schema.TypeInt, + Optional: true, + Description: "Unique ID of the account, which this ViNS belongs to.", + }, + + // the rest of attributes are computed + "account_name": { + Type: schema.TypeString, + Computed: true, + Description: "Name of the account, which this ViNS belongs to.", + }, + + "description": { + Type: schema.TypeString, + Computed: true, + Description: "User-defined text description of this ViNS.", + }, + + "ext_ip_addr": { + Type: schema.TypeString, + Computed: true, + Description: "IP address of the external connection (valid for ViNS connected to external network, empty string otherwise).", + }, + + "ext_net_id": { + Type: schema.TypeInt, + Computed: true, + Description: "ID of the external network this ViNS is connected to (-1 means no external connection).", + }, + + "ipcidr": { + Type: schema.TypeString, + Computed: true, + Description: "Network address used by this ViNS.", + }, + }, + } +} diff --git a/internal/service/cloudbroker/vins/data_source_vins_list.go b/internal/service/cloudbroker/vins/data_source_vins_list.go new file mode 100644 index 0000000..2178eb5 --- /dev/null +++ b/internal/service/cloudbroker/vins/data_source_vins_list.go @@ -0,0 +1,189 @@ +/* +Copyright (c) 2019-2022 Digital Energy Cloud Solutions LLC. All Rights Reserved. +Authors: +Petr Krutov, +Stanislav Solovev, + +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. +*/ + +/* +Terraform DECORT provider - manage resources provided by DECORT (Digital Energy Cloud +Orchestration Technology) with Terraform by Hashicorp. + +Source code: https://github.com/rudecs/terraform-provider-decort + +Please see README.md to learn where to place source code so that it +builds seamlessly. + +Documentation: https://github.com/rudecs/terraform-provider-decort/wiki +*/ + +package vins + +import ( + "context" + + "github.com/google/uuid" + "github.com/hashicorp/terraform-plugin-sdk/v2/diag" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" + "github.com/rudecs/terraform-provider-decort/internal/constants" +) + +func flattenVinsList(vl VinsList) []map[string]interface{} { + res := make([]map[string]interface{}, 0) + for _, v := range vl { + temp := map[string]interface{}{ + "account_id": v.AccountId, + "account_name": v.AccountName, + "created_by": v.CreatedBy, + "created_time": v.CreatedTime, + "deleted_by": v.DeletedBy, + "deleted_time": v.DeletedTime, + "external_ip": v.ExternalIP, + "vins_id": v.ID, + "vins_name": v.Name, + "network": v.Network, + "rg_id": v.RGID, + "rg_name": v.RGName, + "status": v.Status, + "updated_by": v.UpdatedBy, + "updated_time": v.UpdatedTime, + "vxlan_id": v.VXLanID, + } + res = append(res, temp) + } + return res +} + +func dataSourceVinsListRead(ctx context.Context, d *schema.ResourceData, m interface{}) diag.Diagnostics { + vinsList, err := utilityVinsListCheckPresence(ctx, d, m) + if err != nil { + return diag.FromErr(err) + } + + id := uuid.New() + d.SetId(id.String()) + d.Set("items", flattenVinsList(vinsList)) + + return nil +} + +func dataSourceVinsListSchemaMake() map[string]*schema.Schema { + res := map[string]*schema.Schema{ + "include_deleted": { + Type: schema.TypeBool, + Optional: true, + Default: false, + Description: "include deleted computes", + }, + "page": { + Type: schema.TypeInt, + Optional: true, + Description: "Page number", + }, + "size": { + Type: schema.TypeInt, + Optional: true, + Description: "Page size", + }, + "items": { + Type: schema.TypeList, + Computed: true, + Elem: &schema.Resource{ + Schema: map[string]*schema.Schema{ + "account_id": { + Type: schema.TypeInt, + Computed: true, + }, + "account_name": { + Type: schema.TypeString, + Computed: true, + }, + "created_by": { + Type: schema.TypeString, + Computed: true, + }, + "created_time": { + Type: schema.TypeInt, + Computed: true, + }, + "deleted_by": { + Type: schema.TypeString, + Computed: true, + }, + "deleted_time": { + Type: schema.TypeInt, + Computed: true, + }, + "external_ip": { + Type: schema.TypeString, + Computed: true, + }, + "vins_id": { + Type: schema.TypeInt, + Computed: true, + }, + "vins_name": { + Type: schema.TypeString, + Computed: true, + }, + "network": { + Type: schema.TypeString, + Computed: true, + }, + "rg_id": { + Type: schema.TypeInt, + Computed: true, + }, + "rg_name": { + Type: schema.TypeString, + Computed: true, + }, + "status": { + Type: schema.TypeString, + Computed: true, + }, + "updated_by": { + Type: schema.TypeString, + Computed: true, + }, + "updated_time": { + Type: schema.TypeInt, + Computed: true, + }, + "vxlan_id": { + Type: schema.TypeInt, + Computed: true, + }, + }, + }, + }, + } + return res +} + +func DataSourceVinsList() *schema.Resource { + return &schema.Resource{ + SchemaVersion: 1, + + ReadContext: dataSourceVinsListRead, + + Timeouts: &schema.ResourceTimeout{ + Read: &constants.Timeout30s, + Default: &constants.Timeout60s, + }, + + Schema: dataSourceVinsListSchemaMake(), + } +} diff --git a/internal/service/cloudbroker/vins/models.go b/internal/service/cloudbroker/vins/models.go new file mode 100644 index 0000000..e8b95d1 --- /dev/null +++ b/internal/service/cloudbroker/vins/models.go @@ -0,0 +1,94 @@ +/* +Copyright (c) 2019-2022 Digital Energy Cloud Solutions LLC. All Rights Reserved. +Authors: +Petr Krutov, +Stanislav Solovev, + +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. +*/ + +/* +Terraform DECORT provider - manage resources provided by DECORT (Digital Energy Cloud +Orchestration Technology) with Terraform by Hashicorp. + +Source code: https://github.com/rudecs/terraform-provider-decort + +Please see README.md to learn where to place source code so that it +builds seamlessly. + +Documentation: https://github.com/rudecs/terraform-provider-decort/wiki +*/ + +package vins + +type Vins struct { + AccountId int `json:"accountId"` + AccountName string `json:"accountName"` + CreatedBy string `json:"createdBy"` + CreatedTime int `json:"createdTime"` + DeletedBy string `json:"deletedBy"` + DeletedTime int `json:"deletedTime"` + ExternalIP string `json:"externalIP"` + ID int `json:"id"` + Name string `json:"name"` + Network string `json:"network"` + RGID int `json:"rgId"` + RGName string `json:"rgName"` + Status string `json:"status"` + UpdatedBy string `json:"updatedBy"` + UpdatedTime int `json:"updatedTime"` + VXLanID int `json:"vxlanId"` +} + +type VinsList []Vins + +type VinsSearchResp []VinsSearchRecord + +type VnfRecord struct { + ID int `json:"id"` + AccountID int `json:"accountId"` + Type string `json:"type"` // "DHCP", "NAT", "GW" etc + Config map[string]interface{} `json:"config"` // NOTE: VNF specs vary by VNF type +} + +type VnfGwConfigRecord struct { // describes GW VNF config structure inside ViNS, as returned by API vins/get + ExtNetID int `json:"ext_net_id"` + ExtNetIP string `json:"ext_net_ip"` + ExtNetMask int `json:"ext_net_mask"` + DefaultGW string `json:"default_gw"` +} +type VinsRecord struct { // represents part of the response from API vins/get + ID int `json:"id"` + Name string `json:"name"` + IPCidr string `json:"network"` + VxLanID int `json:"vxlanId"` + ExternalIP string `json:"externalIP"` + AccountID int `json:"accountId"` + AccountName string `json:"accountName"` + RgID int `json:"rgid"` + RgName string `json:"rgName"` + VNFs map[string]VnfRecord `json:"vnfs"` + Desc string `json:"desc"` +} + +type VinsSearchRecord struct { + ID int `json:"id"` + Name string `json:"name"` + IPCidr string `json:"network"` + VxLanID int `json:"vxlanId"` + ExternalIP string `json:"externalIP"` + AccountID int `json:"accountId"` + AccountName string `json:"accountName"` + RgID int `json:"rgId"` + RgName string `json:"rgName"` +} diff --git a/internal/service/cloudbroker/vins/resource_vins.go b/internal/service/cloudbroker/vins/resource_vins.go new file mode 100644 index 0000000..22729f6 --- /dev/null +++ b/internal/service/cloudbroker/vins/resource_vins.go @@ -0,0 +1,323 @@ +/* +Copyright (c) 2019-2022 Digital Energy Cloud Solutions LLC. All Rights Reserved. +Authors: +Petr Krutov, +Stanislav Solovev, + +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. +*/ + +/* +Terraform DECORT provider - manage resources provided by DECORT (Digital Energy Cloud +Orchestration Technology) with Terraform by Hashicorp. + +Source code: https://github.com/rudecs/terraform-provider-decort + +Please see README.md to learn where to place source code so that it +builds seamlessly. + +Documentation: https://github.com/rudecs/terraform-provider-decort/wiki +*/ + +package vins + +import ( + "context" + "fmt" + "net/url" + "strconv" + + "github.com/rudecs/terraform-provider-decort/internal/constants" + "github.com/rudecs/terraform-provider-decort/internal/controller" + log "github.com/sirupsen/logrus" + + "github.com/hashicorp/terraform-plugin-sdk/v2/diag" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/validation" +) + +func ipcidrDiffSupperss(key, oldVal, newVal string, d *schema.ResourceData) bool { + if oldVal == "" && newVal != "" { + // if old value for "ipcidr" resource is empty string, it means that we are creating new ViNS + // and there is a chance that the user will want specific IP address range for this ViNS - + // check if "ipcidr" is explicitly set in TF file to a non-empty string. + log.Debugf("ipcidrDiffSupperss: key=%s, oldVal=%q, newVal=%q -> suppress=FALSE", key, oldVal, newVal) + return false // there is a difference between stored and new value + } + log.Debugf("ipcidrDiffSupperss: key=%s, oldVal=%q, newVal=%q -> suppress=TRUE", key, oldVal, newVal) + return true // suppress difference +} + +func resourceVinsCreate(ctx context.Context, d *schema.ResourceData, m interface{}) diag.Diagnostics { + log.Debugf("resourceVinsCreate: called for ViNS name %s, Account ID %d, RG ID %d", + d.Get("name").(string), d.Get("account_id").(int), d.Get("rg_id").(int)) + + apiToCall := VinsCreateInAccountAPI + + c := m.(*controller.ControllerCfg) + urlValues := &url.Values{} + + urlValues.Add("name", d.Get("name").(string)) + + argVal, argSet := d.GetOk("rg_id") + if argSet && argVal.(int) > 0 { + apiToCall = VinsCreateInRgAPI + urlValues.Add("rgId", fmt.Sprintf("%d", argVal.(int))) + } else { + // RG ID either not set at all or set to 0 - user may want ViNS at account level + argVal, argSet = d.GetOk("account_id") + if !argSet || argVal.(int) <= 0 { + // No valid Account ID (and no RG ID either) - cannot create ViNS + return diag.Errorf("resourceVinsCreate: ViNS name %s - no valid account and/or resource group ID specified", d.Id()) + } + urlValues.Add("accountId", fmt.Sprintf("%d", argVal.(int))) + } + + argVal, argSet = d.GetOk("ext_net_id") // NB: even if ext_net_id value is explicitly set to 0, argSet = false anyway + if argSet { + if argVal.(int) > 0 { + // connect to specific external network + urlValues.Add("extNetId", fmt.Sprintf("%d", argVal.(int))) + /* + Commented out, as we've made "ext_net_ip" parameter non-configurable via Terraform! + + // in case of specific ext net connection user may also want a particular IP address + argVal, argSet = d.GetOk("ext_net_ip") + if argSet && argVal.(string) != "" { + urlValues.Add("extIp", argVal.(string)) + } + */ + } else { + // ext_net_id is set to a negative value - connect to default external network + // no particular IP address selection in this case + urlValues.Add("extNetId", "0") + } + } + + argVal, argSet = d.GetOk("ipcidr") + if argSet && argVal.(string) != "" { + log.Debugf("resourceVinsCreate: ipcidr is set to %s", argVal.(string)) + urlValues.Add("ipcidr", argVal.(string)) + } + + argVal, argSet = d.GetOk("description") + if argSet { + urlValues.Add("desc", argVal.(string)) + } + + apiResp, err := c.DecortAPICall(ctx, "POST", apiToCall, urlValues) + if err != nil { + return diag.FromErr(err) + } + + d.SetId(apiResp) // update ID of the resource to tell Terraform that the ViNS resource exists + vinsId, _ := strconv.Atoi(apiResp) + + log.Debugf("resourceVinsCreate: new ViNS ID / name %d / %s creation sequence complete", vinsId, d.Get("name").(string)) + + // We may reuse dataSourceVinsRead here as we maintain similarity + // between ViNS resource and ViNS data source schemas + // ViNS resource read function will also update resource ID on success, so that Terraform + // will know the resource exists (however, we already did it a few lines before) + return dataSourceVinsRead(ctx, d, m) +} + +func resourceVinsRead(ctx context.Context, d *schema.ResourceData, m interface{}) diag.Diagnostics { + vinsFacts, err := utilityVinsCheckPresence(ctx, d, m) + if vinsFacts == "" { + // if empty string is returned from utilityVinsCheckPresence then there is no + // such ViNS and err tells so - just return it to the calling party + d.SetId("") // ensure ID is empty + return diag.FromErr(err) + } + + return flattenVins(d, vinsFacts) +} + +func resourceVinsUpdate(ctx context.Context, d *schema.ResourceData, m interface{}) diag.Diagnostics { + + log.Debugf("resourceVinsUpdate: called for ViNS ID / name %s / %s, Account ID %d, RG ID %d", + d.Id(), d.Get("name").(string), d.Get("account_id").(int), d.Get("rg_id").(int)) + + c := m.(*controller.ControllerCfg) + + // 1. Handle external network connection change + oldExtNetId, newExtNedId := d.GetChange("ext_net_id") + if oldExtNetId.(int) != newExtNedId.(int) { + log.Debugf("resourceVinsUpdate: changing ViNS ID %s - ext_net_id %d -> %d", d.Id(), oldExtNetId.(int), newExtNedId.(int)) + + extnetParams := &url.Values{} + extnetParams.Add("vinsId", d.Id()) + + if oldExtNetId.(int) > 0 { + // there was preexisting external net connection - disconnect ViNS + _, err := c.DecortAPICall(ctx, "POST", VinsExtNetDisconnectAPI, extnetParams) + if err != nil { + return diag.FromErr(err) + } + } + + if newExtNedId.(int) > 0 { + // new external network connection requested - connect ViNS + extnetParams.Add("netId", fmt.Sprintf("%d", newExtNedId.(int))) + _, err := c.DecortAPICall(ctx, "POST", VinsExtNetConnectAPI, extnetParams) + if err != nil { + return diag.FromErr(err) + } + } + } + + // we may reuse dataSourceVinsRead here as we maintain similarity + // between Compute resource and Compute data source schemas + return dataSourceVinsRead(ctx, d, m) +} + +func resourceVinsDelete(ctx context.Context, d *schema.ResourceData, m interface{}) diag.Diagnostics { + log.Debugf("resourceVinsDelete: called for ViNS ID / name %s / %s, Account ID %d, RG ID %d", + d.Id(), d.Get("name").(string), d.Get("account_id").(int), d.Get("rg_id").(int)) + + vinsFacts, err := utilityVinsCheckPresence(ctx, d, m) + if vinsFacts == "" { + if err != nil { + return diag.FromErr(err) + } + // the specified ViNS does not exist - in this case according to Terraform best practice + // we exit from Destroy method without error + return nil + } + + params := &url.Values{} + params.Add("vinsId", d.Id()) + params.Add("force", "1") // disconnect all computes before deleting ViNS + params.Add("permanently", "1") // delete ViNS immediately bypassing recycle bin + + c := m.(*controller.ControllerCfg) + _, err = c.DecortAPICall(ctx, "POST", VinsDeleteAPI, params) + if err != nil { + return diag.FromErr(err) + } + + return nil +} + +func resourceVinsExists(ctx context.Context, d *schema.ResourceData, m interface{}) (bool, error) { + // Reminder: according to Terraform rules, this function should not modify its ResourceData argument + log.Debugf("resourceVinsExists: called for ViNS name %s, Account ID %d, RG ID %d", + d.Get("name").(string), d.Get("account_id").(int), d.Get("rg_id").(int)) + + vinsFacts, err := utilityVinsCheckPresence(ctx, d, m) + if vinsFacts == "" { + if err != nil { + return false, err + } + return false, nil + } + return true, nil +} + +func resourceVinsSchemaMake() map[string]*schema.Schema { + rets := map[string]*schema.Schema{ + "name": { + Type: schema.TypeString, + Required: true, + ValidateFunc: validation.StringIsNotEmpty, + Description: "Name of the ViNS. Names are case sensitive and unique within the context of an account or resource group.", + }, + + /* we do not need ViNS ID as an argument because if we already know this ID, it is not practical to call resource provider. + Resource Import will work anyway, as it obtains the ID of ViNS to be imported through another mechanism. + "vins_id": { + Type: schema.TypeInt, + Optional: true, + Description: "Unique ID of the ViNS. If ViNS ID is specified, then ViNS name, rg_id and account_id are ignored.", + }, + */ + + "rg_id": { + Type: schema.TypeInt, + Optional: true, + ForceNew: true, + Default: 0, + Description: "ID of the resource group, where this ViNS belongs to. Non-zero for ViNS created at resource group level, 0 otherwise.", + }, + + "account_id": { + Type: schema.TypeInt, + Required: true, + ForceNew: true, + ValidateFunc: validation.IntAtLeast(1), + Description: "ID of the account, which this ViNS belongs to. For ViNS created at account level, resource group ID is 0.", + }, + + "ext_net_id": { + Type: schema.TypeInt, + Required: true, + ValidateFunc: validation.IntAtLeast(0), + Description: "ID of the external network this ViNS is connected to. Pass 0 if no external connection required.", + }, + + "ipcidr": { + Type: schema.TypeString, + Optional: true, + DiffSuppressFunc: ipcidrDiffSupperss, + Description: "Network address to use by this ViNS. This parameter is only valid when creating new ViNS.", + }, + + "description": { + Type: schema.TypeString, + Optional: true, + Default: "", + Description: "Optional user-defined text description of this ViNS.", + }, + + // the rest of attributes are computed + "account_name": { + Type: schema.TypeString, + Computed: true, + Description: "Name of the account, which this ViNS belongs to.", + }, + + "ext_ip_addr": { + Type: schema.TypeString, + Computed: true, + Description: "IP address of the external connection (valid for ViNS connected to external network, ignored otherwise).", + }, + } + + return rets +} + +func ResourceVins() *schema.Resource { + return &schema.Resource{ + SchemaVersion: 1, + + CreateContext: resourceVinsCreate, + ReadContext: resourceVinsRead, + UpdateContext: resourceVinsUpdate, + DeleteContext: resourceVinsDelete, + + Importer: &schema.ResourceImporter{ + State: schema.ImportStatePassthrough, + }, + + Timeouts: &schema.ResourceTimeout{ + Create: &constants.Timeout180s, + Read: &constants.Timeout30s, + Update: &constants.Timeout180s, + Delete: &constants.Timeout60s, + Default: &constants.Timeout60s, + }, + + Schema: resourceVinsSchemaMake(), + } +} diff --git a/internal/service/cloudbroker/vins/utility_vins.go b/internal/service/cloudbroker/vins/utility_vins.go new file mode 100644 index 0000000..a53ea85 --- /dev/null +++ b/internal/service/cloudbroker/vins/utility_vins.go @@ -0,0 +1,153 @@ +/* +Copyright (c) 2019-2022 Digital Energy Cloud Solutions LLC. All Rights Reserved. +Authors: +Petr Krutov, +Stanislav Solovev, + +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. +*/ + +/* +Terraform DECORT provider - manage resources provided by DECORT (Digital Energy Cloud +Orchestration Technology) with Terraform by Hashicorp. + +Source code: https://github.com/rudecs/terraform-provider-decort + +Please see README.md to learn where to place source code so that it +builds seamlessly. + +Documentation: https://github.com/rudecs/terraform-provider-decort/wiki +*/ + +package vins + +import ( + "context" + "encoding/json" + "fmt" + "net/url" + "strconv" + + "github.com/rudecs/terraform-provider-decort/internal/controller" + log "github.com/sirupsen/logrus" + + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" +) + +// On success this function returns a string, as returned by API vins/get, which could be unmarshalled +// into VinsGetResp structure +func utilityVinsCheckPresence(ctx context.Context, d *schema.ResourceData, m interface{}) (string, error) { + // This function tries to locate ViNS by one of the following algorithms depending + // on the parameters passed: + // - if resource group ID is specified -> it looks for a ViNS at the RG level + // - if account ID is specifeid -> it looks for a ViNS at the account level + // + // If succeeded, it returns non empty string that contains JSON formatted facts about the + // ViNS as returned by vins/get API call. + // Otherwise it returns empty string and a meaningful error. + // + // This function does not modify its ResourceData argument, so it is safe to use it as core + // method for the Terraform resource Exists method. + // + + c := m.(*controller.ControllerCfg) + urlValues := &url.Values{} + + // make it possible to use "read" & "check presence" functions with ViNS ID set so + // that Import of ViNS resource is possible + idSet := false + theId, err := strconv.Atoi(d.Id()) + if err != nil || theId <= 0 { + vinsId, argSet := d.GetOk("vins_id") // NB: vins_id is NOT present in vinsResource schema! + if argSet { + theId = vinsId.(int) + idSet = true + } + } else { + idSet = true + } + + if idSet { + // ViNS ID is specified, try to get compute instance straight by this ID + log.Debugf("utilityVinsCheckPresence: locating ViNS by its ID %d", theId) + urlValues.Add("vinsId", fmt.Sprintf("%d", theId)) + vinsFacts, err := c.DecortAPICall(ctx, "POST", VinsGetAPI, urlValues) + if err != nil { + return "", err + } + return vinsFacts, nil + } + + // ID was not set in the schema upon entering this function - work through ViNS name + // and Account / RG ID + + vinsName, argSet := d.GetOk("name") + if !argSet { + // if ViNS name is not set. then we cannot locate ViNS + return "", fmt.Errorf("Cannot check ViNS presence if ViNS name is empty") + } + urlValues.Add("name", vinsName.(string)) + urlValues.Add("show_all", "false") + log.Debugf("utilityVinsCheckPresence: preparing to locate ViNS name %s", vinsName.(string)) + + rgId, rgSet := d.GetOk("rg_id") + if rgSet { + log.Debugf("utilityVinsCheckPresence: limiting ViNS search to RG ID %d", rgId.(int)) + urlValues.Add("rgId", fmt.Sprintf("%d", rgId.(int))) + } + + accountId, accountSet := d.GetOk("account_id") + if accountSet { + log.Debugf("utilityVinsCheckPresence: limiting ViNS search to Account ID %d", accountId.(int)) + urlValues.Add("accountId", fmt.Sprintf("%d", accountId.(int))) + } + + apiResp, err := c.DecortAPICall(ctx, "POST", VinsSearchAPI, urlValues) + if err != nil { + return "", err + } + + // log.Debugf("%s", apiResp) + // log.Debugf("utilityResgroupCheckPresence: ready to decode response body from %s", VinsSearchAPI) + model := VinsSearchResp{} + err = json.Unmarshal([]byte(apiResp), &model) + if err != nil { + return "", err + } + + log.Debugf("utilityVinsCheckPresence: traversing decoded Json of length %d", len(model)) + for index, item := range model { + if item.Name == vinsName.(string) { + if (accountSet && item.AccountID != accountId.(int)) || + (rgSet && item.RgID != rgId.(int)) { + // double check that account ID and Rg ID match, if set in the schema + continue + } + + log.Debugf("utilityVinsCheckPresence: match ViNS name %s / ID %d, account ID %d, RG ID %d at index %d", + item.Name, item.ID, item.AccountID, item.RgID, index) + + // element returned by API vins/search does not contain all information we may need to + // manage ViNS, so we have to get detailed info by calling API vins/get + rqValues := &url.Values{} + rqValues.Add("vinsId", fmt.Sprintf("%d", item.ID)) + vinsGetResp, err := c.DecortAPICall(ctx, "POST", VinsGetAPI, rqValues) + if err != nil { + return "", err + } + return vinsGetResp, nil + } + } + + return "", fmt.Errorf("Cannot find ViNS name %s. Check name and/or RG ID & Account ID and your access rights", vinsName.(string)) +} diff --git a/internal/service/cloudbroker/vins/utility_vins_list.go b/internal/service/cloudbroker/vins/utility_vins_list.go new file mode 100644 index 0000000..4746f23 --- /dev/null +++ b/internal/service/cloudbroker/vins/utility_vins_list.go @@ -0,0 +1,73 @@ +/* +Copyright (c) 2019-2022 Digital Energy Cloud Solutions LLC. All Rights Reserved. +Authors: +Petr Krutov, +Stanislav Solovev, + +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. +*/ + +/* +Terraform DECORT provider - manage resources provided by DECORT (Digital Energy Cloud +Orchestration Technology) with Terraform by Hashicorp. + +Source code: https://github.com/rudecs/terraform-provider-decort + +Please see README.md to learn where to place source code so that it +builds seamlessly. + +Documentation: https://github.com/rudecs/terraform-provider-decort/wiki +*/ + +package vins + +import ( + "context" + "encoding/json" + "net/url" + "strconv" + + "github.com/rudecs/terraform-provider-decort/internal/controller" + log "github.com/sirupsen/logrus" + + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" +) + +func utilityVinsListCheckPresence(ctx context.Context, d *schema.ResourceData, m interface{}) (VinsList, error) { + vinsList := VinsList{} + c := m.(*controller.ControllerCfg) + urlValues := &url.Values{} + + if includeDeleted, ok := d.GetOk("include_deleted"); ok { + urlValues.Add("includeDeleted", strconv.FormatBool(includeDeleted.(bool))) + } + if page, ok := d.GetOk("page"); ok { + urlValues.Add("page", strconv.Itoa(page.(int))) + } + if size, ok := d.GetOk("size"); ok { + urlValues.Add("size", strconv.Itoa(size.(int))) + } + + log.Debugf("utilityVinsListCheckPresence") + vinsListRaw, err := c.DecortAPICall(ctx, "POST", VinsListAPI, urlValues) + if err != nil { + return nil, err + } + + err = json.Unmarshal([]byte(vinsListRaw), &vinsList) + if err != nil { + return nil, err + } + + return vinsList, nil +} diff --git a/samples/README.md b/samples/README.md index d77ed3e..9ec7c53 100644 --- a/samples/README.md +++ b/samples/README.md @@ -2,62 +2,96 @@ Каждый файл снабжен комментариями, которые кратко описывают возможности и параметры ресурса. Для успешной работы необходим установленный terraform. ## Ресурсы в примерах -- data: - - grid - - grid_list - - image - - image_list - - image_list_stacks - - snapshot_list - - pcidevice_list - - pcidevice - - sep - - sep_list - - sep_disk_list - - sep_config - - sep_pool - - sep_consumption - - vgpu - - disk_list - - rg_list - - account_list - - account_computes_list - - account_disks_list - - account_vins_list - - account_audits_list - - account - - account_rg_list - - account_counsumed_units - - account_counsumed_units_by_type - - account_reserved_units - - account_templates_list - - account_deleted_list - - bservice_list - - bservice_snapshot_list - - bservice_deleted_list - - bservice - - bservice_group - - extnet_default - - extnet_list - - extnet - - extnet_computes_list - - vins_list - - locations_list - - location_url -- resources: - - image - - virtual_image - - cdrom_image - - delete_images - - k8s - - k8s_wg - - snapshot - - pcidevice - - sep - - sep_config - - account - - bservice - - bservice_group +- cloudapi: + - data: + - image + - image_list + - image_list_stacks + - snapshot_list + - pcidevice_list + - pcidevice + - vgpu + - disk_list + - rg_list + - account_list + - account_computes_list + - account_disks_list + - account_vins_list + - account_audits_list + - account + - account_rg_list + - account_counsumed_units + - account_counsumed_units_by_type + - account_reserved_units + - account_templates_list + - account_deleted_list + - bservice_list + - bservice_snapshot_list + - bservice_deleted_list + - bservice + - bservice_group + - extnet_default + - extnet_list + - extnet + - extnet_computes_list + - vins_list + - locations_list + - location_url + - resources: + - image + - virtual_image + - cdrom_image + - delete_images + - k8s + - k8s_wg + - snapshot + - pcidevice + - account + - bservice + - bservice_group +- cloudbroker: + - data: + - grid + - grid_list + - image + - image_list + - image_list_stacks + - pcidevice_list + - pcidevice + - sep + - sep_list + - sep_disk_list + - sep_config + - sep_pool + - sep_consumption + - disk_list + - rg_list + - account_list + - account_computes_list + - account_disks_list + - account_vins_list + - account_audits_list + - account + - account_rg_list + - account_counsumed_units + - account_counsumed_units_by_type + - account_reserved_units + - account_templates_list + - account_deleted_list + - vins_list + - resources: + - image + - virtual_image + - cdrom_image + - delete_images + - k8s + - k8s_wg + - snapshot + - pcidevice + - sep + - sep_config + - account + - vins ## Как пользоваться примерами 1. Установить terraform diff --git a/samples/cloudapi/data_disk/main.tf b/samples/cloudapi/data_disk/main.tf new file mode 100644 index 0000000..941dccf --- /dev/null +++ b/samples/cloudapi/data_disk/main.tf @@ -0,0 +1,35 @@ +/* +Пример использования +Получение списка доступных образов +*/ +#Расскомментируйте этот код, +#и внесите необходимые правки в версию и путь, +#чтобы работать с установленным вручную (не через hashicorp provider registry) провайдером + +terraform { + required_providers { + decort = { + version = "1.1" + source = "digitalenergy.online/decort/decort" + } + } +} + + +provider "decort" { + authenticator = "oauth2" + #controller_url = + controller_url = "https://ds1.digitalenergy.online" + #oauth2_url = + oauth2_url = "https://sso.digitalenergy.online" + allow_unverified_ssl = true +} + +data "decort_disk" "acl" { + disk_id = 49304 + +} + +output "test" { + value = data.decort_disk.acl +} diff --git a/samples/cloudapi/data_image/main.tf b/samples/cloudapi/data_image/main.tf new file mode 100644 index 0000000..bf65e29 --- /dev/null +++ b/samples/cloudapi/data_image/main.tf @@ -0,0 +1,43 @@ +/* +Пример использования +Получение информации об образе +*/ +#Расскомментируйте этот код, +#и внесите необходимые правки в версию и путь, +#чтобы работать с установленным вручную (не через hashicorp provider registry) провайдером +/* +terraform { + required_providers { + decort = { + version = "1.1" + source = "digitalenergy.online/decort/decort" + } + } +} +*/ + +provider "decort" { + authenticator = "oauth2" + #controller_url = + controller_url = "https://ds1.digitalenergy.online" + #oauth2_url = + oauth2_url = "https://sso.digitalenergy.online" + allow_unverified_ssl = true +} + +data "decort_image" "image" { + #id образа + #обязательный параметр + #тип - число + image_id = 111 + + #позывать ли информацию об удаленном образе + #опциональный параметр + #тип - булево значение + #по умолчанию - false + #show_all = false +} + +output "test" { + value = data.decort_image.image +} diff --git a/samples/cloudapi/data_image_list/main.tf b/samples/cloudapi/data_image_list/main.tf new file mode 100644 index 0000000..06084eb --- /dev/null +++ b/samples/cloudapi/data_image_list/main.tf @@ -0,0 +1,52 @@ +/* +Пример использования +Получение списка доступных образов +*/ +#Расскомментируйте этот код, +#и внесите необходимые правки в версию и путь, +#чтобы работать с установленным вручную (не через hashicorp provider registry) провайдером + +terraform { + required_providers { + decort = { + version = "1.1" + source = "digitalenergy.online/decort/decort" + } + } +} + + +provider "decort" { + authenticator = "oauth2" + #controller_url = + controller_url = "https://ds1.digitalenergy.online" + #oauth2_url = + oauth2_url = "https://sso.digitalenergy.online" + allow_unverified_ssl = true +} + +data "decort_image_list" "il" { + #id аккаунта для включения образов аккаунтов в результат + #пользователь для осуществления успешного запроса должен иметь права доступа к аккаунту + #опциональный параметр + #тип - число + #если не задан - выводятся все общие образа + #account_id = 111 + + #номер страницы для отображения + #опциональный параметр + #тип - число + #если не задан - выводятся все доступные данные + #page = 2 + + #размер страницы + #опциональный параметр + #тип - число + #если не задан - выводятся все доступные данные + #size = 3 + +} + +output "test" { + value = data.decort_image_list.il +} diff --git a/samples/cloudapi/resource_disk/main.tf b/samples/cloudapi/resource_disk/main.tf new file mode 100644 index 0000000..7097213 --- /dev/null +++ b/samples/cloudapi/resource_disk/main.tf @@ -0,0 +1,56 @@ +/* +Пример использования +Получение списка доступных образов +*/ +#Расскомментируйте этот код, +#и внесите необходимые правки в версию и путь, +#чтобы работать с установленным вручную (не через hashicorp provider registry) провайдером + +terraform { + required_providers { + decort = { + version = "1.1" + source = "digitalenergy.online/decort/decort" + } + } +} + + +provider "decort" { + authenticator = "oauth2" + #controller_url = + controller_url = "https://ds1.digitalenergy.online" + #oauth2_url = + oauth2_url = "https://sso.digitalenergy.online" + allow_unverified_ssl = true +} + +resource "decort_disk" "acl" { + account_id = 88366 + gid = 212 + disk_name = "super-disk-re" + size_max = 20 + restore = true + permanently = true + reason = "delete" + iotune { + read_bytes_sec = 0 + read_bytes_sec_max = 0 + read_iops_sec = 0 + read_iops_sec_max = 0 + size_iops_sec = 0 + total_bytes_sec = 0 + total_bytes_sec_max = 0 + total_iops_sec = 3000 + total_iops_sec_max = 0 + write_bytes_sec = 0 + write_bytes_sec_max = 0 + write_iops_sec = 0 + write_iops_sec_max = 0 + } + +} + +output "test" { + value = decort_disk.acl +} diff --git a/samples/cloudbroker/data_account_audits_list/main.tf b/samples/cloudbroker/data_account_audits_list/main.tf new file mode 100644 index 0000000..1cd48f5 --- /dev/null +++ b/samples/cloudbroker/data_account_audits_list/main.tf @@ -0,0 +1,40 @@ +/* +Пример использования +Получение информации об использовании аккаунта + +*/ +#Расскомментируйте этот код, +#и внесите необходимые правки в версию и путь, +#чтобы работать с установленным вручную (не через hashicorp provider registry) провайдером +/* +terraform { + required_providers { + decort = { + version = "1.1" + source = "digitalenergy.online/decort/decort" + } + } +} +*/ + + +provider "decort" { + authenticator = "oauth2" + #controller_url = + controller_url = "https://ds1.digitalenergy.online" + #oauth2_url = + oauth2_url = "https://sso.digitalenergy.online" + allow_unverified_ssl = true +} + +data "decort_account_audits_list" "aal" { + #id аккаунта + #обязательный параметр + #тип - число + account_id = 11111 + +} + +output "test" { + value = data.decort_account_audits_list.aal +} diff --git a/samples/cloudbroker/data_account_computes_list/main.tf b/samples/cloudbroker/data_account_computes_list/main.tf new file mode 100644 index 0000000..26edae2 --- /dev/null +++ b/samples/cloudbroker/data_account_computes_list/main.tf @@ -0,0 +1,39 @@ +/* +Пример использования +Получение списка computes, используемых аккаунтом + +*/ +#Расскомментируйте этот код, +#и внесите необходимые правки в версию и путь, +#чтобы работать с установленным вручную (не через hashicorp provider registry) провайдером +/* +terraform { + required_providers { + decort = { + version = "1.1" + source = "digitalenergy.online/decort/decort" + } + } +} +*/ + +provider "decort" { + authenticator = "oauth2" + #controller_url = + controller_url = "https://ds1.digitalenergy.online" + #oauth2_url = + oauth2_url = "https://sso.digitalenergy.online" + allow_unverified_ssl = true +} + +data "decort_account_computes_list" "acl" { + #id аккаунта + #обязательный параметр + #тип - число + account_id = 1111 + +} + +output "test" { + value = data.decort_account_computes_list.acl +} diff --git a/samples/cloudbroker/data_account_deleted_list/main.tf b/samples/cloudbroker/data_account_deleted_list/main.tf new file mode 100644 index 0000000..7309fcd --- /dev/null +++ b/samples/cloudbroker/data_account_deleted_list/main.tf @@ -0,0 +1,45 @@ +/* +Пример использования +Получение информации об удаленных аккаунтах +Информация предоставляется только по аккаунтам, удаленным без флага permanently +*/ +#Расскомментируйте этот код, +#и внесите необходимые правки в версию и путь, +#чтобы работать с установленным вручную (не через hashicorp provider registry) провайдером +/* +terraform { + required_providers { + decort = { + version = "1.1" + source = "digitalenergy.online/decort/decort" + } + } +} +*/ + +provider "decort" { + authenticator = "oauth2" + #controller_url = + controller_url = "https://ds1.digitalenergy.online" + #oauth2_url = + oauth2_url = "https://sso.digitalenergy.online" + allow_unverified_ssl = true +} + +data "decort_account_deleted_list" "adl" { + #номер страницы для отображения + #опциональный параметр + #тип - число + #если не задан - выводятся все доступные данные + #page = 2 + + #размер страницы + #опциональный параметр + #тип - число + #если не задан - выводятся все доступные данные + #size = 3 +} + +output "test" { + value = data.decort_account_deleted_list.adl +} diff --git a/samples/cloudbroker/data_account_disks_list/main.tf b/samples/cloudbroker/data_account_disks_list/main.tf new file mode 100644 index 0000000..c0ac605 --- /dev/null +++ b/samples/cloudbroker/data_account_disks_list/main.tf @@ -0,0 +1,39 @@ +/* +Пример использования +Получение информации о дисках, которые использует аккаунт + +*/ +#Расскомментируйте этот код, +#и внесите необходимые правки в версию и путь, +#чтобы работать с установленным вручную (не через hashicorp provider registry) провайдером +/* +terraform { + required_providers { + decort = { + version = "1.1" + source = "digitalenergy.online/decort/decort" + } + } +} +*/ + +provider "decort" { + authenticator = "oauth2" + #controller_url = + controller_url = "https://ds1.digitalenergy.online" + #oauth2_url = + oauth2_url = "https://sso.digitalenergy.online" + allow_unverified_ssl = true +} + +data "decort_account_disks_list" "adl" { + #id аккаунта + #обязательный параметр + #тип - число + account_id = 11111 + +} + +output "test" { + value = data.decort_account_disks_list.adl +} diff --git a/samples/cloudbroker/data_account_flipgroups_list/main.tf b/samples/cloudbroker/data_account_flipgroups_list/main.tf new file mode 100644 index 0000000..134d621 --- /dev/null +++ b/samples/cloudbroker/data_account_flipgroups_list/main.tf @@ -0,0 +1,38 @@ +/* +Пример использования +Получение информации о flipgroups, используемых аккаунтом + +*/ +#Расскомментируйте этот код, +#и внесите необходимые правки в версию и путь, +#чтобы работать с установленным вручную (не через hashicorp provider registry) провайдером +/* +terraform { + required_providers { + decort = { + version = "1.1" + source = "digitalenergy.online/decort/decort" + } + } +} +*/ + +provider "decort" { + authenticator = "oauth2" + #controller_url = + controller_url = "https://ds1.digitalenergy.online" + #oauth2_url = + oauth2_url = "https://sso.digitalenergy.online" + allow_unverified_ssl = true +} + +data "decort_account_flipgroups_list" "afgl" { + #id аккаунта + #обязательный параметр + #тип - число + account_id = 1111 +} + +output "test" { + value = data.decort_account_flipgroups_list.afgl +} diff --git a/samples/cloudbroker/data_account_list/main.tf b/samples/cloudbroker/data_account_list/main.tf new file mode 100644 index 0000000..381eaed --- /dev/null +++ b/samples/cloudbroker/data_account_list/main.tf @@ -0,0 +1,44 @@ +/* +Пример использования +Получение всех аккаунтов,имеющихся в системе +*/ +#Расскомментируйте этот код, +#и внесите необходимые правки в версию и путь, +#чтобы работать с установленным вручную (не через hashicorp provider registry) провайдером +/* +terraform { + required_providers { + decort = { + version = "1.1" + source = "digitalenergy.online/decort/decort" + } + } +} +*/ + +provider "decort" { + authenticator = "oauth2" + #controller_url = + controller_url = "https://ds1.digitalenergy.online" + #oauth2_url = + oauth2_url = "https://sso.digitalenergy.online" + allow_unverified_ssl = true +} + +data "decort_account_list" "al" { + #номер страницы для отображения + #опциональный параметр + #тип - число + #если не задан - выводятся все доступные данные + #page = 2 + + #размер страницы + #опциональный параметр + #тип - число + #если не задан - выводятся все доступные данные + #size = 3 +} + +output "test" { + value = data.decort_account_list.al +} diff --git a/samples/cloudbroker/data_account_rg_list/main.tf b/samples/cloudbroker/data_account_rg_list/main.tf new file mode 100644 index 0000000..13fbb6d --- /dev/null +++ b/samples/cloudbroker/data_account_rg_list/main.tf @@ -0,0 +1,37 @@ +/* +Пример использования +Получение информации о ресурных группах, используемых аккаунтом +*/ +#Расскомментируйте этот код, +#и внесите необходимые правки в версию и путь, +#чтобы работать с установленным вручную (не через hashicorp provider registry) провайдером +/* +terraform { + required_providers { + decort = { + version = "1.1" + source = "digitalenergy.online/decort/decort" + } + } +} +*/ + +provider "decort" { + authenticator = "oauth2" + #controller_url = + controller_url = "https://ds1.digitalenergy.online" + #oauth2_url = + oauth2_url = "https://sso.digitalenergy.online" + allow_unverified_ssl = true +} + +data "decort_account_rg_list" "argl" { + #id аккаунта + #обязательный параметр + #тип - число + account_id = 66666 +} + +output "test" { + value = data.decort_account_rg_list.argl +} diff --git a/samples/cloudbroker/data_account_vins_list/main.tf b/samples/cloudbroker/data_account_vins_list/main.tf new file mode 100644 index 0000000..e0e8eda --- /dev/null +++ b/samples/cloudbroker/data_account_vins_list/main.tf @@ -0,0 +1,39 @@ +/* +Пример использования +Получение списка vins, используемых аккаунтом + +*/ +#Расскомментируйте этот код, +#и внесите необходимые правки в версию и путь, +#чтобы работать с установленным вручную (не через hashicorp provider registry) провайдером +/* +terraform { + required_providers { + decort = { + version = "1.1" + source = "digitalenergy.online/decort/decort" + } + } +} +*/ + +provider "decort" { + authenticator = "oauth2" + #controller_url = + controller_url = "https://ds1.digitalenergy.online" + #oauth2_url = + oauth2_url = "https://sso.digitalenergy.online" + allow_unverified_ssl = true +} + +data "decort_account_vins_list" "avl" { + #id аккаунта + #обязательный параметр + #тип - число + account_id = 22222 + +} + +output "test" { + value = data.decort_account_vins_list.avl +} diff --git a/samples/cloudbroker/data_disk/main.tf b/samples/cloudbroker/data_disk/main.tf new file mode 100644 index 0000000..941dccf --- /dev/null +++ b/samples/cloudbroker/data_disk/main.tf @@ -0,0 +1,35 @@ +/* +Пример использования +Получение списка доступных образов +*/ +#Расскомментируйте этот код, +#и внесите необходимые правки в версию и путь, +#чтобы работать с установленным вручную (не через hashicorp provider registry) провайдером + +terraform { + required_providers { + decort = { + version = "1.1" + source = "digitalenergy.online/decort/decort" + } + } +} + + +provider "decort" { + authenticator = "oauth2" + #controller_url = + controller_url = "https://ds1.digitalenergy.online" + #oauth2_url = + oauth2_url = "https://sso.digitalenergy.online" + allow_unverified_ssl = true +} + +data "decort_disk" "acl" { + disk_id = 49304 + +} + +output "test" { + value = data.decort_disk.acl +} diff --git a/samples/cloudbroker/data_disk_list/main.tf b/samples/cloudbroker/data_disk_list/main.tf new file mode 100644 index 0000000..1074f83 --- /dev/null +++ b/samples/cloudbroker/data_disk_list/main.tf @@ -0,0 +1,54 @@ +/* +Пример использования +Получение списка доступных дисков +*/ +#Расскомментируйте этот код, +#и внесите необходимые правки в версию и путь, +#чтобы работать с установленным вручную (не через hashicorp provider registry) провайдером +/* +terraform { + required_providers { + decort = { + version = "1.1" + source = "digitalenergy.online/decort/decort" + } + } +} +*/ + + +provider "decort" { + authenticator = "oauth2" + #controller_url = + controller_url = "https://ds1.digitalenergy.online" + #oauth2_url = + oauth2_url = "https://sso.digitalenergy.online" + allow_unverified_ssl = true +} + +data "decort_disk_list" "dl" { + #id аккаунта для получения списка дисков + #опциональный параметр + #тип - число + #account_id = 11111 + + #тип диска + #опциональный параметр + #тип - строка + #возможные типы: "b" - boot_disk, "d" - data_disk + #type = "d" + + #кол-во страниц для вывода + #опицональный параметр + #тип - число + #page = 1 + + #размер страницы + #опицональный параметр + #тип - число + #size = 1 +} + +output "test" { + value = data.decort_disk_list.dl +} diff --git a/samples/cloudbroker/resource_disk/main.tf b/samples/cloudbroker/resource_disk/main.tf new file mode 100644 index 0000000..7097213 --- /dev/null +++ b/samples/cloudbroker/resource_disk/main.tf @@ -0,0 +1,56 @@ +/* +Пример использования +Получение списка доступных образов +*/ +#Расскомментируйте этот код, +#и внесите необходимые правки в версию и путь, +#чтобы работать с установленным вручную (не через hashicorp provider registry) провайдером + +terraform { + required_providers { + decort = { + version = "1.1" + source = "digitalenergy.online/decort/decort" + } + } +} + + +provider "decort" { + authenticator = "oauth2" + #controller_url = + controller_url = "https://ds1.digitalenergy.online" + #oauth2_url = + oauth2_url = "https://sso.digitalenergy.online" + allow_unverified_ssl = true +} + +resource "decort_disk" "acl" { + account_id = 88366 + gid = 212 + disk_name = "super-disk-re" + size_max = 20 + restore = true + permanently = true + reason = "delete" + iotune { + read_bytes_sec = 0 + read_bytes_sec_max = 0 + read_iops_sec = 0 + read_iops_sec_max = 0 + size_iops_sec = 0 + total_bytes_sec = 0 + total_bytes_sec_max = 0 + total_iops_sec = 3000 + total_iops_sec_max = 0 + write_bytes_sec = 0 + write_bytes_sec_max = 0 + write_iops_sec = 0 + write_iops_sec_max = 0 + } + +} + +output "test" { + value = decort_disk.acl +} From f06aa41b96ab00321672db9af085ff307daaa0e5 Mon Sep 17 00:00:00 2001 From: kjubybot Date: Wed, 20 Jul 2022 17:37:09 +0300 Subject: [PATCH 44/51] updated linter config --- .golangci.yml | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/.golangci.yml b/.golangci.yml index 808f9e1..b21eb60 100644 --- a/.golangci.yml +++ b/.golangci.yml @@ -5,7 +5,7 @@ linters: - dogsled - errorlint - exportloopref - - gocognit + #- gocognit - disabled till better times - goconst - gocyclo - gosec @@ -20,7 +20,7 @@ linters: linters-settings: errcheck: exclude-functions: - - (*github.com/hashicorp/terraform-plugin-sdk/helper/schema.ResourceData).Set + - (*github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema.ResourceData).Set staticcheck: go: "1.18" checks: From 32754240892b8f6e5868ceb4e568c08fe2fc64da Mon Sep 17 00:00:00 2001 From: kjubybot Date: Wed, 20 Jul 2022 17:39:20 +0300 Subject: [PATCH 45/51] added arm64 to goreleaser config --- .goreleaser.yml | 3 +++ 1 file changed, 3 insertions(+) diff --git a/.goreleaser.yml b/.goreleaser.yml index a658ffb..feafdbf 100644 --- a/.goreleaser.yml +++ b/.goreleaser.yml @@ -15,9 +15,12 @@ builds: goarch: - amd64 - '386' + - arm64 ignore: - goos: darwin goarch: '386' + - goos: windows + goarch: arm64 binary: '{{ .ProjectName }}_v{{ .Version }}' archives: - format: zip From 4c4a007a58ac3f6be24820d5094ad4fc29e1c342 Mon Sep 17 00:00:00 2001 From: kjubybot Date: Thu, 21 Jul 2022 11:23:46 +0300 Subject: [PATCH 46/51] added compute deletion on failed disk/network attachment --- .../cloudapi/kvmvm/resource_compute.go | 57 +++++++------------ .../service/cloudapi/kvmvm/utility_compute.go | 42 ++++++++++++++ 2 files changed, 62 insertions(+), 37 deletions(-) diff --git a/internal/service/cloudapi/kvmvm/resource_compute.go b/internal/service/cloudapi/kvmvm/resource_compute.go index 2d6c2a3..9b8eac8 100644 --- a/internal/service/cloudapi/kvmvm/resource_compute.go +++ b/internal/service/cloudapi/kvmvm/resource_compute.go @@ -33,7 +33,6 @@ package kvmvm import ( "context" - "encoding/json" "fmt" "net/url" "strconv" @@ -129,6 +128,20 @@ func resourceComputeCreate(ctx context.Context, d *schema.ResourceData, m interf d.SetId(apiResp) // update ID of the resource to tell Terraform that the resource exists, albeit partially compId, _ := strconv.Atoi(apiResp) + cleanup := false + defer func() { + if cleanup { + utilityComputeDetachDisks(ctx, d, m) + urlValues := &url.Values{} + urlValues.Add("computeId", d.Id()) + urlValues.Add("permanently", "1") + + if _, err := c.DecortAPICall(ctx, "POST", ComputeDeleteAPI, urlValues); err != nil { + log.Errorf("resourceComputeCreate: could not delete compute after failed creation: %v", err) + } + } + }() + log.Debugf("resourceComputeCreate: new simple Compute ID %d, name %s created", compId, d.Get("name").(string)) // Configure data disks if any @@ -139,6 +152,7 @@ func resourceComputeCreate(ctx context.Context, d *schema.ResourceData, m interf err = utilityComputeExtraDisksConfigure(ctx, d, m, false) // do_delta=false, as we are working on a new compute if err != nil { log.Errorf("resourceComputeCreate: error when attaching extra disk(s) to a new Compute ID %d: %v", compId, err) + cleanup = true return diag.FromErr(err) } } @@ -149,6 +163,7 @@ func resourceComputeCreate(ctx context.Context, d *schema.ResourceData, m interf err = utilityComputeNetworksConfigure(ctx, d, m, false) // do_delta=false, as we are working on a new compute if err != nil { log.Errorf("resourceComputeCreate: error when attaching networks to a new Compute ID %d: %s", compId, err) + cleanup = true return diag.FromErr(err) } } @@ -160,6 +175,7 @@ func resourceComputeCreate(ctx context.Context, d *schema.ResourceData, m interf reqValues.Add("computeId", fmt.Sprintf("%d", compId)) log.Debugf("resourceComputeCreate: starting Compute ID %d after completing its resource configuration", compId) if _, err := c.DecortAPICall(ctx, "POST", ComputeStartAPI, reqValues); err != nil { + cleanup = true return diag.FromErr(err) } } @@ -297,51 +313,18 @@ func resourceComputeDelete(ctx context.Context, d *schema.ResourceData, m interf log.Debugf("resourceComputeDelete: called for Compute name %s, RG ID %d", d.Get("name").(string), d.Get("rg_id").(int)) - compFacts, err := utilityComputeCheckPresence(ctx, d, m) - if compFacts == "" { - if err != nil { - return diag.FromErr(err) - } - // the target Compute does not exist - in this case according to Terraform best practice - // we exit from Destroy method without error - return nil + if err := utilityComputeDetachDisks(ctx, d, m); err != nil { + return diag.FromErr(err) } c := m.(*controller.ControllerCfg) - model := ComputeGetResp{} - log.Debugf("resourceComputeDelete: ready to unmarshal string %s", compFacts) - err = json.Unmarshal([]byte(compFacts), &model) - if err == nil && len(model.Disks) > 0 { - // prepare to detach data disks from compute - do it only if compFacts unmarshalled - // properly and the resulting model contains non-empty Disks list - for _, diskFacts := range model.Disks { - if diskFacts.Type == "B" { - // boot disk is never detached on compute delete - continue - } - - log.Debugf("resourceComputeDelete: ready to detach data disk ID %d from compute ID %s", diskFacts.ID, d.Id()) - - detachParams := &url.Values{} - detachParams.Add("computeId", d.Id()) - detachParams.Add("diskId", fmt.Sprintf("%d", diskFacts.ID)) - - _, err = c.DecortAPICall(ctx, "POST", ComputeDiskDetachAPI, detachParams) - if err != nil { - // We do not fail compute deletion on data disk detach errors - log.Errorf("resourceComputeDelete: error when detaching Disk ID %d: %s", diskFacts.ID, err) - } - } - } - params := &url.Values{} params.Add("computeId", d.Id()) params.Add("permanently", "1") // TODO: this is for the upcoming API update - params.Add("detachdisks", "1") - _, err = c.DecortAPICall(ctx, "POST", ComputeDeleteAPI, params) - if err != nil { + if _, err := c.DecortAPICall(ctx, "POST", ComputeDeleteAPI, params); err != nil { return diag.FromErr(err) } diff --git a/internal/service/cloudapi/kvmvm/utility_compute.go b/internal/service/cloudapi/kvmvm/utility_compute.go index 0bf64ea..27fd4bb 100644 --- a/internal/service/cloudapi/kvmvm/utility_compute.go +++ b/internal/service/cloudapi/kvmvm/utility_compute.go @@ -308,3 +308,45 @@ func utilityComputeCheckPresence(ctx context.Context, d *schema.ResourceData, m return "", nil // there should be no error if Compute does not exist } + +func utilityComputeDetachDisks(ctx context.Context, d *schema.ResourceData, m interface{}) error { + compFacts, err := utilityComputeCheckPresence(ctx, d, m) + if compFacts == "" { + if err != nil { + return err + } + // the target Compute does not exist - in this case according to Terraform best practice + // we exit from Destroy method without error + return nil + } + + c := m.(*controller.ControllerCfg) + + model := ComputeGetResp{} + log.Debugf("resourceComputeDelete: ready to unmarshal string %s", compFacts) + err = json.Unmarshal([]byte(compFacts), &model) + + if err != nil && len(model.Disks) > 0 { + // prepare to detach data disks from compute - do it only if compFacts unmarshalled + // properly and the resulting model contains non-empty Disks list + for _, diskFacts := range model.Disks { + if diskFacts.Type == "B" { + // boot disk is never detached on compute delete + continue + } + + log.Debugf("utilityComputeDetachDisks: ready to detach data disk ID %d from compute ID %s", diskFacts.ID, d.Id()) + + detachParams := &url.Values{} + detachParams.Add("computeId", d.Id()) + detachParams.Add("diskId", fmt.Sprintf("%d", diskFacts.ID)) + + if _, err := c.DecortAPICall(ctx, "POST", ComputeDiskDetachAPI, detachParams); err != nil { + // We do not fail compute deletion on data disk detach errors + log.Errorf("utilityComputeDetachDisks: error when detaching Disk ID %d: %s", diskFacts.ID, err) + } + } + } + + return nil +} From fae22aa4845c1f13591f3b60cfbd4d5cda5fb3d0 Mon Sep 17 00:00:00 2001 From: kjubybot Date: Thu, 21 Jul 2022 13:38:52 +0300 Subject: [PATCH 47/51] a lot of refactoring and fixes --- .golangci.yml | 2 + .../cloudapi/account/resource_account.go | 14 ---- .../cloudapi/bservice/resource_bservice.go | 14 ---- .../bservice/resource_bservice_group.go | 14 ---- .../service/cloudapi/disks/resource_disk.go | 12 --- .../extnet/data_source_extnet_default.go | 2 +- .../cloudapi/extnet/utility_extnet_default.go | 4 +- .../service/cloudapi/image/resource_image.go | 14 ---- internal/service/cloudapi/k8s/resource_k8s.go | 11 --- .../service/cloudapi/k8s/resource_k8s_wg.go | 14 ---- .../cloudapi/kvmvm/data_source_compute.go | 30 -------- .../cloudapi/kvmvm/resource_compute.go | 24 +----- .../service/cloudapi/kvmvm/utility_compute.go | 42 ----------- .../locations/data_source_locations_url.go | 3 +- .../locations/utility_location_url.go | 6 +- internal/service/cloudapi/pfw/resource_pfw.go | 14 ---- internal/service/cloudapi/rg/resource_rg.go | 12 --- .../cloudapi/snapshot/resource_snapshot.go | 12 --- .../service/cloudapi/vins/resource_vins.go | 15 ---- internal/service/cloudbroker/account/api.go | 8 +- .../cloudbroker/account/resource_account.go | 14 ---- .../cloudbroker/disks/resource_disk.go | 12 --- .../cloudbroker/image/resource_image.go | 14 ---- .../service/cloudbroker/k8s/resource_k8s.go | 11 --- .../cloudbroker/k8s/resource_k8s_wg.go | 14 ---- .../cloudbroker/kvmvm/data_source_compute.go | 43 ++--------- .../cloudbroker/kvmvm/resource_compute.go | 75 +++++-------------- .../pcidevice/data_source_pcidevice_list.go | 2 +- .../pcidevice/resource_pcidevice.go | 12 --- .../pcidevice/utility_pcidevice.go | 2 +- .../pcidevice/utility_pcidevice_list.go | 3 +- .../service/cloudbroker/pfw/resource_pfw.go | 14 ---- .../service/cloudbroker/rg/resource_rg.go | 12 --- .../service/cloudbroker/sep/resource_sep.go | 14 ---- .../cloudbroker/snapshot/resource_snapshot.go | 12 --- .../service/cloudbroker/vins/resource_vins.go | 15 ---- 36 files changed, 43 insertions(+), 493 deletions(-) diff --git a/.golangci.yml b/.golangci.yml index b21eb60..6c104b8 100644 --- a/.golangci.yml +++ b/.golangci.yml @@ -28,6 +28,8 @@ linters-settings: - -SA1019 nestif: min-complexity: 7 + gocyclo: + min-complexity: 40 issues: max-same-issues: 0 diff --git a/internal/service/cloudapi/account/resource_account.go b/internal/service/cloudapi/account/resource_account.go index 4a87285..4013760 100644 --- a/internal/service/cloudapi/account/resource_account.go +++ b/internal/service/cloudapi/account/resource_account.go @@ -233,20 +233,6 @@ func resourceAccountDelete(ctx context.Context, d *schema.ResourceData, m interf return nil } -func resourceAccountExists(ctx context.Context, d *schema.ResourceData, m interface{}) (bool, error) { - log.Debugf("resourceAccountExists") - - account, err := utilityAccountCheckPresence(ctx, d, m) - if account == nil { - if err != nil { - return false, err - } - return false, nil - } - - return true, nil -} - func resourceAccountEdit(ctx context.Context, d *schema.ResourceData, m interface{}) diag.Diagnostics { log.Debugf("resourceAccountEdit") c := m.(*controller.ControllerCfg) diff --git a/internal/service/cloudapi/bservice/resource_bservice.go b/internal/service/cloudapi/bservice/resource_bservice.go index ab5ff65..f8a3ed0 100644 --- a/internal/service/cloudapi/bservice/resource_bservice.go +++ b/internal/service/cloudapi/bservice/resource_bservice.go @@ -143,20 +143,6 @@ func resourceBasicServiceDelete(ctx context.Context, d *schema.ResourceData, m i return nil } -func resourceBasicServiceExists(ctx context.Context, d *schema.ResourceData, m interface{}) (bool, error) { - log.Debugf("resourceBasicServiceExists") - - bservice, err := utilityBasicServiceCheckPresence(ctx, d, m) - if bservice == nil { - if err != nil { - return false, err - } - return false, nil - } - - return true, nil -} - func resourceBasicServiceEdit(ctx context.Context, d *schema.ResourceData, m interface{}) diag.Diagnostics { log.Debugf("resourceBasicServiceEdit") c := m.(*controller.ControllerCfg) diff --git a/internal/service/cloudapi/bservice/resource_bservice_group.go b/internal/service/cloudapi/bservice/resource_bservice_group.go index 145af41..2c0e28f 100644 --- a/internal/service/cloudapi/bservice/resource_bservice_group.go +++ b/internal/service/cloudapi/bservice/resource_bservice_group.go @@ -183,20 +183,6 @@ func resourceBasicServiceGroupDelete(ctx context.Context, d *schema.ResourceData return nil } -func resourceBasicServiceGroupExists(ctx context.Context, d *schema.ResourceData, m interface{}) (bool, error) { - log.Debugf("resourceBasicServiceGroupExists") - - bserviceGroup, err := utilityBasicServiceGroupCheckPresence(ctx, d, m) - if bserviceGroup == nil { - if err != nil { - return false, err - } - return false, nil - } - - return true, nil -} - func resourceBasicServiceGroupEdit(ctx context.Context, d *schema.ResourceData, m interface{}) diag.Diagnostics { log.Debugf("resourceBasicServiceGroupEdit") c := m.(*controller.ControllerCfg) diff --git a/internal/service/cloudapi/disks/resource_disk.go b/internal/service/cloudapi/disks/resource_disk.go index 9cb264b..2ab95c4 100644 --- a/internal/service/cloudapi/disks/resource_disk.go +++ b/internal/service/cloudapi/disks/resource_disk.go @@ -281,18 +281,6 @@ func resourceDiskDelete(ctx context.Context, d *schema.ResourceData, m interface return nil } -func resourceDiskExists(ctx context.Context, d *schema.ResourceData, m interface{}) (bool, error) { - - diskFacts, err := utilityDiskCheckPresence(ctx, d, m) - if diskFacts == nil { - if err != nil { - return false, err - } - return false, nil - } - return true, nil -} - func resourceDiskSchemaMake() map[string]*schema.Schema { rets := map[string]*schema.Schema{ "account_id": { diff --git a/internal/service/cloudapi/extnet/data_source_extnet_default.go b/internal/service/cloudapi/extnet/data_source_extnet_default.go index 22463eb..765f998 100644 --- a/internal/service/cloudapi/extnet/data_source_extnet_default.go +++ b/internal/service/cloudapi/extnet/data_source_extnet_default.go @@ -42,7 +42,7 @@ import ( ) func dataSourceExtnetDefaultRead(ctx context.Context, d *schema.ResourceData, m interface{}) diag.Diagnostics { - extnetId, err := utilityExtnetDefaultCheckPresence(ctx, d, m) + extnetId, err := utilityExtnetDefaultCheckPresence(ctx, m) if err != nil { return diag.FromErr(err) } diff --git a/internal/service/cloudapi/extnet/utility_extnet_default.go b/internal/service/cloudapi/extnet/utility_extnet_default.go index 7b7257b..f94eda2 100644 --- a/internal/service/cloudapi/extnet/utility_extnet_default.go +++ b/internal/service/cloudapi/extnet/utility_extnet_default.go @@ -37,11 +37,9 @@ import ( "github.com/rudecs/terraform-provider-decort/internal/controller" log "github.com/sirupsen/logrus" - - "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" ) -func utilityExtnetDefaultCheckPresence(ctx context.Context, d *schema.ResourceData, m interface{}) (string, error) { +func utilityExtnetDefaultCheckPresence(ctx context.Context, m interface{}) (string, error) { c := m.(*controller.ControllerCfg) urlValues := &url.Values{} diff --git a/internal/service/cloudapi/image/resource_image.go b/internal/service/cloudapi/image/resource_image.go index f963141..4902535 100644 --- a/internal/service/cloudapi/image/resource_image.go +++ b/internal/service/cloudapi/image/resource_image.go @@ -192,20 +192,6 @@ func resourceImageDelete(ctx context.Context, d *schema.ResourceData, m interfac return nil } -func resourceImageExists(ctx context.Context, d *schema.ResourceData, m interface{}) (bool, error) { - log.Debugf("resourceImageExists: called for %s, id: %s", d.Get("name").(string), d.Id()) - - image, err := utilityImageCheckPresence(ctx, d, m) - if image == nil { - if err != nil { - return false, err - } - return false, nil - } - - return true, nil -} - func resourceImageEditName(ctx context.Context, d *schema.ResourceData, m interface{}) error { log.Debugf("resourceImageEditName: called for %s, id: %s", d.Get("name").(string), d.Id()) c := m.(*controller.ControllerCfg) diff --git a/internal/service/cloudapi/k8s/resource_k8s.go b/internal/service/cloudapi/k8s/resource_k8s.go index a7f6301..99dca28 100644 --- a/internal/service/cloudapi/k8s/resource_k8s.go +++ b/internal/service/cloudapi/k8s/resource_k8s.go @@ -274,17 +274,6 @@ func resourceK8sDelete(ctx context.Context, d *schema.ResourceData, m interface{ return nil } -func resourceK8sExists(ctx context.Context, d *schema.ResourceData, m interface{}) (bool, error) { - log.Debugf("resourceK8sExists: called with id %s, rg %d", d.Id(), d.Get("rg_id").(int)) - - k8s, err := utilityK8sCheckPresence(ctx, d, m) - if k8s == nil { - return false, err - } - - return true, nil -} - func resourceK8sSchemaMake() map[string]*schema.Schema { return map[string]*schema.Schema{ "name": { diff --git a/internal/service/cloudapi/k8s/resource_k8s_wg.go b/internal/service/cloudapi/k8s/resource_k8s_wg.go index d1eeafb..b167d7d 100644 --- a/internal/service/cloudapi/k8s/resource_k8s_wg.go +++ b/internal/service/cloudapi/k8s/resource_k8s_wg.go @@ -169,20 +169,6 @@ func resourceK8sWgDelete(ctx context.Context, d *schema.ResourceData, m interfac return nil } -func resourceK8sWgExists(ctx context.Context, d *schema.ResourceData, m interface{}) (bool, error) { - log.Debugf("resourceK8sWgExists: called with k8s id %d", d.Get("k8s_id").(int)) - - wg, err := utilityK8sWgCheckPresence(ctx, d, m) - if wg == nil { - if err != nil { - return false, err - } - return false, nil - } - - return true, nil -} - func resourceK8sWgSchemaMake() map[string]*schema.Schema { return map[string]*schema.Schema{ "k8s_id": { diff --git a/internal/service/cloudapi/kvmvm/data_source_compute.go b/internal/service/cloudapi/kvmvm/data_source_compute.go index 652191c..2999e3b 100644 --- a/internal/service/cloudapi/kvmvm/data_source_compute.go +++ b/internal/service/cloudapi/kvmvm/data_source_compute.go @@ -76,36 +76,6 @@ func parseComputeDisksToExtraDisks(disks []DiskRecord) []interface{} { return result } -func parseBootDiskSize(disks []DiskRecord) int { - // this return value will be used to d.Set("boot_disk_size",) item of dataSourceCompute schema - if len(disks) == 0 { - return 0 - } - - for _, value := range disks { - if value.Type == "B" { - return value.SizeMax - } - } - - return 0 -} - -func parseBootDiskId(disks []DiskRecord) uint { - // this return value will be used to d.Set("boot_disk_id",) item of dataSourceCompute schema - if len(disks) == 0 { - return 0 - } - - for _, value := range disks { - if value.Type == "B" { - return value.ID - } - } - - return 0 -} - func findBootDisk(disks []DiskRecord) *DiskRecord { for _, d := range disks { if d.Type == "B" { diff --git a/internal/service/cloudapi/kvmvm/resource_compute.go b/internal/service/cloudapi/kvmvm/resource_compute.go index 9b8eac8..6bf5c49 100644 --- a/internal/service/cloudapi/kvmvm/resource_compute.go +++ b/internal/service/cloudapi/kvmvm/resource_compute.go @@ -131,14 +131,15 @@ func resourceComputeCreate(ctx context.Context, d *schema.ResourceData, m interf cleanup := false defer func() { if cleanup { - utilityComputeDetachDisks(ctx, d, m) urlValues := &url.Values{} urlValues.Add("computeId", d.Id()) urlValues.Add("permanently", "1") + urlValues.Add("detachDisks", "1") if _, err := c.DecortAPICall(ctx, "POST", ComputeDeleteAPI, urlValues); err != nil { log.Errorf("resourceComputeCreate: could not delete compute after failed creation: %v", err) } + d.SetId("") } }() @@ -313,16 +314,12 @@ func resourceComputeDelete(ctx context.Context, d *schema.ResourceData, m interf log.Debugf("resourceComputeDelete: called for Compute name %s, RG ID %d", d.Get("name").(string), d.Get("rg_id").(int)) - if err := utilityComputeDetachDisks(ctx, d, m); err != nil { - return diag.FromErr(err) - } - c := m.(*controller.ControllerCfg) params := &url.Values{} params.Add("computeId", d.Id()) params.Add("permanently", "1") - // TODO: this is for the upcoming API update - params.Add("detachdisks", "1") + params.Add("detachDisks", "1") if _, err := c.DecortAPICall(ctx, "POST", ComputeDeleteAPI, params); err != nil { return diag.FromErr(err) @@ -331,21 +328,6 @@ func resourceComputeDelete(ctx context.Context, d *schema.ResourceData, m interf return nil } -func resourceComputeExists(ctx context.Context, d *schema.ResourceData, m interface{}) (bool, error) { - // Reminder: according to Terraform rules, this function should not modify its ResourceData argument - log.Debugf("resourceComputeExist: called for Compute name %s, RG ID %d", - d.Get("name").(string), d.Get("rg_id").(int)) - - compFacts, err := utilityComputeCheckPresence(ctx, d, m) - if compFacts == "" { - if err != nil { - return false, err - } - return false, nil - } - return true, nil -} - func ResourceCompute() *schema.Resource { return &schema.Resource{ SchemaVersion: 1, diff --git a/internal/service/cloudapi/kvmvm/utility_compute.go b/internal/service/cloudapi/kvmvm/utility_compute.go index 27fd4bb..0bf64ea 100644 --- a/internal/service/cloudapi/kvmvm/utility_compute.go +++ b/internal/service/cloudapi/kvmvm/utility_compute.go @@ -308,45 +308,3 @@ func utilityComputeCheckPresence(ctx context.Context, d *schema.ResourceData, m return "", nil // there should be no error if Compute does not exist } - -func utilityComputeDetachDisks(ctx context.Context, d *schema.ResourceData, m interface{}) error { - compFacts, err := utilityComputeCheckPresence(ctx, d, m) - if compFacts == "" { - if err != nil { - return err - } - // the target Compute does not exist - in this case according to Terraform best practice - // we exit from Destroy method without error - return nil - } - - c := m.(*controller.ControllerCfg) - - model := ComputeGetResp{} - log.Debugf("resourceComputeDelete: ready to unmarshal string %s", compFacts) - err = json.Unmarshal([]byte(compFacts), &model) - - if err != nil && len(model.Disks) > 0 { - // prepare to detach data disks from compute - do it only if compFacts unmarshalled - // properly and the resulting model contains non-empty Disks list - for _, diskFacts := range model.Disks { - if diskFacts.Type == "B" { - // boot disk is never detached on compute delete - continue - } - - log.Debugf("utilityComputeDetachDisks: ready to detach data disk ID %d from compute ID %s", diskFacts.ID, d.Id()) - - detachParams := &url.Values{} - detachParams.Add("computeId", d.Id()) - detachParams.Add("diskId", fmt.Sprintf("%d", diskFacts.ID)) - - if _, err := c.DecortAPICall(ctx, "POST", ComputeDiskDetachAPI, detachParams); err != nil { - // We do not fail compute deletion on data disk detach errors - log.Errorf("utilityComputeDetachDisks: error when detaching Disk ID %d: %s", diskFacts.ID, err) - } - } - } - - return nil -} diff --git a/internal/service/cloudapi/locations/data_source_locations_url.go b/internal/service/cloudapi/locations/data_source_locations_url.go index b06d55b..9f1eac8 100644 --- a/internal/service/cloudapi/locations/data_source_locations_url.go +++ b/internal/service/cloudapi/locations/data_source_locations_url.go @@ -41,9 +41,8 @@ import ( ) func dataSourceLocationUrlRead(ctx context.Context, d *schema.ResourceData, m interface{}) diag.Diagnostics { - url, err := utilityLocationUrlCheckPresence(ctx, d, m) + url, err := utilityLocationUrlCheckPresence(ctx, m) if err != nil { - return diag.FromErr(err) } diff --git a/internal/service/cloudapi/locations/utility_location_url.go b/internal/service/cloudapi/locations/utility_location_url.go index 9ebc215..8f63879 100644 --- a/internal/service/cloudapi/locations/utility_location_url.go +++ b/internal/service/cloudapi/locations/utility_location_url.go @@ -38,11 +38,9 @@ import ( "github.com/rudecs/terraform-provider-decort/internal/controller" log "github.com/sirupsen/logrus" - - "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" ) -func utilityLocationUrlCheckPresence(ctx context.Context, d *schema.ResourceData, m interface{}) (string, error) { +func utilityLocationUrlCheckPresence(ctx context.Context, m interface{}) (string, error) { c := m.(*controller.ControllerCfg) log.Debugf("utilityLocationUrlCheckPresence: load locations list") @@ -54,7 +52,7 @@ func utilityLocationUrlCheckPresence(ctx context.Context, d *schema.ResourceData location := new(string) err = json.Unmarshal([]byte(locationUrl), location) if err != nil { - return "", nil + return "", err } return *location, nil diff --git a/internal/service/cloudapi/pfw/resource_pfw.go b/internal/service/cloudapi/pfw/resource_pfw.go index 199187b..70b3e75 100644 --- a/internal/service/cloudapi/pfw/resource_pfw.go +++ b/internal/service/cloudapi/pfw/resource_pfw.go @@ -122,20 +122,6 @@ func resourcePfwDelete(ctx context.Context, d *schema.ResourceData, m interface{ return nil } -func resourcePfwExists(ctx context.Context, d *schema.ResourceData, m interface{}) (bool, error) { - log.Debugf("resourcePfwExists: called for compute %d, rule %s", d.Get("compute_id").(int), d.Id()) - - pfw, err := utilityPfwCheckPresence(ctx, d, m) - if pfw == nil { - if err != nil { - return false, err - } - return false, nil - } - - return true, nil -} - func resourcePfwSchemaMake() map[string]*schema.Schema { return map[string]*schema.Schema{ "compute_id": { diff --git a/internal/service/cloudapi/rg/resource_rg.go b/internal/service/cloudapi/rg/resource_rg.go index d893334..09334ba 100644 --- a/internal/service/cloudapi/rg/resource_rg.go +++ b/internal/service/cloudapi/rg/resource_rg.go @@ -297,18 +297,6 @@ func resourceResgroupDelete(ctx context.Context, d *schema.ResourceData, m inter return nil } -func resourceResgroupExists(ctx context.Context, d *schema.ResourceData, m interface{}) (bool, error) { - // Reminder: according to Terraform rules, this function should NOT modify ResourceData argument - rg_facts, err := utilityResgroupCheckPresence(ctx, d, m) - if rg_facts == "" { - if err != nil { - return false, err - } - return false, nil - } - return true, nil -} - func ResourceResgroup() *schema.Resource { return &schema.Resource{ SchemaVersion: 1, diff --git a/internal/service/cloudapi/snapshot/resource_snapshot.go b/internal/service/cloudapi/snapshot/resource_snapshot.go index 9a8fbc7..2169720 100644 --- a/internal/service/cloudapi/snapshot/resource_snapshot.go +++ b/internal/service/cloudapi/snapshot/resource_snapshot.go @@ -101,18 +101,6 @@ func resourceSnapshotDelete(ctx context.Context, d *schema.ResourceData, m inter return nil } -func resourceSnapshotExists(ctx context.Context, d *schema.ResourceData, m interface{}) (bool, error) { - snapshot, err := utilitySnapshotCheckPresence(ctx, d, m) - if err != nil { - return false, err - } - if snapshot == nil { - return false, nil - } - - return true, nil -} - func resourceSnapshotEdit(ctx context.Context, d *schema.ResourceData, m interface{}) diag.Diagnostics { if d.HasChange("rollback") { if d.Get("rollback").(bool) { diff --git a/internal/service/cloudapi/vins/resource_vins.go b/internal/service/cloudapi/vins/resource_vins.go index 22729f6..a394b87 100644 --- a/internal/service/cloudapi/vins/resource_vins.go +++ b/internal/service/cloudapi/vins/resource_vins.go @@ -210,21 +210,6 @@ func resourceVinsDelete(ctx context.Context, d *schema.ResourceData, m interface return nil } -func resourceVinsExists(ctx context.Context, d *schema.ResourceData, m interface{}) (bool, error) { - // Reminder: according to Terraform rules, this function should not modify its ResourceData argument - log.Debugf("resourceVinsExists: called for ViNS name %s, Account ID %d, RG ID %d", - d.Get("name").(string), d.Get("account_id").(int), d.Get("rg_id").(int)) - - vinsFacts, err := utilityVinsCheckPresence(ctx, d, m) - if vinsFacts == "" { - if err != nil { - return false, err - } - return false, nil - } - return true, nil -} - func resourceVinsSchemaMake() map[string]*schema.Schema { rets := map[string]*schema.Schema{ "name": { diff --git a/internal/service/cloudbroker/account/api.go b/internal/service/cloudbroker/account/api.go index 3ed17ed..5e30619 100644 --- a/internal/service/cloudbroker/account/api.go +++ b/internal/service/cloudbroker/account/api.go @@ -49,6 +49,8 @@ const accountListVinsAPI = "/restmachine/cloudbroker/account/listVins" const accountRestoreAPI = "/restmachine/cloudbroker/account/restore" const accountUpdateAPI = "/restmachine/cloudbroker/account/update" const accountUpdateUserAPI = "/restmachine/cloudbroker/account/updateUser" -const accountsEnableAPI = "/restmachine/cloudbroker/account/enableAccounts" -const accountsDisableAPI = "/restmachine/cloudbroker/account/disableAccounts" -const accountsDeleteAPI = "/restmachine/cloudbroker/account/deleteAccounts" + +//currently unused +//const accountsEnableAPI = "/restmachine/cloudbroker/account/enableAccounts" +//const accountsDisableAPI = "/restmachine/cloudbroker/account/disableAccounts" +//const accountsDeleteAPI = "/restmachine/cloudbroker/account/deleteAccounts" diff --git a/internal/service/cloudbroker/account/resource_account.go b/internal/service/cloudbroker/account/resource_account.go index 2647b9d..0c33d51 100644 --- a/internal/service/cloudbroker/account/resource_account.go +++ b/internal/service/cloudbroker/account/resource_account.go @@ -228,20 +228,6 @@ func resourceAccountDelete(ctx context.Context, d *schema.ResourceData, m interf return nil } -func resourceAccountExists(ctx context.Context, d *schema.ResourceData, m interface{}) (bool, error) { - log.Debugf("resourceAccountExists") - - account, err := utilityAccountCheckPresence(ctx, d, m) - if account == nil { - if err != nil { - return false, err - } - return false, nil - } - - return true, nil -} - func resourceAccountEdit(ctx context.Context, d *schema.ResourceData, m interface{}) diag.Diagnostics { log.Debugf("resourceAccountEdit") c := m.(*controller.ControllerCfg) diff --git a/internal/service/cloudbroker/disks/resource_disk.go b/internal/service/cloudbroker/disks/resource_disk.go index 9cb264b..2ab95c4 100644 --- a/internal/service/cloudbroker/disks/resource_disk.go +++ b/internal/service/cloudbroker/disks/resource_disk.go @@ -281,18 +281,6 @@ func resourceDiskDelete(ctx context.Context, d *schema.ResourceData, m interface return nil } -func resourceDiskExists(ctx context.Context, d *schema.ResourceData, m interface{}) (bool, error) { - - diskFacts, err := utilityDiskCheckPresence(ctx, d, m) - if diskFacts == nil { - if err != nil { - return false, err - } - return false, nil - } - return true, nil -} - func resourceDiskSchemaMake() map[string]*schema.Schema { rets := map[string]*schema.Schema{ "account_id": { diff --git a/internal/service/cloudbroker/image/resource_image.go b/internal/service/cloudbroker/image/resource_image.go index b578709..8868b2e 100644 --- a/internal/service/cloudbroker/image/resource_image.go +++ b/internal/service/cloudbroker/image/resource_image.go @@ -211,20 +211,6 @@ func resourceImageDelete(ctx context.Context, d *schema.ResourceData, m interfac return nil } -func resourceImageExists(ctx context.Context, d *schema.ResourceData, m interface{}) (bool, error) { - log.Debugf("resourceImageExists: called for %s, id: %s", d.Get("name").(string), d.Id()) - - image, err := utilityImageCheckPresence(ctx, d, m) - if image == nil { - if err != nil { - return false, err - } - return false, nil - } - - return true, nil -} - func resourceImageEditName(ctx context.Context, d *schema.ResourceData, m interface{}) error { log.Debugf("resourceImageEditName: called for %s, id: %s", d.Get("name").(string), d.Id()) c := m.(*controller.ControllerCfg) diff --git a/internal/service/cloudbroker/k8s/resource_k8s.go b/internal/service/cloudbroker/k8s/resource_k8s.go index a7f6301..99dca28 100644 --- a/internal/service/cloudbroker/k8s/resource_k8s.go +++ b/internal/service/cloudbroker/k8s/resource_k8s.go @@ -274,17 +274,6 @@ func resourceK8sDelete(ctx context.Context, d *schema.ResourceData, m interface{ return nil } -func resourceK8sExists(ctx context.Context, d *schema.ResourceData, m interface{}) (bool, error) { - log.Debugf("resourceK8sExists: called with id %s, rg %d", d.Id(), d.Get("rg_id").(int)) - - k8s, err := utilityK8sCheckPresence(ctx, d, m) - if k8s == nil { - return false, err - } - - return true, nil -} - func resourceK8sSchemaMake() map[string]*schema.Schema { return map[string]*schema.Schema{ "name": { diff --git a/internal/service/cloudbroker/k8s/resource_k8s_wg.go b/internal/service/cloudbroker/k8s/resource_k8s_wg.go index d1eeafb..b167d7d 100644 --- a/internal/service/cloudbroker/k8s/resource_k8s_wg.go +++ b/internal/service/cloudbroker/k8s/resource_k8s_wg.go @@ -169,20 +169,6 @@ func resourceK8sWgDelete(ctx context.Context, d *schema.ResourceData, m interfac return nil } -func resourceK8sWgExists(ctx context.Context, d *schema.ResourceData, m interface{}) (bool, error) { - log.Debugf("resourceK8sWgExists: called with k8s id %d", d.Get("k8s_id").(int)) - - wg, err := utilityK8sWgCheckPresence(ctx, d, m) - if wg == nil { - if err != nil { - return false, err - } - return false, nil - } - - return true, nil -} - func resourceK8sWgSchemaMake() map[string]*schema.Schema { return map[string]*schema.Schema{ "k8s_id": { diff --git a/internal/service/cloudbroker/kvmvm/data_source_compute.go b/internal/service/cloudbroker/kvmvm/data_source_compute.go index 4622b2b..2999e3b 100644 --- a/internal/service/cloudbroker/kvmvm/data_source_compute.go +++ b/internal/service/cloudbroker/kvmvm/data_source_compute.go @@ -34,7 +34,6 @@ package kvmvm import ( "context" "encoding/json" - "errors" "fmt" // "net/url" @@ -77,44 +76,15 @@ func parseComputeDisksToExtraDisks(disks []DiskRecord) []interface{} { return result } -func parseBootDiskSize(disks []DiskRecord) int { - // this return value will be used to d.Set("boot_disk_size",) item of dataSourceCompute schema - if len(disks) == 0 { - return 0 - } - - for _, value := range disks { - if value.Type == "B" { - return value.SizeMax - } - } - - return 0 -} - -func parseBootDiskId(disks []DiskRecord) uint { - // this return value will be used to d.Set("boot_disk_id",) item of dataSourceCompute schema - if len(disks) == 0 { - return 0 - } - - for _, value := range disks { - if value.Type == "B" { - return value.ID - } - } - - return 0 -} - -func findBootDisk(disks []DiskRecord) (*DiskRecord, error) { +func findBootDisk(disks []DiskRecord) *DiskRecord { for _, d := range disks { if d.Type == "B" { - return &d, nil + return &d } } - return nil, errors.New("boot disk not found") + // some computes don't have a boot disk, so... + return &DiskRecord{} } // Parse the list of interfaces from compute/get response into a list of networks @@ -181,10 +151,7 @@ func flattenCompute(d *schema.ResourceData, compFacts string) error { d.Set("started", false) } - bootDisk, err := findBootDisk(model.Disks) - if err != nil { - return err - } + bootDisk := findBootDisk(model.Disks) d.Set("boot_disk_size", bootDisk.SizeMax) d.Set("boot_disk_id", bootDisk.ID) // we may need boot disk ID in resize operations diff --git a/internal/service/cloudbroker/kvmvm/resource_compute.go b/internal/service/cloudbroker/kvmvm/resource_compute.go index 2d6c2a3..6bf5c49 100644 --- a/internal/service/cloudbroker/kvmvm/resource_compute.go +++ b/internal/service/cloudbroker/kvmvm/resource_compute.go @@ -33,7 +33,6 @@ package kvmvm import ( "context" - "encoding/json" "fmt" "net/url" "strconv" @@ -129,6 +128,21 @@ func resourceComputeCreate(ctx context.Context, d *schema.ResourceData, m interf d.SetId(apiResp) // update ID of the resource to tell Terraform that the resource exists, albeit partially compId, _ := strconv.Atoi(apiResp) + cleanup := false + defer func() { + if cleanup { + urlValues := &url.Values{} + urlValues.Add("computeId", d.Id()) + urlValues.Add("permanently", "1") + urlValues.Add("detachDisks", "1") + + if _, err := c.DecortAPICall(ctx, "POST", ComputeDeleteAPI, urlValues); err != nil { + log.Errorf("resourceComputeCreate: could not delete compute after failed creation: %v", err) + } + d.SetId("") + } + }() + log.Debugf("resourceComputeCreate: new simple Compute ID %d, name %s created", compId, d.Get("name").(string)) // Configure data disks if any @@ -139,6 +153,7 @@ func resourceComputeCreate(ctx context.Context, d *schema.ResourceData, m interf err = utilityComputeExtraDisksConfigure(ctx, d, m, false) // do_delta=false, as we are working on a new compute if err != nil { log.Errorf("resourceComputeCreate: error when attaching extra disk(s) to a new Compute ID %d: %v", compId, err) + cleanup = true return diag.FromErr(err) } } @@ -149,6 +164,7 @@ func resourceComputeCreate(ctx context.Context, d *schema.ResourceData, m interf err = utilityComputeNetworksConfigure(ctx, d, m, false) // do_delta=false, as we are working on a new compute if err != nil { log.Errorf("resourceComputeCreate: error when attaching networks to a new Compute ID %d: %s", compId, err) + cleanup = true return diag.FromErr(err) } } @@ -160,6 +176,7 @@ func resourceComputeCreate(ctx context.Context, d *schema.ResourceData, m interf reqValues.Add("computeId", fmt.Sprintf("%d", compId)) log.Debugf("resourceComputeCreate: starting Compute ID %d after completing its resource configuration", compId) if _, err := c.DecortAPICall(ctx, "POST", ComputeStartAPI, reqValues); err != nil { + cleanup = true return diag.FromErr(err) } } @@ -297,72 +314,20 @@ func resourceComputeDelete(ctx context.Context, d *schema.ResourceData, m interf log.Debugf("resourceComputeDelete: called for Compute name %s, RG ID %d", d.Get("name").(string), d.Get("rg_id").(int)) - compFacts, err := utilityComputeCheckPresence(ctx, d, m) - if compFacts == "" { - if err != nil { - return diag.FromErr(err) - } - // the target Compute does not exist - in this case according to Terraform best practice - // we exit from Destroy method without error - return nil - } - c := m.(*controller.ControllerCfg) - model := ComputeGetResp{} - log.Debugf("resourceComputeDelete: ready to unmarshal string %s", compFacts) - err = json.Unmarshal([]byte(compFacts), &model) - if err == nil && len(model.Disks) > 0 { - // prepare to detach data disks from compute - do it only if compFacts unmarshalled - // properly and the resulting model contains non-empty Disks list - for _, diskFacts := range model.Disks { - if diskFacts.Type == "B" { - // boot disk is never detached on compute delete - continue - } - - log.Debugf("resourceComputeDelete: ready to detach data disk ID %d from compute ID %s", diskFacts.ID, d.Id()) - - detachParams := &url.Values{} - detachParams.Add("computeId", d.Id()) - detachParams.Add("diskId", fmt.Sprintf("%d", diskFacts.ID)) - - _, err = c.DecortAPICall(ctx, "POST", ComputeDiskDetachAPI, detachParams) - if err != nil { - // We do not fail compute deletion on data disk detach errors - log.Errorf("resourceComputeDelete: error when detaching Disk ID %d: %s", diskFacts.ID, err) - } - } - } - params := &url.Values{} params.Add("computeId", d.Id()) params.Add("permanently", "1") - // TODO: this is for the upcoming API update - params.Add("detachdisks", "1") + params.Add("detachDisks", "1") - _, err = c.DecortAPICall(ctx, "POST", ComputeDeleteAPI, params) - if err != nil { + if _, err := c.DecortAPICall(ctx, "POST", ComputeDeleteAPI, params); err != nil { return diag.FromErr(err) } return nil } -func resourceComputeExists(ctx context.Context, d *schema.ResourceData, m interface{}) (bool, error) { - // Reminder: according to Terraform rules, this function should not modify its ResourceData argument - log.Debugf("resourceComputeExist: called for Compute name %s, RG ID %d", - d.Get("name").(string), d.Get("rg_id").(int)) - - compFacts, err := utilityComputeCheckPresence(ctx, d, m) - if compFacts == "" { - if err != nil { - return false, err - } - return false, nil - } - return true, nil -} - func ResourceCompute() *schema.Resource { return &schema.Resource{ SchemaVersion: 1, diff --git a/internal/service/cloudbroker/pcidevice/data_source_pcidevice_list.go b/internal/service/cloudbroker/pcidevice/data_source_pcidevice_list.go index ce9baef..3933790 100644 --- a/internal/service/cloudbroker/pcidevice/data_source_pcidevice_list.go +++ b/internal/service/cloudbroker/pcidevice/data_source_pcidevice_list.go @@ -64,7 +64,7 @@ func flattenPcideviceList(pl PcideviceList) []map[string]interface{} { } func dataSourcePcideviceListRead(ctx context.Context, d *schema.ResourceData, m interface{}) diag.Diagnostics { - pcideviceList, err := utilityPcideviceListCheckPresence(ctx, d, m) + pcideviceList, err := utilityPcideviceListCheckPresence(ctx, m) if err != nil { return diag.FromErr(err) } diff --git a/internal/service/cloudbroker/pcidevice/resource_pcidevice.go b/internal/service/cloudbroker/pcidevice/resource_pcidevice.go index ebcd5dc..1fcb0d9 100644 --- a/internal/service/cloudbroker/pcidevice/resource_pcidevice.go +++ b/internal/service/cloudbroker/pcidevice/resource_pcidevice.go @@ -115,18 +115,6 @@ func resourcePcideviceDelete(ctx context.Context, d *schema.ResourceData, m inte return nil } -func resourcePcideviceExists(ctx context.Context, d *schema.ResourceData, m interface{}) (bool, error) { - pcidevice, err := utilityPcideviceCheckPresence(ctx, d, m) - if err != nil { - return false, err - } - if pcidevice == nil { - return false, nil - } - - return true, nil -} - func resourcePcideviceEdit(ctx context.Context, d *schema.ResourceData, m interface{}) diag.Diagnostics { if d.HasChange("enable") { state := d.Get("enable").(bool) diff --git a/internal/service/cloudbroker/pcidevice/utility_pcidevice.go b/internal/service/cloudbroker/pcidevice/utility_pcidevice.go index 9b22947..3ace283 100644 --- a/internal/service/cloudbroker/pcidevice/utility_pcidevice.go +++ b/internal/service/cloudbroker/pcidevice/utility_pcidevice.go @@ -39,7 +39,7 @@ import ( ) func utilityPcideviceCheckPresence(ctx context.Context, d *schema.ResourceData, m interface{}) (*Pcidevice, error) { - pcideviceList, err := utilityPcideviceListCheckPresence(ctx, d, m) + pcideviceList, err := utilityPcideviceListCheckPresence(ctx, m) if err != nil { return nil, err } diff --git a/internal/service/cloudbroker/pcidevice/utility_pcidevice_list.go b/internal/service/cloudbroker/pcidevice/utility_pcidevice_list.go index ada9adc..97e65b5 100644 --- a/internal/service/cloudbroker/pcidevice/utility_pcidevice_list.go +++ b/internal/service/cloudbroker/pcidevice/utility_pcidevice_list.go @@ -36,11 +36,10 @@ import ( "encoding/json" "net/url" - "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" "github.com/rudecs/terraform-provider-decort/internal/controller" ) -func utilityPcideviceListCheckPresence(ctx context.Context, d *schema.ResourceData, m interface{}) (PcideviceList, error) { +func utilityPcideviceListCheckPresence(ctx context.Context, m interface{}) (PcideviceList, error) { pcideviceList := PcideviceList{} c := m.(*controller.ControllerCfg) urlValues := &url.Values{} diff --git a/internal/service/cloudbroker/pfw/resource_pfw.go b/internal/service/cloudbroker/pfw/resource_pfw.go index 199187b..70b3e75 100644 --- a/internal/service/cloudbroker/pfw/resource_pfw.go +++ b/internal/service/cloudbroker/pfw/resource_pfw.go @@ -122,20 +122,6 @@ func resourcePfwDelete(ctx context.Context, d *schema.ResourceData, m interface{ return nil } -func resourcePfwExists(ctx context.Context, d *schema.ResourceData, m interface{}) (bool, error) { - log.Debugf("resourcePfwExists: called for compute %d, rule %s", d.Get("compute_id").(int), d.Id()) - - pfw, err := utilityPfwCheckPresence(ctx, d, m) - if pfw == nil { - if err != nil { - return false, err - } - return false, nil - } - - return true, nil -} - func resourcePfwSchemaMake() map[string]*schema.Schema { return map[string]*schema.Schema{ "compute_id": { diff --git a/internal/service/cloudbroker/rg/resource_rg.go b/internal/service/cloudbroker/rg/resource_rg.go index d893334..09334ba 100644 --- a/internal/service/cloudbroker/rg/resource_rg.go +++ b/internal/service/cloudbroker/rg/resource_rg.go @@ -297,18 +297,6 @@ func resourceResgroupDelete(ctx context.Context, d *schema.ResourceData, m inter return nil } -func resourceResgroupExists(ctx context.Context, d *schema.ResourceData, m interface{}) (bool, error) { - // Reminder: according to Terraform rules, this function should NOT modify ResourceData argument - rg_facts, err := utilityResgroupCheckPresence(ctx, d, m) - if rg_facts == "" { - if err != nil { - return false, err - } - return false, nil - } - return true, nil -} - func ResourceResgroup() *schema.Resource { return &schema.Resource{ SchemaVersion: 1, diff --git a/internal/service/cloudbroker/sep/resource_sep.go b/internal/service/cloudbroker/sep/resource_sep.go index f6561f7..9bc2fff 100644 --- a/internal/service/cloudbroker/sep/resource_sep.go +++ b/internal/service/cloudbroker/sep/resource_sep.go @@ -160,20 +160,6 @@ func resourceSepDelete(ctx context.Context, d *schema.ResourceData, m interface{ return nil } -func resourceSepExists(ctx context.Context, d *schema.ResourceData, m interface{}) (bool, error) { - log.Debugf("resourceSepExists: called for %s, id: %d", d.Get("name").(string), d.Get("sep_id").(int)) - - sepDes, err := utilitySepCheckPresence(ctx, d, m) - if sepDes == nil { - if err != nil { - return false, err - } - return false, nil - } - - return true, nil -} - func resourceSepEdit(ctx context.Context, d *schema.ResourceData, m interface{}) diag.Diagnostics { log.Debugf("resourceSepEdit: called for %s, id: %d", d.Get("name").(string), d.Get("sep_id").(int)) c := m.(*controller.ControllerCfg) diff --git a/internal/service/cloudbroker/snapshot/resource_snapshot.go b/internal/service/cloudbroker/snapshot/resource_snapshot.go index 9a8fbc7..2169720 100644 --- a/internal/service/cloudbroker/snapshot/resource_snapshot.go +++ b/internal/service/cloudbroker/snapshot/resource_snapshot.go @@ -101,18 +101,6 @@ func resourceSnapshotDelete(ctx context.Context, d *schema.ResourceData, m inter return nil } -func resourceSnapshotExists(ctx context.Context, d *schema.ResourceData, m interface{}) (bool, error) { - snapshot, err := utilitySnapshotCheckPresence(ctx, d, m) - if err != nil { - return false, err - } - if snapshot == nil { - return false, nil - } - - return true, nil -} - func resourceSnapshotEdit(ctx context.Context, d *schema.ResourceData, m interface{}) diag.Diagnostics { if d.HasChange("rollback") { if d.Get("rollback").(bool) { diff --git a/internal/service/cloudbroker/vins/resource_vins.go b/internal/service/cloudbroker/vins/resource_vins.go index 22729f6..a394b87 100644 --- a/internal/service/cloudbroker/vins/resource_vins.go +++ b/internal/service/cloudbroker/vins/resource_vins.go @@ -210,21 +210,6 @@ func resourceVinsDelete(ctx context.Context, d *schema.ResourceData, m interface return nil } -func resourceVinsExists(ctx context.Context, d *schema.ResourceData, m interface{}) (bool, error) { - // Reminder: according to Terraform rules, this function should not modify its ResourceData argument - log.Debugf("resourceVinsExists: called for ViNS name %s, Account ID %d, RG ID %d", - d.Get("name").(string), d.Get("account_id").(int), d.Get("rg_id").(int)) - - vinsFacts, err := utilityVinsCheckPresence(ctx, d, m) - if vinsFacts == "" { - if err != nil { - return false, err - } - return false, nil - } - return true, nil -} - func resourceVinsSchemaMake() map[string]*schema.Schema { rets := map[string]*schema.Schema{ "name": { From 818875976c4c32f226546ba7c2b2b4815390b80e Mon Sep 17 00:00:00 2001 From: stSolo Date: Mon, 25 Jul 2022 19:45:07 +0300 Subject: [PATCH 48/51] Move vgpu from cloudapi to cloudbroker --- internal/provider/cloudapi/data_sources_map.go | 2 -- internal/provider/cloudbroker/data_sources_map.go | 4 ++++ internal/service/{cloudapi => cloudbroker}/vgpu/api.go | 0 .../{cloudapi => cloudbroker}/vgpu/data_source_vgpu.go | 0 internal/service/{cloudapi => cloudbroker}/vgpu/models.go | 0 .../service/{cloudapi => cloudbroker}/vgpu/utility_vgpu.go | 0 6 files changed, 4 insertions(+), 2 deletions(-) rename internal/service/{cloudapi => cloudbroker}/vgpu/api.go (100%) rename internal/service/{cloudapi => cloudbroker}/vgpu/data_source_vgpu.go (100%) rename internal/service/{cloudapi => cloudbroker}/vgpu/models.go (100%) rename internal/service/{cloudapi => cloudbroker}/vgpu/utility_vgpu.go (100%) diff --git a/internal/provider/cloudapi/data_sources_map.go b/internal/provider/cloudapi/data_sources_map.go index e1103a1..e7aad67 100644 --- a/internal/provider/cloudapi/data_sources_map.go +++ b/internal/provider/cloudapi/data_sources_map.go @@ -30,7 +30,6 @@ import ( "github.com/rudecs/terraform-provider-decort/internal/service/cloudapi/locations" "github.com/rudecs/terraform-provider-decort/internal/service/cloudapi/rg" "github.com/rudecs/terraform-provider-decort/internal/service/cloudapi/snapshot" - "github.com/rudecs/terraform-provider-decort/internal/service/cloudapi/vgpu" "github.com/rudecs/terraform-provider-decort/internal/service/cloudapi/vins" ) @@ -41,7 +40,6 @@ func NewDataSourcesMap() map[string]*schema.Resource { "decort_kvmvm": kvmvm.DataSourceCompute(), "decort_vins": vins.DataSourceVins(), "decort_snapshot_list": snapshot.DataSourceSnapshotList(), - "decort_vgpu": vgpu.DataSourceVGPU(), "decort_disk": disks.DataSourceDisk(), "decort_disk_list": disks.DataSourceDiskList(), "decort_rg_list": rg.DataSourceRgList(), diff --git a/internal/provider/cloudbroker/data_sources_map.go b/internal/provider/cloudbroker/data_sources_map.go index 82e74d5..d8e4293 100644 --- a/internal/provider/cloudbroker/data_sources_map.go +++ b/internal/provider/cloudbroker/data_sources_map.go @@ -26,7 +26,9 @@ import ( "github.com/rudecs/terraform-provider-decort/internal/service/cloudbroker/grid" "github.com/rudecs/terraform-provider-decort/internal/service/cloudbroker/image" "github.com/rudecs/terraform-provider-decort/internal/service/cloudbroker/pcidevice" + "github.com/rudecs/terraform-provider-decort/internal/service/cloudbroker/rg" "github.com/rudecs/terraform-provider-decort/internal/service/cloudbroker/sep" + "github.com/rudecs/terraform-provider-decort/internal/service/cloudbroker/vgpu" ) func NewDataSourcesMap() map[string]*schema.Resource { @@ -55,6 +57,8 @@ func NewDataSourcesMap() map[string]*schema.Resource { "decort_sep_disk_list": sep.DataSourceSepDiskList(), "decort_sep_config": sep.DataSourceSepConfig(), "decort_sep_pool": sep.DataSourceSepPool(), + "decort_vgpu": vgpu.DataSourceVGPU(), + "decort_rg_list": rg.DataSourceRgList(), // "decort_pfw": dataSourcePfw(), } diff --git a/internal/service/cloudapi/vgpu/api.go b/internal/service/cloudbroker/vgpu/api.go similarity index 100% rename from internal/service/cloudapi/vgpu/api.go rename to internal/service/cloudbroker/vgpu/api.go diff --git a/internal/service/cloudapi/vgpu/data_source_vgpu.go b/internal/service/cloudbroker/vgpu/data_source_vgpu.go similarity index 100% rename from internal/service/cloudapi/vgpu/data_source_vgpu.go rename to internal/service/cloudbroker/vgpu/data_source_vgpu.go diff --git a/internal/service/cloudapi/vgpu/models.go b/internal/service/cloudbroker/vgpu/models.go similarity index 100% rename from internal/service/cloudapi/vgpu/models.go rename to internal/service/cloudbroker/vgpu/models.go diff --git a/internal/service/cloudapi/vgpu/utility_vgpu.go b/internal/service/cloudbroker/vgpu/utility_vgpu.go similarity index 100% rename from internal/service/cloudapi/vgpu/utility_vgpu.go rename to internal/service/cloudbroker/vgpu/utility_vgpu.go From bdcb1ab532e3e3705a235cbada07bccf4a33f7bb Mon Sep 17 00:00:00 2001 From: kjubybot Date: Wed, 27 Jul 2022 12:28:34 +0300 Subject: [PATCH 49/51] updated dependencies and go version --- go.mod | 70 +++- go.sum | 514 +++++------------------------- internal/controller/controller.go | 2 +- 3 files changed, 140 insertions(+), 446 deletions(-) diff --git a/go.mod b/go.mod index 1028826..a35ed33 100644 --- a/go.mod +++ b/go.mod @@ -1,12 +1,70 @@ module github.com/rudecs/terraform-provider-decort -go 1.15 +go 1.18 require ( - github.com/dgrijalva/jwt-go v3.2.0+incompatible + github.com/golang-jwt/jwt/v4 v4.4.2 github.com/google/uuid v1.3.0 - github.com/hashicorp/terraform-plugin-docs v0.5.1 - github.com/hashicorp/terraform-plugin-sdk/v2 v2.17.0 // indirect - github.com/sirupsen/logrus v1.7.0 - golang.org/x/net v0.0.0-20210326060303-6b1517762897 // indirect + github.com/hashicorp/terraform-plugin-docs v0.13.0 + github.com/hashicorp/terraform-plugin-sdk/v2 v2.19.0 + github.com/sirupsen/logrus v1.9.0 + golang.org/x/net v0.0.0-20211112202133-69e39bad7dc2 +) + +require ( + github.com/Masterminds/goutils v1.1.1 // indirect + github.com/Masterminds/semver/v3 v3.1.1 // indirect + github.com/Masterminds/sprig/v3 v3.2.2 // indirect + github.com/agext/levenshtein v1.2.2 // indirect + github.com/apparentlymart/go-textseg/v13 v13.0.0 // indirect + github.com/armon/go-radix v1.0.0 // indirect + github.com/bgentry/speakeasy v0.1.0 // indirect + github.com/fatih/color v1.13.0 // indirect + github.com/golang/protobuf v1.5.2 // indirect + github.com/google/go-cmp v0.5.8 // indirect + github.com/hashicorp/errwrap v1.1.0 // indirect + github.com/hashicorp/go-checkpoint v0.5.0 // indirect + github.com/hashicorp/go-cleanhttp v0.5.2 // indirect + github.com/hashicorp/go-cty v1.4.1-0.20200414143053-d3edf31b6320 // indirect + github.com/hashicorp/go-hclog v1.2.1 // indirect + github.com/hashicorp/go-multierror v1.1.1 // indirect + github.com/hashicorp/go-plugin v1.4.4 // indirect + github.com/hashicorp/go-uuid v1.0.3 // indirect + github.com/hashicorp/go-version v1.6.0 // indirect + github.com/hashicorp/hc-install v0.4.0 // indirect + github.com/hashicorp/hcl/v2 v2.13.0 // indirect + github.com/hashicorp/logutils v1.0.0 // indirect + github.com/hashicorp/terraform-exec v0.17.2 // indirect + github.com/hashicorp/terraform-json v0.14.0 // indirect + github.com/hashicorp/terraform-plugin-go v0.12.0 // indirect + github.com/hashicorp/terraform-plugin-log v0.6.0 // indirect + github.com/hashicorp/terraform-registry-address v0.0.0-20220623143253-7d51757b572c // indirect + github.com/hashicorp/terraform-svchost v0.0.0-20200729002733-f050f53b9734 // indirect + github.com/hashicorp/yamux v0.0.0-20181012175058-2f1d1f20f75d // indirect + github.com/huandu/xstrings v1.3.2 // indirect + github.com/imdario/mergo v0.3.13 // indirect + github.com/mattn/go-colorable v0.1.12 // indirect + github.com/mattn/go-isatty v0.0.14 // indirect + github.com/mitchellh/cli v1.1.4 // indirect + github.com/mitchellh/copystructure v1.2.0 // indirect + github.com/mitchellh/go-testing-interface v1.14.1 // indirect + github.com/mitchellh/go-wordwrap v1.0.0 // indirect + github.com/mitchellh/mapstructure v1.5.0 // indirect + github.com/mitchellh/reflectwalk v1.0.2 // indirect + github.com/oklog/run v1.0.0 // indirect + github.com/posener/complete v1.2.3 // indirect + github.com/russross/blackfriday v1.6.0 // indirect + github.com/shopspring/decimal v1.3.1 // indirect + github.com/spf13/cast v1.5.0 // indirect + github.com/vmihailenco/msgpack v4.0.4+incompatible // indirect + github.com/vmihailenco/msgpack/v4 v4.3.12 // indirect + github.com/vmihailenco/tagparser v0.1.1 // indirect + github.com/zclconf/go-cty v1.10.0 // indirect + golang.org/x/crypto v0.0.0-20220622213112-05595931fe9d // indirect + golang.org/x/sys v0.0.0-20220715151400-c0bba94af5f8 // indirect + golang.org/x/text v0.3.7 // indirect + google.golang.org/appengine v1.6.6 // indirect + google.golang.org/genproto v0.0.0-20200711021454-869866162049 // indirect + google.golang.org/grpc v1.48.0 // indirect + google.golang.org/protobuf v1.28.0 // indirect ) diff --git a/go.sum b/go.sum index 66dcc19..e95fd18 100644 --- a/go.sum +++ b/go.sum @@ -1,45 +1,14 @@ cloud.google.com/go v0.26.0/go.mod h1:aQUYkXzVsufM+DwF1aE+0xfcU+56JwCaLick0ClmMTw= cloud.google.com/go v0.34.0/go.mod h1:aQUYkXzVsufM+DwF1aE+0xfcU+56JwCaLick0ClmMTw= -cloud.google.com/go v0.38.0/go.mod h1:990N+gfupTy94rShfmMCWGDn0LpTmnzTp2qbd1dvSRU= -cloud.google.com/go v0.44.1/go.mod h1:iSa0KzasP4Uvy3f1mN/7PiObzGgflwredwwASm/v6AU= -cloud.google.com/go v0.44.2/go.mod h1:60680Gw3Yr4ikxnPRS/oxxkBccT6SA1yMk63TGekxKY= -cloud.google.com/go v0.45.1/go.mod h1:RpBamKRgapWJb87xiFSdk4g1CME7QZg3uwTez+TSTjc= -cloud.google.com/go v0.46.3/go.mod h1:a6bKKbmY7er1mI7TEI4lsAkts/mkhTSZK8w33B4RAg0= -cloud.google.com/go v0.50.0/go.mod h1:r9sluTvynVuxRIOHXQEHMFffphuXHOMZMycpNR5e6To= -cloud.google.com/go v0.52.0/go.mod h1:pXajvRH/6o3+F9jDHZWQ5PbGhn+o8w9qiu/CffaVdO4= -cloud.google.com/go v0.53.0/go.mod h1:fp/UouUEsRkN6ryDKNW/Upv/JBKnv6WDthjR6+vze6M= -cloud.google.com/go v0.54.0/go.mod h1:1rq2OEkV3YMf6n/9ZvGWI3GWw0VoqH/1x2nd8Is/bPc= -cloud.google.com/go v0.56.0/go.mod h1:jr7tqZxxKOVYizybht9+26Z/gUq7tiRzu+ACVAMbKVk= -cloud.google.com/go v0.57.0/go.mod h1:oXiQ6Rzq3RAkkY7N6t3TcE6jE+CIBBbA36lwQ1JyzZs= -cloud.google.com/go v0.61.0 h1:NLQf5e1OMspfNT1RAHOB3ublr1TW3YTXO8OiWwVjK2U= -cloud.google.com/go v0.61.0/go.mod h1:XukKJg4Y7QsUu0Hxg3qQKUWR4VuWivmyMK2+rUyxAqw= -cloud.google.com/go/bigquery v1.0.1/go.mod h1:i/xbL2UlR5RvWAURpBYZTtm/cXjCha9lbfbpx4poX+o= -cloud.google.com/go/bigquery v1.3.0/go.mod h1:PjpwJnslEMmckchkHFfq+HTD2DmtT67aNFKH1/VBDHE= -cloud.google.com/go/bigquery v1.4.0/go.mod h1:S8dzgnTigyfTmLBfrtrhyYhwRxG72rYxvftPBK2Dvzc= -cloud.google.com/go/bigquery v1.5.0/go.mod h1:snEHRnqQbz117VIFhE8bmtwIDY80NLUZUMb4Nv6dBIg= -cloud.google.com/go/bigquery v1.7.0/go.mod h1://okPTzCYNXSlb24MZs83e2Do+h+VXtc4gLoIoXIAPc= -cloud.google.com/go/bigquery v1.8.0/go.mod h1:J5hqkt3O0uAFnINi6JXValWIb1v0goeZM77hZzJN/fQ= -cloud.google.com/go/datastore v1.0.0/go.mod h1:LXYbyblFSglQ5pkeyhO+Qmw7ukd3C+pD7TKLgZqpHYE= -cloud.google.com/go/datastore v1.1.0/go.mod h1:umbIZjpQpHh4hmRpGhH4tLFup+FVzqBi1b3c64qFpCk= -cloud.google.com/go/pubsub v1.0.1/go.mod h1:R0Gpsv3s54REJCy4fxDixWD93lHJMoZTyQ2kNxGRt3I= -cloud.google.com/go/pubsub v1.1.0/go.mod h1:EwwdRX2sKPjnvnqCa270oGRyludottCI76h+R3AArQw= -cloud.google.com/go/pubsub v1.2.0/go.mod h1:jhfEVHT8odbXTkndysNHCcx0awwzvfOlguIAii9o8iA= -cloud.google.com/go/pubsub v1.3.1/go.mod h1:i+ucay31+CNRpDW4Lu78I4xXG+O1r/MAHgjpRVR+TSU= -cloud.google.com/go/storage v1.0.0/go.mod h1:IhtSnM/ZTZV8YYJWCY8RULGVqBDmpoyjwiyrjsg+URw= -cloud.google.com/go/storage v1.5.0/go.mod h1:tpKbwo567HUNpVclU5sGELwQWBDZ8gh0ZeosJ0Rtdos= -cloud.google.com/go/storage v1.6.0/go.mod h1:N7U0C8pVQ/+NIKOBQyamJIeKQKkZ+mxpohlUTyfDhBk= -cloud.google.com/go/storage v1.8.0/go.mod h1:Wv1Oy7z6Yz3DshWRJFhqM/UCfaWIRTdp0RXyy7KQOVs= -cloud.google.com/go/storage v1.10.0 h1:STgFzyU5/8miMl0//zKh2aQeTyeaUH3WN9bSUiJ09bA= -cloud.google.com/go/storage v1.10.0/go.mod h1:FLPqc6j+Ki4BU591ie1oL6qBQGu2Bl/tZ9ullr3+Kg0= -dmitri.shuralyov.com/gpu/mtl v0.0.0-20190408044501-666a987793e9/go.mod h1:H6x//7gZCb22OMCxBHrMx7a5I7Hp++hsVxbQ4BYO7hU= github.com/BurntSushi/toml v0.3.1/go.mod h1:xHWCNGjB5oqiDr8zfno3MHue2Ht5sIBksp03qcyfWMU= -github.com/BurntSushi/xgb v0.0.0-20160522181843-27f122750802/go.mod h1:IVnqGOEym/WlBOVXweHU+Q+/VP0lqqI8lqeDx9IjBqo= -github.com/Masterminds/goutils v1.1.0 h1:zukEsf/1JZwCMgHiK3GZftabmxiCw4apj3a28RPBiVg= github.com/Masterminds/goutils v1.1.0/go.mod h1:8cTjp+g8YejhMuvIA5y2vz3BpJxksy863GQaJW2MFNU= -github.com/Masterminds/semver v1.5.0 h1:H65muMkzWKEuNDnfl9d70GUjFniHKHRbFPGBuZ3QEww= -github.com/Masterminds/semver v1.5.0/go.mod h1:MB6lktGJrhw8PrUyiEoblNEGEQ+RzHPF078ddwwvV3Y= -github.com/Masterminds/sprig v2.22.0+incompatible h1:z4yfnGrZ7netVz+0EDJ0Wi+5VZCSYp4Z0m2dk6cEM60= -github.com/Masterminds/sprig v2.22.0+incompatible/go.mod h1:y6hNFY5UBTIWBxnzTeuNhlNS5hqE0NB0E6fgfo2Br3o= +github.com/Masterminds/goutils v1.1.1 h1:5nUrii3FMTL5diU80unEVvNevw1nH4+ZV4DSLVJLSYI= +github.com/Masterminds/goutils v1.1.1/go.mod h1:8cTjp+g8YejhMuvIA5y2vz3BpJxksy863GQaJW2MFNU= +github.com/Masterminds/semver/v3 v3.1.1 h1:hLg3sBzpNErnxhQtUy/mmLR2I9foDujNK030IGemrRc= +github.com/Masterminds/semver/v3 v3.1.1/go.mod h1:VPu/7SZ7ePZ3QOrcuXROw5FAcLl4a0cBrbBpGY/8hQs= +github.com/Masterminds/sprig/v3 v3.2.0/go.mod h1:tWhwTbUTndesPNeF0C900vKoq283u6zp4APT9vaF3SI= +github.com/Masterminds/sprig/v3 v3.2.2 h1:17jRggJu518dr3QaafizSXOjKYp94wKfABxUmyxvxX8= +github.com/Masterminds/sprig/v3 v3.2.2/go.mod h1:UoaO7Yp8KlPnJIYWTFkMaqPUYKTfGFPhxNuwnnxkKlk= github.com/Microsoft/go-winio v0.4.14/go.mod h1:qXqCSQ3Xa7+6tgxaGTIe4Kpcdsi+P8jBhyzoq1bpyYA= github.com/Microsoft/go-winio v0.4.16 h1:FtSW/jqD+l4ba5iPBj9CODVtgfYAD8w2wS923g/cFDk= github.com/Microsoft/go-winio v0.4.16/go.mod h1:XB6nPKklQyQ7GC9LdcBEcBl8PF76WugXOPRXwdLnMv0= @@ -47,23 +16,11 @@ github.com/ProtonMail/go-crypto v0.0.0-20210428141323-04723f9f07d7 h1:YoJbenK9C6 github.com/ProtonMail/go-crypto v0.0.0-20210428141323-04723f9f07d7/go.mod h1:z4/9nQmJSSwwds7ejkxaJwO37dru3geImFUdJlaLzQo= github.com/acomagu/bufpipe v1.0.3 h1:fxAGrHZTgQ9w5QqVItgzwj235/uYZYgbXitB+dLupOk= github.com/acomagu/bufpipe v1.0.3/go.mod h1:mxdxdup/WdsKVreO5GpW4+M/1CE2sMG4jeGJ2sYmHc4= -github.com/agext/levenshtein v1.2.1/go.mod h1:JEDfjyjHDjOF/1e4FlBE/PkbqA9OfWu2ki2W0IB5558= github.com/agext/levenshtein v1.2.2 h1:0S/Yg6LYmFJ5stwQeRp6EeOcCbj7xiqQSdNelsXvaqE= github.com/agext/levenshtein v1.2.2/go.mod h1:JEDfjyjHDjOF/1e4FlBE/PkbqA9OfWu2ki2W0IB5558= -github.com/agl/ed25519 v0.0.0-20170116200512-5312a6153412/go.mod h1:WPjqKcmVOxf0XSf3YxCJs6N6AOSrOx3obionmG7T0y0= -github.com/alcortesm/tgz v0.0.0-20161220082320-9c5fe88206d7/go.mod h1:6zEj6s6u/ghQa61ZWa/C2Aw3RkjiTBOix7dkqa1VLIs= -github.com/andybalholm/crlf v0.0.0-20171020200849-670099aa064f/go.mod h1:k8feO4+kXDxro6ErPXBRTJ/ro2mf0SsFG8s7doP9kJE= -github.com/anmitsu/go-shlex v0.0.0-20161002113705-648efa622239 h1:kFOfPq6dUM1hTo4JG6LR5AXSUEsOjtdm0kw0FtQtMJA= github.com/anmitsu/go-shlex v0.0.0-20161002113705-648efa622239/go.mod h1:2FmKhYUyUczH0OGQWaF5ceTx0UBShxjsH6f8oGKYe2c= github.com/antihax/optional v1.0.0/go.mod h1:uupD/76wgC+ih3iEmQUL+0Ugr19nfwCT1kdvxnR2qWY= -github.com/apparentlymart/go-cidr v1.0.1 h1:NmIwLZ/KdsjIUlhf+/Np40atNXm/+lZ5txfTJ/SpF+U= -github.com/apparentlymart/go-cidr v1.0.1/go.mod h1:EBcsNrHc3zQeuaeCeCtQruQm+n9/YjEn/vI25Lg7Gwc= -github.com/apparentlymart/go-cidr v1.1.0 h1:2mAhrMoF+nhXqxTzSZMUzDHkLjmIHC+Zzn4tdgBZjnU= -github.com/apparentlymart/go-cidr v1.1.0/go.mod h1:EBcsNrHc3zQeuaeCeCtQruQm+n9/YjEn/vI25Lg7Gwc= -github.com/apparentlymart/go-dump v0.0.0-20180507223929-23540a00eaa3/go.mod h1:oL81AME2rN47vu18xqj1S1jPIPuN7afo62yKTNn3XMM= github.com/apparentlymart/go-dump v0.0.0-20190214190832-042adf3cf4a0 h1:MzVXffFUye+ZcSR6opIgz9Co7WcDx6ZcY+RjfFHoA0I= -github.com/apparentlymart/go-dump v0.0.0-20190214190832-042adf3cf4a0/go.mod h1:oL81AME2rN47vu18xqj1S1jPIPuN7afo62yKTNn3XMM= -github.com/apparentlymart/go-textseg v1.0.0 h1:rRmlIsPEEhUTIKQb7T++Nz/A5Q6C9IuX2wFoYVvnCs0= github.com/apparentlymart/go-textseg v1.0.0/go.mod h1:z96Txxhf3xSFMPmb5X/1W05FF/Nj9VFpLOpjS5yuumk= github.com/apparentlymart/go-textseg/v12 v12.0.0/go.mod h1:S/4uRK2UtaQttw1GenVJEynmyUenKwP++x/+DdGV/Ec= github.com/apparentlymart/go-textseg/v13 v13.0.0 h1:Y+KvPE1NYz0xl601PVImeQfFyEy6iT90AvPUL1NNfNw= @@ -71,21 +28,11 @@ github.com/apparentlymart/go-textseg/v13 v13.0.0/go.mod h1:ZK2fH7c4NqDTLtiYLvIkE github.com/armon/go-radix v0.0.0-20180808171621-7fddfc383310/go.mod h1:ufUuZ+zHj4x4TnLV4JWEpy2hxWSpsRywHrMgIH9cCH8= github.com/armon/go-radix v1.0.0 h1:F4z6KzEeeQIMeLFa97iZU6vupzoecKdU5TX24SNppXI= github.com/armon/go-radix v1.0.0/go.mod h1:ufUuZ+zHj4x4TnLV4JWEpy2hxWSpsRywHrMgIH9cCH8= -github.com/armon/go-socks5 v0.0.0-20160902184237-e75332964ef5 h1:0CwZNZbxp69SHPdPJAN/hZIm0C4OItdklCFmMRWYpio= github.com/armon/go-socks5 v0.0.0-20160902184237-e75332964ef5/go.mod h1:wHh0iHkYZB8zMSxRWpUBQtwG5a7fFgvEO+odwuTv2gs= -github.com/aws/aws-sdk-go v1.15.78/go.mod h1:E3/ieXAlvM0XWO57iftYVDLLvQ824smPP3ATZkfNZeM= -github.com/aws/aws-sdk-go v1.25.3 h1:uM16hIw9BotjZKMZlX05SN2EFtaWfi/NonPKIARiBLQ= -github.com/aws/aws-sdk-go v1.25.3/go.mod h1:KmX6BPdI08NWTb3/sm4ZGu5ShLoqVDhKgpiN924inxo= -github.com/bgentry/go-netrc v0.0.0-20140422174119-9fd32a8b3d3d h1:xDfNPAt8lFiC1UJrqV3uuy861HCTo708pDMbjHHdCas= -github.com/bgentry/go-netrc v0.0.0-20140422174119-9fd32a8b3d3d/go.mod h1:6QX/PXZ00z/TKoufEY6K/a0k6AhaJrQKdFe6OfVXsa4= github.com/bgentry/speakeasy v0.1.0 h1:ByYyxL9InA1OWqxJqqp2A5pYHUrCiAL6K3J+LKSsQkY= github.com/bgentry/speakeasy v0.1.0/go.mod h1:+zsyZBPWlz7T6j88CTgSN5bM796AkVf0kBD4zp0CCIs= github.com/census-instrumentation/opencensus-proto v0.2.1/go.mod h1:f6KPmirojxKA12rnyqOA5BBL4O983OfeGPqjHWSTneU= github.com/cespare/xxhash/v2 v2.1.1/go.mod h1:VGX0DQ3Q6kWi7AoAeZDth3/j3BFtOZR5XLFGgcrjCOs= -github.com/cheggaaa/pb v1.0.27/go.mod h1:pQciLPpbU0oxA0h+VJYYLxO+XeDQb5pZijXscXHm81s= -github.com/chzyer/logex v1.1.10/go.mod h1:+Ywpsq7O8HXn0nuIou7OrIPyXbp3wmkHB+jjWRnGsAI= -github.com/chzyer/readline v0.0.0-20180603132655-2972be24d48e/go.mod h1:nSuG5e5PlCu98SY8svDHJxuZscDgtXS6KTTbou5AhLI= -github.com/chzyer/test v0.0.0-20180213035817-a1ea475d72b1/go.mod h1:Q3SI9o4m/ZMnBNeIyt5eFwwo7qiLfzFZmjNmxjkiQlU= github.com/client9/misspell v0.3.4/go.mod h1:qj6jICC3Q7zFZvVWo7KLAzC3yx5G7kyvSDkc90ppPyw= github.com/cncf/udpa/go v0.0.0-20191209042840-269d4d468f6f/go.mod h1:M8M6+tZqaGXZJjfX53e64911xZQV5JYwmTeXPW+k8Sc= github.com/cncf/udpa/go v0.0.0-20201120205902-5459f2c99403/go.mod h1:WmhPx2Nbnhtbo57+VJT5O0JRkEi1Wbu0z5j0R8u5Hbk= @@ -97,8 +44,6 @@ github.com/creack/pty v1.1.9/go.mod h1:oKZEueFk5CKHvIhNR5MUki03XCEU+Q6VDXinZuGJ3 github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c= github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= -github.com/dgrijalva/jwt-go v3.2.0+incompatible h1:7qlOGliEKZXTDg6OTjfoBKDXWrumCAMpl/TFQ4/5kLM= -github.com/dgrijalva/jwt-go v3.2.0+incompatible/go.mod h1:E3ru+11k8xSBh+hMPgOLZmtrrCbhqsmaPHjLKYnJCaQ= github.com/emirpasic/gods v1.12.0 h1:QAUIPSaCu4G+POclxeqb3F+WPpdKqFGlw36+yOzGlrg= github.com/emirpasic/gods v1.12.0/go.mod h1:YfzfFFoVP/catgzJb4IKIqXjX78Ha8FMSDh3ymbK86o= github.com/envoyproxy/go-control-plane v0.9.0/go.mod h1:YTl/9mNaCwkRvm6d1a2C3ymFceY/DCBVvsKhRF0iEA4= @@ -107,98 +52,60 @@ github.com/envoyproxy/go-control-plane v0.9.4/go.mod h1:6rpuAdCZL397s3pYoYcLgu1m github.com/envoyproxy/go-control-plane v0.9.9-0.20201210154907-fd9021fe5dad/go.mod h1:cXg6YxExXjJnVBQHBLXeUAgxn2UodCpnH306RInaBQk= github.com/envoyproxy/go-control-plane v0.10.2-0.20220325020618-49ff273808a1/go.mod h1:KJwIaB5Mv44NWtYuAOFCVOjcI94vtpEz2JU/D2v6IjE= github.com/envoyproxy/protoc-gen-validate v0.1.0/go.mod h1:iSmxcyjqTsJpI2R4NaDN7+kN2VEUnK/pcBlmesArF7c= -github.com/fatih/color v1.7.0 h1:DkWD4oS2D8LGGgTQ6IvwJJXSL5Vp2ffcQg58nFV38Ys= github.com/fatih/color v1.7.0/go.mod h1:Zm6kSWBoL9eyXnKyktHP6abPY2pDugNf5KwzbycvMj4= -github.com/flynn/go-shlex v0.0.0-20150515145356-3f9db97f8568 h1:BHsljHzVlRcyQhjrss6TZTdY2VfCqZPbv5k3iBFa2ZQ= +github.com/fatih/color v1.13.0 h1:8LOYc1KYPPmyKMuN8QV2DNRWNbLo6LZ0iLs8+mlH53w= +github.com/fatih/color v1.13.0/go.mod h1:kLAiJbzzSOZDVNGyDpeOxJ47H46qBXwg5ILebYFFOfk= github.com/flynn/go-shlex v0.0.0-20150515145356-3f9db97f8568/go.mod h1:xEzjJPgXI435gkrCt3MPfRiAkVrwSbHsst4LCFVfpJc= +github.com/frankban/quicktest v1.14.3 h1:FJKSZTDHjyhriyC81FLQ0LY93eSai0ZyR/ZIkd3ZUKE= github.com/ghodss/yaml v1.0.0/go.mod h1:4dBDuWmgqj2HViK6kFavaiC9ZROes6MMH2rRYeMEF04= -github.com/gliderlabs/ssh v0.2.2 h1:6zsha5zo/TWhRhwqCD3+EarCAgZ2yN28ipRnGPnwkI0= github.com/gliderlabs/ssh v0.2.2/go.mod h1:U7qILu1NlMHj9FlMhZLlkCdDnU1DBEAqr0aevW3Awn0= github.com/go-git/gcfg v1.5.0 h1:Q5ViNfGF8zFgyJWPqYwA7qGFoMTEiBmdlkcfRmpIMa4= github.com/go-git/gcfg v1.5.0/go.mod h1:5m20vg6GwYabIxaOonVkTdrILxQMpEShl1xiMF4ua+E= -github.com/go-git/go-billy/v5 v5.0.0/go.mod h1:pmpqyWchKfYfrkb/UVH4otLvyi/5gJlGI4Hb3ZqZ3W0= github.com/go-git/go-billy/v5 v5.2.0/go.mod h1:pmpqyWchKfYfrkb/UVH4otLvyi/5gJlGI4Hb3ZqZ3W0= github.com/go-git/go-billy/v5 v5.3.1 h1:CPiOUAzKtMRvolEKw+bG1PLRpT7D3LIs3/3ey4Aiu34= github.com/go-git/go-billy/v5 v5.3.1/go.mod h1:pmpqyWchKfYfrkb/UVH4otLvyi/5gJlGI4Hb3ZqZ3W0= -github.com/go-git/go-git-fixtures/v4 v4.0.1/go.mod h1:m+ICp2rF3jDhFgEZ/8yziagdT1C+ZpZcrJjappBCDSw= -github.com/go-git/go-git-fixtures/v4 v4.2.1 h1:n9gGL1Ct/yIw+nfsfr8s4+sbhT+Ncu2SubfXjIWgci8= github.com/go-git/go-git-fixtures/v4 v4.2.1/go.mod h1:K8zd3kDUAykwTdDCr+I0per6Y6vMiRR/nnVTBtavnB0= -github.com/go-git/go-git/v5 v5.1.0/go.mod h1:ZKfuPUoY1ZqIG4QG9BDBh3G4gLM5zvPuSJAozQrZuyM= github.com/go-git/go-git/v5 v5.4.2 h1:BXyZu9t0VkbiHtqrsvdq39UDhGJTl1h55VW6CSC4aY4= github.com/go-git/go-git/v5 v5.4.2/go.mod h1:gQ1kArt6d+n+BGd+/B/I74HwRTLhth2+zti4ihgckDc= -github.com/go-gl/glfw v0.0.0-20190409004039-e6da0acd62b1/go.mod h1:vR7hzQXu2zJy9AVAgeJqvqgH9Q5CA+iKCZ2gyEVpxRU= -github.com/go-gl/glfw/v3.3/glfw v0.0.0-20191125211704-12ad95a8df72/go.mod h1:tQ2UAYgL5IevRw8kRxooKSPJfGvJ9fJQFa0TUsXzTg8= -github.com/go-gl/glfw/v3.3/glfw v0.0.0-20200222043503-6f7a984d4dc4/go.mod h1:tQ2UAYgL5IevRw8kRxooKSPJfGvJ9fJQFa0TUsXzTg8= github.com/go-test/deep v1.0.3 h1:ZrJSEWsXzPOxaZnFteGEfooLba+ju3FYIbOrS+rQd68= -github.com/go-test/deep v1.0.3/go.mod h1:wGDj63lr65AM2AQyKZd/NYHGb0R+1RLqB8NKt3aSFNA= +github.com/golang-jwt/jwt/v4 v4.4.2 h1:rcc4lwaZgFMCZ5jxF9ABolDcIHdBytAFgqFPbSJQAYs= +github.com/golang-jwt/jwt/v4 v4.4.2/go.mod h1:m21LjoU+eqJr34lmDMbreY2eSTRJ1cv77w39/MY0Ch0= github.com/golang/glog v0.0.0-20160126235308-23def4e6c14b/go.mod h1:SBH7ygxi8pfUlaOkMMuAQtPIUF8ecWP5IEl/CR7VP2Q= -github.com/golang/groupcache v0.0.0-20190702054246-869f871628b6/go.mod h1:cIg4eruTrX1D+g88fzRXU5OdNfaM+9IcxsU14FzY7Hc= -github.com/golang/groupcache v0.0.0-20191227052852-215e87163ea7/go.mod h1:cIg4eruTrX1D+g88fzRXU5OdNfaM+9IcxsU14FzY7Hc= -github.com/golang/groupcache v0.0.0-20200121045136-8c9f03a8e57e h1:1r7pUrabqp18hOBcwBwiTsbnFeTZHV9eER/QT5JVZxY= -github.com/golang/groupcache v0.0.0-20200121045136-8c9f03a8e57e/go.mod h1:cIg4eruTrX1D+g88fzRXU5OdNfaM+9IcxsU14FzY7Hc= github.com/golang/mock v1.1.1/go.mod h1:oTYuIxOrZwtPieC+H1uAHpcLFnEyAGVDL/k47Jfbm0A= -github.com/golang/mock v1.2.0/go.mod h1:oTYuIxOrZwtPieC+H1uAHpcLFnEyAGVDL/k47Jfbm0A= -github.com/golang/mock v1.3.1/go.mod h1:sBzyDLLjw3U8JLTeZvSv8jJB+tU5PVekmnlKIyFUx0Y= -github.com/golang/mock v1.4.0/go.mod h1:UOMv5ysSaYNkG+OFQykRIcU/QvvxJf3p21QfJ2Bt3cw= -github.com/golang/mock v1.4.1/go.mod h1:UOMv5ysSaYNkG+OFQykRIcU/QvvxJf3p21QfJ2Bt3cw= -github.com/golang/mock v1.4.3 h1:GV+pQPG/EUUbkh47niozDcADz6go/dUwhVzdUQHIVRw= -github.com/golang/mock v1.4.3/go.mod h1:UOMv5ysSaYNkG+OFQykRIcU/QvvxJf3p21QfJ2Bt3cw= github.com/golang/protobuf v1.1.0/go.mod h1:6lQm79b+lXiMfvg/cZm0SGofjICqVBUtrP5yJMmIC1U= github.com/golang/protobuf v1.2.0/go.mod h1:6lQm79b+lXiMfvg/cZm0SGofjICqVBUtrP5yJMmIC1U= github.com/golang/protobuf v1.3.1/go.mod h1:6lQm79b+lXiMfvg/cZm0SGofjICqVBUtrP5yJMmIC1U= github.com/golang/protobuf v1.3.2/go.mod h1:6lQm79b+lXiMfvg/cZm0SGofjICqVBUtrP5yJMmIC1U= github.com/golang/protobuf v1.3.3/go.mod h1:vzj43D7+SQXF/4pzW/hwtAqwc6iTitCiVSaWz5lYuqw= github.com/golang/protobuf v1.3.4/go.mod h1:vzj43D7+SQXF/4pzW/hwtAqwc6iTitCiVSaWz5lYuqw= -github.com/golang/protobuf v1.3.5/go.mod h1:6O5/vntMXwX2lRkT1hjjk0nAC1IDOTvTlVgjlRvqsdk= github.com/golang/protobuf v1.4.0-rc.1/go.mod h1:ceaxUfeHdC40wWswd/P6IGgMaK3YpKi5j83Wpe3EHw8= github.com/golang/protobuf v1.4.0-rc.1.0.20200221234624-67d41d38c208/go.mod h1:xKAWHe0F5eneWXFV3EuXVDTCmh+JuBKY0li0aMyXATA= github.com/golang/protobuf v1.4.0-rc.2/go.mod h1:LlEzMj4AhA7rCAGe4KMBDvJI+AwstrUpVNzEA03Pprs= github.com/golang/protobuf v1.4.0-rc.4.0.20200313231945-b860323f09d0/go.mod h1:WU3c8KckQ9AFe+yFwt9sWVRKCVIyN9cPHBJSNnbL67w= github.com/golang/protobuf v1.4.0/go.mod h1:jodUvKwWbYaEsadDk5Fwe5c77LiNKVO9IDvqG2KuDX0= github.com/golang/protobuf v1.4.1/go.mod h1:U8fpvMrcmy5pZrNK1lt4xCsGvpyWQ/VVv6QDs8UjoX8= -github.com/golang/protobuf v1.4.2 h1:+Z5KGCizgyZCbGh1KZqA0fcLLkwbsjIzS4aV2v7wJX0= github.com/golang/protobuf v1.4.2/go.mod h1:oDoupMAO8OvCJWAcko0GGGIgR6R6ocIYbsSw735rRwI= github.com/golang/protobuf v1.4.3/go.mod h1:oDoupMAO8OvCJWAcko0GGGIgR6R6ocIYbsSw735rRwI= github.com/golang/protobuf v1.5.0/go.mod h1:FsONVRAS9T7sI+LIUmWTfcYkHO4aIWwzhcaSAoJOfIk= github.com/golang/protobuf v1.5.2 h1:ROPKBNFfQgOUMifHyP+KYbvpjbdoFNs+aK7DXlji0Tw= github.com/golang/protobuf v1.5.2/go.mod h1:XVQd3VNwM+JqD3oG2Ue2ip4fOMUkwXdXDdiuN0vRsmY= -github.com/golang/snappy v0.0.1/go.mod h1:/XxbfmMg8lxefKM7IXC3fBNl/7bRcc72aCRzEWrmP2Q= -github.com/google/btree v0.0.0-20180813153112-4030bb1f1f0c/go.mod h1:lNA+9X1NB3Zf8V7Ke586lFgjr2dZNuvo3lPJSGZ5JPQ= -github.com/google/btree v1.0.0/go.mod h1:lNA+9X1NB3Zf8V7Ke586lFgjr2dZNuvo3lPJSGZ5JPQ= github.com/google/go-cmp v0.2.0/go.mod h1:oXzfMopK8JAjlY9xF4vHSVASa0yLyX7SntLO5aqRK0M= github.com/google/go-cmp v0.3.0/go.mod h1:8QqcDgzrUqlUb/G2PQTWiueGozuR1884gddMywk6iLU= github.com/google/go-cmp v0.3.1/go.mod h1:8QqcDgzrUqlUb/G2PQTWiueGozuR1884gddMywk6iLU= github.com/google/go-cmp v0.4.0/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/gNBxE= -github.com/google/go-cmp v0.4.1/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/gNBxE= github.com/google/go-cmp v0.5.0/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/gNBxE= github.com/google/go-cmp v0.5.5/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/gNBxE= -github.com/google/go-cmp v0.5.6 h1:BKbKCqvP6I+rmFHt06ZmyQtvB8xAkWdhFyr0ZUNZcxQ= github.com/google/go-cmp v0.5.6/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/gNBxE= -github.com/google/go-cmp v0.5.7/go.mod h1:n+brtR0CgQNWTVd5ZUFpTBC8YFBDLK/h/bpaJ8/DtOE= github.com/google/go-cmp v0.5.8 h1:e6P7q2lk1O+qJJb4BtCQXlK8vWEO8V1ZeuEdJNOqZyg= github.com/google/go-cmp v0.5.8/go.mod h1:17dUlkBOakJ0+DkrSSNjCkIjxS6bF9zb3elmeNGIjoY= -github.com/google/martian v2.1.0+incompatible h1:/CP5g8u/VJHijgedC/Legn3BAbAaWPgecwXBIDzw5no= -github.com/google/martian v2.1.0+incompatible/go.mod h1:9I4somxYTbIHy5NJKHRl3wXiIaQGbYVAs8BPL6v8lEs= -github.com/google/martian/v3 v3.0.0 h1:pMen7vLs8nvgEYhywH3KDWJIJTeEr2ULsVWHWYHQyBs= -github.com/google/martian/v3 v3.0.0/go.mod h1:y5Zk1BBys9G+gd6Jrk0W3cC1+ELVxBWuIGO+w/tUAp0= -github.com/google/pprof v0.0.0-20181206194817-3ea8567a2e57/go.mod h1:zfwlbNMJ+OItoe0UupaVj+oy1omPYYDuagoSzA8v9mc= -github.com/google/pprof v0.0.0-20190515194954-54271f7e092f/go.mod h1:zfwlbNMJ+OItoe0UupaVj+oy1omPYYDuagoSzA8v9mc= -github.com/google/pprof v0.0.0-20191218002539-d4f498aebedc/go.mod h1:ZgVRPoUq/hfqzAqh7sHMqb3I9Rq5C59dIz2SbBwJ4eM= -github.com/google/pprof v0.0.0-20200212024743-f11f1df84d12/go.mod h1:ZgVRPoUq/hfqzAqh7sHMqb3I9Rq5C59dIz2SbBwJ4eM= -github.com/google/pprof v0.0.0-20200229191704-1ebb73c60ed3/go.mod h1:ZgVRPoUq/hfqzAqh7sHMqb3I9Rq5C59dIz2SbBwJ4eM= -github.com/google/pprof v0.0.0-20200430221834-fc25d7d30c6d/go.mod h1:ZgVRPoUq/hfqzAqh7sHMqb3I9Rq5C59dIz2SbBwJ4eM= -github.com/google/pprof v0.0.0-20200708004538-1a94d8640e99/go.mod h1:ZgVRPoUq/hfqzAqh7sHMqb3I9Rq5C59dIz2SbBwJ4eM= -github.com/google/renameio v0.1.0/go.mod h1:KWCgfxg9yswjAJkECMjeO8J8rahYeXnNhOm40UhjYkI= github.com/google/uuid v1.1.1/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo= github.com/google/uuid v1.1.2/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo= github.com/google/uuid v1.3.0 h1:t6JiXgmwXMjEs8VusXIJk2BXHsn+wx8BZdTaoZ5fu7I= github.com/google/uuid v1.3.0/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo= -github.com/googleapis/gax-go/v2 v2.0.4/go.mod h1:0Wqv26UfaUD9n4G6kQubkQ+KchISgw+vpHVxEJEs9eg= -github.com/googleapis/gax-go/v2 v2.0.5 h1:sjZBwGj9Jlw33ImPtvFviGYvseOtDM7hkSKB7+Tv3SM= -github.com/googleapis/gax-go/v2 v2.0.5/go.mod h1:DWXyrwAJ9X0FpwwEdw+IPEYBICEFu5mhpdKc/us6bOk= github.com/grpc-ecosystem/grpc-gateway v1.16.0/go.mod h1:BDjrQk3hbvj6Nolgz8mAMFbcEtjT1g+wF4CSlocrBnw= -github.com/hashicorp/errwrap v1.0.0 h1:hLrqtEDnRye3+sgx6z4qVLNuviH3MR5aQ0ykNJa/UYA= github.com/hashicorp/errwrap v1.0.0/go.mod h1:YH+1FKiLXxHSkmPseP+kNlulaMuP3n2brvKWEqk/Jc4= +github.com/hashicorp/errwrap v1.1.0 h1:OxrOeh75EUXMY8TBjag2fzXGZ40LB6IKw45YeGUDY2I= +github.com/hashicorp/errwrap v1.1.0/go.mod h1:YH+1FKiLXxHSkmPseP+kNlulaMuP3n2brvKWEqk/Jc4= github.com/hashicorp/go-checkpoint v0.5.0 h1:MFYpPZCnQqQTE18jFwSII6eUQrD/oxMFp3mlgcqk5mU= github.com/hashicorp/go-checkpoint v0.5.0/go.mod h1:7nfLNL10NsxqO4iWuW6tWW0HjZuDrwkBuEQsVcpCOgg= github.com/hashicorp/go-cleanhttp v0.5.0/go.mod h1:JpRdi6/HCYpAwUzNwuwqhbovhLtngrth3wmdIIUrZ80= @@ -207,191 +114,120 @@ github.com/hashicorp/go-cleanhttp v0.5.2 h1:035FKYIWjmULyFRBKPs8TBQoi0x6d9G4xc9n github.com/hashicorp/go-cleanhttp v0.5.2/go.mod h1:kO/YDlP8L1346E6Sodw+PrpBSV4/SoxCXGY6BqNFT48= github.com/hashicorp/go-cty v1.4.1-0.20200414143053-d3edf31b6320 h1:1/D3zfFHttUKaCaGKZ/dR2roBXv0vKbSCnssIldfQdI= github.com/hashicorp/go-cty v1.4.1-0.20200414143053-d3edf31b6320/go.mod h1:EiZBMaudVLy8fmjf9Npq1dq9RalhveqZG5w/yz3mHWs= -github.com/hashicorp/go-getter v1.4.0/go.mod h1:7qxyCd8rBfcShwsvxgIguu4KbS3l8bUCwg2Umn7RjeY= -github.com/hashicorp/go-getter v1.4.2-0.20200106182914-9813cbd4eb02/go.mod h1:7qxyCd8rBfcShwsvxgIguu4KbS3l8bUCwg2Umn7RjeY= -github.com/hashicorp/go-getter v1.5.3 h1:NF5+zOlQegim+w/EUhSLh6QhXHmZMEeHLQzllkQ3ROU= -github.com/hashicorp/go-getter v1.5.3/go.mod h1:BrrV/1clo8cCYu6mxvboYg+KutTiFnXjMEgDD8+i7ZI= -github.com/hashicorp/go-hclog v0.0.0-20180709165350-ff2cf002a8dd/go.mod h1:9bjs9uLqI8l75knNv3lV1kA55veR+WUPSiKIWcQHudI= -github.com/hashicorp/go-hclog v0.9.2 h1:CG6TE5H9/JXsFWJCfoIVpKFIkFe6ysEuHirp4DxCsHI= -github.com/hashicorp/go-hclog v0.9.2/go.mod h1:5CU+agLiy3J7N7QjHK5d05KxGsuXiQLrjA0H7acj2lQ= -github.com/hashicorp/go-hclog v0.14.1/go.mod h1:whpDNt7SSdeAju8AWKIWsul05p54N/39EeqMAyrmvFQ= -github.com/hashicorp/go-hclog v1.2.0 h1:La19f8d7WIlm4ogzNHB0JGqs5AUDAZ2UfCY4sJXcJdM= -github.com/hashicorp/go-hclog v1.2.0/go.mod h1:whpDNt7SSdeAju8AWKIWsul05p54N/39EeqMAyrmvFQ= -github.com/hashicorp/go-multierror v1.0.0 h1:iVjPR7a6H0tWELX5NxNe7bYopibicUzc7uPribsnS6o= +github.com/hashicorp/go-hclog v1.2.1 h1:YQsLlGDJgwhXFpucSPyVbCBviQtjlHv3jLTlp8YmtEw= +github.com/hashicorp/go-hclog v1.2.1/go.mod h1:W4Qnvbt70Wk/zYJryRzDRU/4r0kIg0PVHBcfoyhpF5M= github.com/hashicorp/go-multierror v1.0.0/go.mod h1:dHtQlpGsu+cZNNAkkCN/P3hoUDHhCYQXV3UM06sGGrk= github.com/hashicorp/go-multierror v1.1.1 h1:H5DkEtf6CXdFp0N0Em5UCwQpXMWke8IA0+lD48awMYo= github.com/hashicorp/go-multierror v1.1.1/go.mod h1:iw975J/qwKPdAO1clOe2L8331t/9/fmwbPZ6JB6eMoM= -github.com/hashicorp/go-plugin v1.3.0 h1:4d/wJojzvHV1I4i/rrjVaeuyxWrLzDE1mDCyDy8fXS8= -github.com/hashicorp/go-plugin v1.3.0/go.mod h1:F9eH4LrE/ZsRdbwhfjs9k9HoDUwAHnYtXdgmf1AVNs0= github.com/hashicorp/go-plugin v1.4.4 h1:NVdrSdFRt3SkZtNckJ6tog7gbpRrcbOjQi/rgF7JYWQ= github.com/hashicorp/go-plugin v1.4.4/go.mod h1:viDMjcLJuDui6pXb8U4HVfb8AamCWhHGUjr2IrTF67s= -github.com/hashicorp/go-safetemp v1.0.0 h1:2HR189eFNrjHQyENnQMMpCiBAsRxzbTMIgBhEyExpmo= -github.com/hashicorp/go-safetemp v1.0.0/go.mod h1:oaerMy3BhqiTbVye6QuFhFtIceqFoDHxNAB65b+Rj1I= github.com/hashicorp/go-uuid v1.0.0/go.mod h1:6SBZvOh/SIDV7/2o3Jml5SYk/TvGqwFJ/bN7x4byOro= -github.com/hashicorp/go-uuid v1.0.1 h1:fv1ep09latC32wFoVwnqcnKJGnMSdBanPczbHAYm1BE= -github.com/hashicorp/go-uuid v1.0.1/go.mod h1:6SBZvOh/SIDV7/2o3Jml5SYk/TvGqwFJ/bN7x4byOro= github.com/hashicorp/go-uuid v1.0.3 h1:2gKiV6YVmrJ1i2CKKa9obLvRieoRGviZFL26PcT/Co8= github.com/hashicorp/go-uuid v1.0.3/go.mod h1:6SBZvOh/SIDV7/2o3Jml5SYk/TvGqwFJ/bN7x4byOro= -github.com/hashicorp/go-version v1.1.0/go.mod h1:fltr4n8CU8Ke44wwGCBoEymUuxUHl09ZGVZPK5anwXA= github.com/hashicorp/go-version v1.2.0/go.mod h1:fltr4n8CU8Ke44wwGCBoEymUuxUHl09ZGVZPK5anwXA= -github.com/hashicorp/go-version v1.2.1/go.mod h1:fltr4n8CU8Ke44wwGCBoEymUuxUHl09ZGVZPK5anwXA= -github.com/hashicorp/go-version v1.3.0 h1:McDWVJIU/y+u1BRV06dPaLfLCaT7fUTJLp5r04x7iNw= -github.com/hashicorp/go-version v1.3.0/go.mod h1:fltr4n8CU8Ke44wwGCBoEymUuxUHl09ZGVZPK5anwXA= -github.com/hashicorp/go-version v1.4.0/go.mod h1:fltr4n8CU8Ke44wwGCBoEymUuxUHl09ZGVZPK5anwXA= -github.com/hashicorp/go-version v1.5.0 h1:O293SZ2Eg+AAYijkVK3jR786Am1bhDEh2GHT0tIVE5E= github.com/hashicorp/go-version v1.5.0/go.mod h1:fltr4n8CU8Ke44wwGCBoEymUuxUHl09ZGVZPK5anwXA= -github.com/hashicorp/golang-lru v0.5.0/go.mod h1:/m3WP610KZHVQ1SGc6re/UDhFvYD7pJ4Ao+sR/qLZy8= -github.com/hashicorp/golang-lru v0.5.1/go.mod h1:/m3WP610KZHVQ1SGc6re/UDhFvYD7pJ4Ao+sR/qLZy8= -github.com/hashicorp/hc-install v0.3.1/go.mod h1:3LCdWcCDS1gaHC9mhHCGbkYfoY6vdsKohGjugbZdZak= -github.com/hashicorp/hc-install v0.3.2/go.mod h1:xMG6Tr8Fw1WFjlxH0A9v61cW15pFwgEGqEz0V4jisHs= -github.com/hashicorp/hcl v0.0.0-20170504190234-a4b07c25de5f h1:UdxlrJz4JOnY8W+DbLISwf2B8WXEolNRA8BGCwI9jws= -github.com/hashicorp/hcl v0.0.0-20170504190234-a4b07c25de5f/go.mod h1:oZtUIOe8dh44I2q6ScRibXws4Ajl+d+nod3AaR9vL5w= -github.com/hashicorp/hcl/v2 v2.0.0/go.mod h1:oVVDG71tEinNGYCxinCYadcmKU9bglqW9pV3txagJ90= -github.com/hashicorp/hcl/v2 v2.3.0 h1:iRly8YaMwTBAKhn1Ybk7VSdzbnopghktCD031P8ggUE= -github.com/hashicorp/hcl/v2 v2.3.0/go.mod h1:d+FwDBbOLvpAM3Z6J7gPj/VoAGkNe/gm352ZhjJ/Zv8= -github.com/hashicorp/hcl/v2 v2.12.0 h1:PsYxySWpMD4KPaoJLnsHwtK5Qptvj/4Q6s0t4sUxZf4= -github.com/hashicorp/hcl/v2 v2.12.0/go.mod h1:FwWsfWEjyV/CMj8s/gqAuiviY72rJ1/oayI9WftqcKg= +github.com/hashicorp/go-version v1.6.0 h1:feTTfFNnjP967rlCxM/I9g701jU+RN74YKx2mOkIeek= +github.com/hashicorp/go-version v1.6.0/go.mod h1:fltr4n8CU8Ke44wwGCBoEymUuxUHl09ZGVZPK5anwXA= +github.com/hashicorp/hc-install v0.4.0 h1:cZkRFr1WVa0Ty6x5fTvL1TuO1flul231rWkGH92oYYk= +github.com/hashicorp/hc-install v0.4.0/go.mod h1:5d155H8EC5ewegao9A4PUTMNPZaq+TbOzkJJZ4vrXeI= +github.com/hashicorp/hcl/v2 v2.13.0 h1:0Apadu1w6M11dyGFxWnmhhcMjkbAiKCv7G1r/2QgCNc= +github.com/hashicorp/hcl/v2 v2.13.0/go.mod h1:e4z5nxYlWNPdDSNYX+ph14EvWYMFm3eP0zIUqPc2jr0= github.com/hashicorp/logutils v1.0.0 h1:dLEQVugN8vlakKOUE3ihGLTZJRB4j+M2cdTm/ORI65Y= github.com/hashicorp/logutils v1.0.0/go.mod h1:QIAnNjmIWmVIIkWDTG1z5v++HQmx9WQRO+LraFDTW64= -github.com/hashicorp/terraform-config-inspect v0.0.0-20191115094559-17f92b0546e8 h1:+RyjwU+Gnd/aTJBPZVDNm903eXVjjqhbaR4Ypx3xYyY= -github.com/hashicorp/terraform-config-inspect v0.0.0-20191115094559-17f92b0546e8/go.mod h1:p+ivJws3dpqbp1iP84+npOyAmTTOLMgCzrXd3GSdn/A= -github.com/hashicorp/terraform-exec v0.10.0/go.mod h1:tOT8j1J8rP05bZBGWXfMyU3HkLi1LWyqL3Bzsc3CJjo= -github.com/hashicorp/terraform-exec v0.15.0 h1:cqjh4d8HYNQrDoEmlSGelHmg2DYDh5yayckvJ5bV18E= -github.com/hashicorp/terraform-exec v0.15.0/go.mod h1:H4IG8ZxanU+NW0ZpDRNsvh9f0ul7C0nHP+rUR/CHs7I= -github.com/hashicorp/terraform-exec v0.16.1/go.mod h1:aj0lVshy8l+MHhFNoijNHtqTJQI3Xlowv5EOsEaGO7M= -github.com/hashicorp/terraform-json v0.5.0/go.mod h1:eAbqb4w0pSlRmdvl8fOyHAi/+8jnkVYN28gJkSJrLhU= -github.com/hashicorp/terraform-json v0.13.0 h1:Li9L+lKD1FO5RVFRM1mMMIBDoUHslOniyEi5CM+FWGY= -github.com/hashicorp/terraform-json v0.13.0/go.mod h1:y5OdLBCT+rxbwnpxZs9kGL7R9ExU76+cpdY8zHwoazk= +github.com/hashicorp/terraform-exec v0.17.2 h1:EU7i3Fh7vDUI9nNRdMATCEfnm9axzTnad8zszYZ73Go= +github.com/hashicorp/terraform-exec v0.17.2/go.mod h1:tuIbsL2l4MlwwIZx9HPM+LOV9vVyEfBYu2GsO1uH3/8= +github.com/hashicorp/terraform-json v0.14.0 h1:sh9iZ1Y8IFJLx+xQiKHGud6/TSUCM0N8e17dKDpqV7s= github.com/hashicorp/terraform-json v0.14.0/go.mod h1:5A9HIWPkk4e5aeeXIBbkcOvaZbIYnAIkEyqP2pNSckM= -github.com/hashicorp/terraform-plugin-docs v0.5.1 h1:WwrUcamix9x0TqfTw/WGHMRqoTe1QPZKaeWJPuFb4lQ= -github.com/hashicorp/terraform-plugin-docs v0.5.1/go.mod h1:SQwEgy0/B0UPQ07rNEG1Wpt6E3jvRcCwkVHPNybGgc0= -github.com/hashicorp/terraform-plugin-go v0.9.1 h1:vXdHaQ6aqL+OF076nMSBV+JKPdmXlzG5mzVDD04WyPs= -github.com/hashicorp/terraform-plugin-go v0.9.1/go.mod h1:ItjVSlQs70otlzcCwlPcU8FRXLdO973oYFRZwAOxy8M= -github.com/hashicorp/terraform-plugin-log v0.4.0 h1:F3eVnm8r2EfQCe2k9blPIiF/r2TT01SHijXnS7bujvc= -github.com/hashicorp/terraform-plugin-log v0.4.0/go.mod h1:9KclxdunFownr4pIm1jdmwKRmE4d6HVG2c9XDq47rpg= -github.com/hashicorp/terraform-plugin-sdk v1.16.0 h1:NrkXMRjHErUPPTHQkZ6JIn6bByiJzGnlJzH1rVdNEuE= -github.com/hashicorp/terraform-plugin-sdk v1.16.0/go.mod h1:5sVxrwW6/xzFhZyql+Q9zXCUEJaGWcBIxBbZFLpVXOI= -github.com/hashicorp/terraform-plugin-sdk/v2 v2.17.0 h1:Qr5fWNg1SPSfCRMtou67Y6Kcy9UnMYRNlIJTKRuUvXU= -github.com/hashicorp/terraform-plugin-sdk/v2 v2.17.0/go.mod h1:b+LFg8WpYgFgvEBP/6Htk5H9/pJp1V1E8NJAekfH2Ws= -github.com/hashicorp/terraform-plugin-test/v2 v2.1.2/go.mod h1:jerO5mrd+jVNALy8aiq+VZOg/CR8T2T1QR3jd6JKGOI= -github.com/hashicorp/terraform-registry-address v0.0.0-20210412075316-9b2996cce896 h1:1FGtlkJw87UsTMg5s8jrekrHmUPUJaMcu6ELiVhQrNw= -github.com/hashicorp/terraform-registry-address v0.0.0-20210412075316-9b2996cce896/go.mod h1:bzBPnUIkI0RxauU8Dqo+2KrZZ28Cf48s8V6IHt3p4co= -github.com/hashicorp/terraform-svchost v0.0.0-20191011084731-65d371908596 h1:hjyO2JsNZUKT1ym+FAdlBEkGPevazYsmVgIMw7dVELg= -github.com/hashicorp/terraform-svchost v0.0.0-20191011084731-65d371908596/go.mod h1:kNDNcF7sN4DocDLBkQYz73HGKwN1ANB1blq4lIYLYvg= +github.com/hashicorp/terraform-plugin-docs v0.13.0 h1:6e+VIWsVGb6jYJewfzq2ok2smPzZrt1Wlm9koLeKazY= +github.com/hashicorp/terraform-plugin-docs v0.13.0/go.mod h1:W0oCmHAjIlTHBbvtppWHe8fLfZ2BznQbuv8+UD8OucQ= +github.com/hashicorp/terraform-plugin-go v0.12.0 h1:6wW9mT1dSs0Xq4LR6HXj1heQ5ovr5GxXNJwkErZzpJw= +github.com/hashicorp/terraform-plugin-go v0.12.0/go.mod h1:kwhmaWHNDvT1B3QiSJdAtrB/D4RaKSY/v3r2BuoWK4M= +github.com/hashicorp/terraform-plugin-log v0.6.0 h1:/Vq78uSIdUSZ3iqDc9PESKtwt8YqNKN6u+khD+lLjuw= +github.com/hashicorp/terraform-plugin-log v0.6.0/go.mod h1:p4R1jWBXRTvL4odmEkFfDdhUjHf9zcs/BCoNHAc7IK4= +github.com/hashicorp/terraform-plugin-sdk/v2 v2.19.0 h1:7gDAcfto/C4Cjtf90SdukQshsxdMxJ/P69QxiF3digI= +github.com/hashicorp/terraform-plugin-sdk/v2 v2.19.0/go.mod h1:/WYikYjhKB7c2j1HmXZhRsAARldRb4M38bLCLOhC3so= +github.com/hashicorp/terraform-registry-address v0.0.0-20220623143253-7d51757b572c h1:D8aRO6+mTqHfLsK/BC3j5OAoogv1WLRWzY1AaTo3rBg= +github.com/hashicorp/terraform-registry-address v0.0.0-20220623143253-7d51757b572c/go.mod h1:Wn3Na71knbXc1G8Lh+yu/dQWWJeFQEpDeJMtWMtlmNI= github.com/hashicorp/terraform-svchost v0.0.0-20200729002733-f050f53b9734 h1:HKLsbzeOsfXmKNpr3GiT18XAblV0BjCbzL8KQAMZGa0= github.com/hashicorp/terraform-svchost v0.0.0-20200729002733-f050f53b9734/go.mod h1:kNDNcF7sN4DocDLBkQYz73HGKwN1ANB1blq4lIYLYvg= -github.com/hashicorp/yamux v0.0.0-20180604194846-3520598351bb/go.mod h1:+NfK9FKeTrX5uv1uIXGdwYDTeHna2qgaIlx54MXqjAM= github.com/hashicorp/yamux v0.0.0-20181012175058-2f1d1f20f75d h1:kJCB4vdITiW1eC1vq2e6IsrXKrZit1bv/TDYFGMp4BQ= github.com/hashicorp/yamux v0.0.0-20181012175058-2f1d1f20f75d/go.mod h1:+NfK9FKeTrX5uv1uIXGdwYDTeHna2qgaIlx54MXqjAM= +github.com/huandu/xstrings v1.3.1/go.mod h1:y5/lhBue+AyNmUVz9RLU9xbLR0o4KIIExikq4ovT0aE= github.com/huandu/xstrings v1.3.2 h1:L18LIDzqlW6xN2rEkpdV8+oL/IXWJ1APd+vsdYy4Wdw= github.com/huandu/xstrings v1.3.2/go.mod h1:y5/lhBue+AyNmUVz9RLU9xbLR0o4KIIExikq4ovT0aE= -github.com/ianlancetaylor/demangle v0.0.0-20181102032728-5e5cf60278f6/go.mod h1:aSSvb/t6k1mPoxDqO4vJh6VOCGPwU4O0C2/Eqndh1Sc= -github.com/imdario/mergo v0.3.9/go.mod h1:2EnlNZ0deacrJVfApfmtdGgDfMuh/nq6Ok1EcJh5FfA= github.com/imdario/mergo v0.3.11/go.mod h1:jmQim1M+e3UYxmgPu/WyfjB3N3VflVyUjjjwH0dnCYA= -github.com/imdario/mergo v0.3.12 h1:b6R2BslTbIEToALKP7LxUvijTsNI9TAe80pLWN2g/HU= github.com/imdario/mergo v0.3.12/go.mod h1:jmQim1M+e3UYxmgPu/WyfjB3N3VflVyUjjjwH0dnCYA= +github.com/imdario/mergo v0.3.13 h1:lFzP57bqS/wsqKssCGmtLAb8A0wKjLGrve2q3PPVcBk= +github.com/imdario/mergo v0.3.13/go.mod h1:4lJ1jqUDcsbIECGy0RUJAXNIhg+6ocWgb1ALK2O4oXg= github.com/jbenet/go-context v0.0.0-20150711004518-d14ea06fba99 h1:BQSFePA1RWJOlocH6Fxy8MmwDt+yVQYULKfN0RoTN8A= github.com/jbenet/go-context v0.0.0-20150711004518-d14ea06fba99/go.mod h1:1lJo3i6rXxKeerYnT8Nvf0QmHCRC1n8sfWVwXF2Frvo= -github.com/jessevdk/go-flags v1.4.0/go.mod h1:4FA24M0QyGHXBuZZK/XkWh8h0e1EYbRYJSGM75WSRxI= github.com/jessevdk/go-flags v1.5.0/go.mod h1:Fw0T6WPc1dYxT4mKEZRfG5kJhaTDP9pj1c2EWnYs/m4= github.com/jhump/protoreflect v1.6.0 h1:h5jfMVslIg6l29nsMs0D8Wj17RDVdNYti0vDN/PZZoE= -github.com/jhump/protoreflect v1.6.0/go.mod h1:eaTn3RZAmMBcV0fifFvlm6VHNz3wSkYyXYWUh7ymB74= -github.com/jmespath/go-jmespath v0.0.0-20160202185014-0b12d6b521d8/go.mod h1:Nht3zPeWKUH0NzdCt2Blrr5ys8VGpn0CEB0cQHVjt7k= -github.com/jmespath/go-jmespath v0.0.0-20180206201540-c2b33e8439af h1:pmfjZENx5imkbgOkpRUYLnmbU7UEFbjtDA2hxJ1ichM= -github.com/jmespath/go-jmespath v0.0.0-20180206201540-c2b33e8439af/go.mod h1:Nht3zPeWKUH0NzdCt2Blrr5ys8VGpn0CEB0cQHVjt7k= -github.com/jstemmer/go-junit-report v0.0.0-20190106144839-af01ea7f8024/go.mod h1:6v2b51hI/fHJwM22ozAgKL4VKDeJcHhJFhtBdhmNjmU= -github.com/jstemmer/go-junit-report v0.9.1 h1:6QPYqodiu3GuPL+7mfx+NwDdp2eTkp9IfEUpgAwUN0o= -github.com/jstemmer/go-junit-report v0.9.1/go.mod h1:Brl9GWCQeLvo8nXZwPNNblvFj/XSXhF0NWZEnDohbsk= -github.com/kevinburke/ssh_config v0.0.0-20190725054713-01f96b0aa0cd/go.mod h1:CT57kijsi8u/K/BOFA39wgDQJ9CxiF4nAY/ojJ6r6mM= github.com/kevinburke/ssh_config v0.0.0-20201106050909-4977a11b4351 h1:DowS9hvgyYSX4TO5NpyC606/Z4SxnNYbT+WX27or6Ck= github.com/kevinburke/ssh_config v0.0.0-20201106050909-4977a11b4351/go.mod h1:CT57kijsi8u/K/BOFA39wgDQJ9CxiF4nAY/ojJ6r6mM= -github.com/keybase/go-crypto v0.0.0-20161004153544-93f5b35093ba/go.mod h1:ghbZscTyKdM07+Fw3KSi0hcJm+AlEUWj8QLlPtijN/M= -github.com/kisielk/gotool v1.0.0/go.mod h1:XhKaO+MFFWcvkIS/tQcRk01m1F5IRFswLeQ+oQHNcck= -github.com/klauspost/compress v1.11.2 h1:MiK62aErc3gIiVEtyzKfeOHgW7atJb5g/KNX5m3c2nQ= -github.com/klauspost/compress v1.11.2/go.mod h1:aoV0uJVorq1K+umq18yTdKaF57EivdYsUV+/s2qKfXs= github.com/konsorten/go-windows-terminal-sequences v1.0.1/go.mod h1:T0+1ngSBFLxvqU3pZ+m/2kptfBszLMUkC4ZK/EgS/cQ= github.com/kr/pretty v0.1.0/go.mod h1:dAy3ld7l9f0ibDNOQOHHMYYIIbhfbHSm3C4ZsoJORNo= -github.com/kr/pretty v0.2.1 h1:Fmg33tUaq4/8ym9TJN1x7sLJnHVwhP33CNkpYV/7rwI= github.com/kr/pretty v0.2.1/go.mod h1:ipq/a2n7PKx3OHsz4KJII5eveXtPO4qwEXGdVfWzfnI= +github.com/kr/pretty v0.3.0 h1:WgNl7dwNpEZ6jJ9k1snq4pZsg7DOEN8hP9Xw0Tsjwk0= github.com/kr/pty v1.1.1/go.mod h1:pFQYn66WHrOpPYNljwOMqo10TkYh1fy3cYio2l3bCsQ= github.com/kr/text v0.1.0/go.mod h1:4Jbv+DJW3UT/LiOwJeYQe1efqtUx/iVham/4vfdArNI= github.com/kr/text v0.2.0 h1:5Nx0Ya0ZqY2ygV366QzturHI13Jq95ApcVaJBhpS+AY= github.com/kr/text v0.2.0/go.mod h1:eLer722TekiGuMkidMxC/pM04lWEeraHUUmBw8l2grE= github.com/kylelemons/godebug v0.0.0-20170820004349-d65d576e9348/go.mod h1:B69LEHPfb2qLo0BaaOLcbitczOKLWTsrBG9LczfCD4k= github.com/kylelemons/godebug v1.1.0 h1:RPNrshWIDI6G2gRW9EHilWtl7Z6Sb1BR0xunSBf0SNc= -github.com/kylelemons/godebug v1.1.0/go.mod h1:9/0rRGxNHcop5bhtWyNeEfOS8JIWk580+fNqagV/RAw= -github.com/matryer/is v1.2.0 h1:92UTHpy8CDwaJ08GqLDzhhuixiBUUD1p3AU6PHddz4A= github.com/matryer/is v1.2.0/go.mod h1:2fLPjFQM9rhQ15aVEtbuwhJinnOqrmgXPNdZsdwlWXA= github.com/mattn/go-colorable v0.0.9/go.mod h1:9vuHe8Xs5qXnSaW/c/ABM9alt+Vo+STaOChaDxuIBZU= -github.com/mattn/go-colorable v0.1.1/go.mod h1:FuOcm+DKB9mbwrcAfNl7/TZVBZ6rcnceauSikq3lYCQ= -github.com/mattn/go-colorable v0.1.4/go.mod h1:U0ppj6V5qS13XJ6of8GYAs25YV2eR4EVcfRqFIhoBtE= -github.com/mattn/go-colorable v0.1.11 h1:nQ+aFkoE2TMGc0b68U2OKSexC+eq46+XwZzWXHRmPYs= -github.com/mattn/go-colorable v0.1.11/go.mod h1:u5H1YNBxpqRaxsYJYSkiCWKzEfiAb1Gb520KVy5xxl4= +github.com/mattn/go-colorable v0.1.9/go.mod h1:u6P/XSegPjTcexA+o6vUJrdnUu04hMope9wVRipJSqc= +github.com/mattn/go-colorable v0.1.12 h1:jF+Du6AlPIjs2BiUiQlKOX0rt3SujHxPnksPKZbaA40= +github.com/mattn/go-colorable v0.1.12/go.mod h1:u5H1YNBxpqRaxsYJYSkiCWKzEfiAb1Gb520KVy5xxl4= github.com/mattn/go-isatty v0.0.3/go.mod h1:M+lRXTBqGeGNdLjl/ufCoiOlB5xdOkqRJdNxMWT7Zi4= -github.com/mattn/go-isatty v0.0.4/go.mod h1:M+lRXTBqGeGNdLjl/ufCoiOlB5xdOkqRJdNxMWT7Zi4= -github.com/mattn/go-isatty v0.0.5/go.mod h1:Iq45c/XA43vh69/j3iqttzPXn0bhXyGjM0Hdxcsrc5s= -github.com/mattn/go-isatty v0.0.8/go.mod h1:Iq45c/XA43vh69/j3iqttzPXn0bhXyGjM0Hdxcsrc5s= -github.com/mattn/go-isatty v0.0.10/go.mod h1:qgIWMr58cqv1PHHyhnkY9lrL7etaEgOFcMEpPG5Rm84= +github.com/mattn/go-isatty v0.0.12/go.mod h1:cbi8OIDigv2wuxKPP5vlRcQ1OAZbq2CE4Kysco4FUpU= github.com/mattn/go-isatty v0.0.14 h1:yVuAays6BHfxijgZPzw+3Zlu5yQgKGP2/hcQbHb7S9Y= github.com/mattn/go-isatty v0.0.14/go.mod h1:7GGIvUiUoEMVVmxf/4nioHXj79iQHKdU27kJ6hsGG94= -github.com/mattn/go-runewidth v0.0.4/go.mod h1:LwmH8dsx7+W8Uxz3IHJYH5QSwggIsqBzpuz5H//U1FU= -github.com/mitchellh/cli v1.1.1/go.mod h1:xcISNoH86gajksDmfB23e/pu+B+GeFRMYmoHXxx3xhI= -github.com/mitchellh/cli v1.1.2 h1:PvH+lL2B7IQ101xQL63Of8yFS2y+aDlsFcsqNc+u/Kw= -github.com/mitchellh/cli v1.1.2/go.mod h1:6iaV0fGdElS6dPBx0EApTxHrcWvmJphyh2n8YBLPPZ4= -github.com/mitchellh/colorstring v0.0.0-20190213212951-d06e56a500db/go.mod h1:l0dey0ia/Uv7NcFFVbCLtqEBQbrT4OCwCSKTEv6enCw= +github.com/mitchellh/cli v1.1.4 h1:qj8czE26AU4PbiaPXK5uVmMSM+V5BYsFBiM9HhGRLUA= +github.com/mitchellh/cli v1.1.4/go.mod h1:vTLESy5mRhKOs9KDp0/RATawxP1UqBmdrpVRMnpcvKQ= github.com/mitchellh/copystructure v1.0.0/go.mod h1:SNtv71yrdKgLRyLFxmLdkAbkKEFWgYaq1OVrnRcwhnw= github.com/mitchellh/copystructure v1.2.0 h1:vpKXTN4ewci03Vljg/q9QvCGUDttBOGBIa15WveJJGw= github.com/mitchellh/copystructure v1.2.0/go.mod h1:qLl+cE2AmVv+CoeAwDPye/v+N2HKCj9FbZEVFJRxO9s= -github.com/mitchellh/go-homedir v1.0.0/go.mod h1:SfyaCUpYCn1Vlf4IUYiD9fPX4A5wJrkLzIz1N1q0pr0= github.com/mitchellh/go-homedir v1.1.0 h1:lukF9ziXFxDFPkA1vsr5zpc1XuPDn/wFntq5mG+4E0Y= github.com/mitchellh/go-homedir v1.1.0/go.mod h1:SfyaCUpYCn1Vlf4IUYiD9fPX4A5wJrkLzIz1N1q0pr0= -github.com/mitchellh/go-testing-interface v0.0.0-20171004221916-a61a99592b77/go.mod h1:kRemZodwjscx+RGhAo8eIhFbs2+BFgRtFPeD/KE+zxI= -github.com/mitchellh/go-testing-interface v1.0.0/go.mod h1:kRemZodwjscx+RGhAo8eIhFbs2+BFgRtFPeD/KE+zxI= -github.com/mitchellh/go-testing-interface v1.0.4 h1:ZU1VNC02qyufSZsjjs7+khruk2fKvbQ3TwRV/IBCeFA= -github.com/mitchellh/go-testing-interface v1.0.4/go.mod h1:kRemZodwjscx+RGhAo8eIhFbs2+BFgRtFPeD/KE+zxI= github.com/mitchellh/go-testing-interface v1.14.1 h1:jrgshOhYAUVNMAJiKbEu7EqAwgJJ2JqpQmpLJOu07cU= github.com/mitchellh/go-testing-interface v1.14.1/go.mod h1:gfgS7OtZj6MA4U1UrDRp04twqAjfvlZyCfX3sDjEym8= -github.com/mitchellh/go-wordwrap v0.0.0-20150314170334-ad45545899c7/go.mod h1:ZXFpozHsX6DPmq2I0TCekCxypsnAUbP2oI0UX1GXzOo= github.com/mitchellh/go-wordwrap v1.0.0 h1:6GlHJ/LTGMrIJbwgdqdl2eEH8o+Exx/0m8ir9Gns0u4= github.com/mitchellh/go-wordwrap v1.0.0/go.mod h1:ZXFpozHsX6DPmq2I0TCekCxypsnAUbP2oI0UX1GXzOo= -github.com/mitchellh/mapstructure v1.1.2 h1:fmNYVwqnSfB9mZU6OS2O6GsXM+wcskZDuKQzvN1EDeE= -github.com/mitchellh/mapstructure v1.1.2/go.mod h1:FVVH3fgwuzCH5S8UJGiWEs2h04kUh9fWfEaFds41c1Y= github.com/mitchellh/mapstructure v1.5.0 h1:jeMsZIYE/09sWLaz43PL7Gy6RuMjD2eJVyuac5Z2hdY= github.com/mitchellh/mapstructure v1.5.0/go.mod h1:bFUtVrKA4DC2yAKiSyO/QUcy7e+RRV2QTWOzhPopBRo= github.com/mitchellh/reflectwalk v1.0.0/go.mod h1:mSTlrgnPZtwu0c4WaC2kGObEpuNDbx0jmZXqmk4esnw= -github.com/mitchellh/reflectwalk v1.0.1/go.mod h1:mSTlrgnPZtwu0c4WaC2kGObEpuNDbx0jmZXqmk4esnw= github.com/mitchellh/reflectwalk v1.0.2 h1:G2LzWKi524PWgd3mLHV8Y5k7s6XUvT0Gef6zxSIeXaQ= github.com/mitchellh/reflectwalk v1.0.2/go.mod h1:mSTlrgnPZtwu0c4WaC2kGObEpuNDbx0jmZXqmk4esnw= github.com/niemeyer/pretty v0.0.0-20200227124842-a10e7caefd8e/go.mod h1:zD1mROLANZcx1PVRCS0qkT7pwLkGfwJo4zjcN/Tysno= -github.com/nsf/jsondiff v0.0.0-20200515183724-f29ed568f4ce/go.mod h1:uFMI8w+ref4v2r9jz+c9i1IfIttS/OkmLfrk1jne5hs= +github.com/nsf/jsondiff v0.0.0-20200515183724-f29ed568f4ce h1:RPclfga2SEJmgMmz2k+Mg7cowZ8yv4Trqw9UsJby758= github.com/oklog/run v1.0.0 h1:Ru7dDtJNOyC66gQ5dQmaCa0qIsAUFY3sFpK1Xk8igrw= github.com/oklog/run v1.0.0/go.mod h1:dlhp/R75TPv97u0XWUtDeV/lRKWPKSdTuV0TZvrmrQA= -github.com/pierrec/lz4 v2.0.5+incompatible/go.mod h1:pdkljMzZIN41W+lC3N2tnIh5sFi+IEE17M5jbnwPHcY= github.com/pkg/errors v0.8.1/go.mod h1:bwawxfHBFNV+L2hUp1rHADufV3IMtnDRdf1r5NINEl0= -github.com/pkg/errors v0.9.1 h1:FEBLx1zS214owpjy7qsBeixbURkuhQAwrK5UwLGTwt4= github.com/pkg/errors v0.9.1/go.mod h1:bwawxfHBFNV+L2hUp1rHADufV3IMtnDRdf1r5NINEl0= github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM= github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4= github.com/posener/complete v1.1.1/go.mod h1:em0nMJCgc9GFtwrmVmEMR/ZL6WyhyjMBndrE9hABlRI= -github.com/posener/complete v1.2.1 h1:LrvDIY//XNo65Lq84G/akBuMGlawHvGBABv8f/ZN6DI= -github.com/posener/complete v1.2.1/go.mod h1:6gapUrK/U1TAN7ciCoNRIdVC5sbdBTUh1DKN0g6uH7E= +github.com/posener/complete v1.2.3 h1:NP0eAhjcjImqslEwo/1hq7gpajME0fTLTezBKDqfXqo= +github.com/posener/complete v1.2.3/go.mod h1:WZIdtGGp+qx0sLrYKtIRAruyNpv6hFCicSgv7Sy7s/s= github.com/prometheus/client_model v0.0.0-20190812154241-14fe0d1b01d4/go.mod h1:xMI15A0UPsDsEKsMN9yxemIoYk6Tm2C1GtYGdfGttqA= github.com/rogpeppe/fastuuid v1.2.0/go.mod h1:jVj6XXZzXRy/MSR5jhDC/2q6DgLz+nrA6LYCDYWNEvQ= -github.com/rogpeppe/go-internal v1.3.0/go.mod h1:M8bDsm7K2OlrFYOpmOWEs/qY81heoFRclV5y23lUDJ4= +github.com/rogpeppe/go-internal v1.6.1 h1:/FiVV8dS/e+YqF2JvO3yXRFbBLTIuSDkuC7aBOAvL+k= github.com/russross/blackfriday v1.6.0 h1:KqfZb0pUVN2lYqZUYRddxF4OR8ZMURnJIG5Y3VRLtww= github.com/russross/blackfriday v1.6.0/go.mod h1:ti0ldHuxg49ri4ksnFxlkCfN+hvslNlmVHqNRXXJNAY= github.com/sebdah/goldie v1.0.0/go.mod h1:jXP4hmWywNEwZzhMuv2ccnqTSFpuq8iyQhtQdkkZBH4= -github.com/sergi/go-diff v1.0.0/go.mod h1:0CfEIISq7TuYL3j771MWULgwwjU+GofnZX9QAmXWZgo= github.com/sergi/go-diff v1.1.0/go.mod h1:STckp+ISIX8hZLjrqAeVduY0gWCT9IjLuqbuNXdaHfM= github.com/sergi/go-diff v1.2.0 h1:XU+rvMAioB0UC3q1MFrIQy4Vo5/4VsRDQQXHsEya6xQ= -github.com/sergi/go-diff v1.2.0/go.mod h1:STckp+ISIX8hZLjrqAeVduY0gWCT9IjLuqbuNXdaHfM= +github.com/shopspring/decimal v1.2.0/go.mod h1:DKyhrW/HYNuLGql+MJL6WCR6knT2jwCFRcu2hWCYk4o= +github.com/shopspring/decimal v1.3.1 h1:2Usl1nmF/WZucqkFZhnfFYxxxu8LG21F6nPQBE5gKV8= +github.com/shopspring/decimal v1.3.1/go.mod h1:DKyhrW/HYNuLGql+MJL6WCR6knT2jwCFRcu2hWCYk4o= github.com/sirupsen/logrus v1.4.1/go.mod h1:ni0Sbl8bgC9z8RoU9G6nDWqqs/fq4eDPysMBDgk/93Q= -github.com/sirupsen/logrus v1.7.0 h1:ShrD1U9pZB12TX0cVy0DtePoCH97K8EtX+mg7ZARUtM= -github.com/sirupsen/logrus v1.7.0/go.mod h1:yWOB1SBYBC5VeMP7gHvWumXLIWorT60ONWic61uBYv0= -github.com/spf13/afero v1.2.2 h1:5jhuqJyZCZf2JRofRvN/nIFgIWNzPa3/Vz8mYylgbWc= -github.com/spf13/afero v1.2.2/go.mod h1:9ZxEEn6pIJ8Rxe320qSDBk6AsU0r9pR7Q4OcevTdifk= -github.com/spf13/pflag v1.0.2/go.mod h1:DYY7MBk1bdzusC3SYhjObp+wFpr4gzcvqqNjLnInEg4= -github.com/spf13/pflag v1.0.3/go.mod h1:DYY7MBk1bdzusC3SYhjObp+wFpr4gzcvqqNjLnInEg4= +github.com/sirupsen/logrus v1.9.0 h1:trlNQbNUG3OdDrDil03MCb1H2o9nJ1x4/5LYw7byDE0= +github.com/sirupsen/logrus v1.9.0/go.mod h1:naHLuLoDiP4jHNo9R0sCBMtWGeIprob74mVsIT4qYEQ= +github.com/spf13/cast v1.3.1/go.mod h1:Qx5cxh0v+4UWYiBimWS+eyWzqEqokIECu5etghLkUJE= +github.com/spf13/cast v1.5.0 h1:rj3WzYc11XZaIZMPKmwP96zkFEnnAmV8s6XbB2aY32w= +github.com/spf13/cast v1.5.0/go.mod h1:SpXXQ5YoyJw6s3/6cMTQuxvgRl3PCJiyaX9p6b155UU= github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME= github.com/stretchr/objx v0.1.1/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME= github.com/stretchr/testify v1.2.2/go.mod h1:a8OnRcib4nhh0OaRAV+Yts87kKdq0PP7pXfy6kDkUVs= @@ -399,91 +235,38 @@ github.com/stretchr/testify v1.3.0/go.mod h1:M5WIy9Dh21IEIfnGCwXGc5bZfKNJtfHm1UV github.com/stretchr/testify v1.4.0/go.mod h1:j7eGeouHqKxXV5pUuKE4zz7dFj8WfuZ+81PSLYec5m4= github.com/stretchr/testify v1.5.1/go.mod h1:5W2xD1RspED5o8YsWQXVCued0rvSQ+mT+I5cxcmMvtA= github.com/stretchr/testify v1.6.1/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg= -github.com/stretchr/testify v1.7.0 h1:nwc3DEeHmmLAfoZucVR881uASk0Mfjw8xYJ99tb5CcY= github.com/stretchr/testify v1.7.0/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg= -github.com/ulikunitz/xz v0.5.5/go.mod h1:2bypXElzHzzJZwzH67Y6wb67pO62Rzfn7BSiF4ABRW8= -github.com/ulikunitz/xz v0.5.7/go.mod h1:nbz6k7qbPmH4IRqmfOplQw/tblSgqTqBwxkY0oWt/14= -github.com/ulikunitz/xz v0.5.8 h1:ERv8V6GKqVi23rgu5cj9pVfVzJbOqAY2Ntl88O6c2nQ= -github.com/ulikunitz/xz v0.5.8/go.mod h1:nbz6k7qbPmH4IRqmfOplQw/tblSgqTqBwxkY0oWt/14= +github.com/stretchr/testify v1.7.2 h1:4jaiDzPyXQvSd7D0EjG45355tLlV3VOECpq10pLC+8s= +github.com/stretchr/testify v1.7.2/go.mod h1:R6va5+xMeoiuVRoj+gSkQ7d3FALtqAAGI1FQKckRals= github.com/vmihailenco/msgpack v3.3.3+incompatible/go.mod h1:fy3FlTQTDXWkZ7Bh6AcGMlsjHatGryHQYUTf1ShIgkk= -github.com/vmihailenco/msgpack v4.0.1+incompatible h1:RMF1enSPeKTlXrXdOcqjFUElywVZjjC6pqse21bKbEU= -github.com/vmihailenco/msgpack v4.0.1+incompatible/go.mod h1:fy3FlTQTDXWkZ7Bh6AcGMlsjHatGryHQYUTf1ShIgkk= github.com/vmihailenco/msgpack v4.0.4+incompatible h1:dSLoQfGFAo3F6OoNhwUmLwVgaUXK79GlxNBwueZn0xI= github.com/vmihailenco/msgpack v4.0.4+incompatible/go.mod h1:fy3FlTQTDXWkZ7Bh6AcGMlsjHatGryHQYUTf1ShIgkk= github.com/vmihailenco/msgpack/v4 v4.3.12 h1:07s4sz9IReOgdikxLTKNbBdqDMLsjPKXwvCazn8G65U= github.com/vmihailenco/msgpack/v4 v4.3.12/go.mod h1:gborTTJjAo/GWTqqRjrLCn9pgNN+NXzzngzBKDPIqw4= github.com/vmihailenco/tagparser v0.1.1 h1:quXMXlA39OCbd2wAdTsGDlK9RkOk6Wuw+x37wVyIuWY= github.com/vmihailenco/tagparser v0.1.1/go.mod h1:OeAg3pn3UbLjkWt+rN9oFYB6u/cQgqMEUPoW2WPyhdI= -github.com/xanzy/ssh-agent v0.2.1/go.mod h1:mLlQY/MoOhWBj+gOGMQkOeiEvkx+8pJSI+0Bx9h2kr4= github.com/xanzy/ssh-agent v0.3.0 h1:wUMzuKtKilRgBAD1sUb8gOwwRr2FGoBVumcjoOACClI= github.com/xanzy/ssh-agent v0.3.0/go.mod h1:3s9xbODqPuuhK9JV1R321M/FlMZSBvE5aY6eAcqrDh0= -github.com/yuin/goldmark v1.1.25/go.mod h1:3hX8gzYuyVAZsxl0MRgGTJEmQBFcNTphYh9decYSb74= -github.com/yuin/goldmark v1.1.27/go.mod h1:3hX8gzYuyVAZsxl0MRgGTJEmQBFcNTphYh9decYSb74= -github.com/yuin/goldmark v1.1.32/go.mod h1:3hX8gzYuyVAZsxl0MRgGTJEmQBFcNTphYh9decYSb74= -github.com/zclconf/go-cty v1.0.0/go.mod h1:xnAOWiHeOqg2nWS62VtQ7pbOu17FtxJNW8RLEih+O3s= github.com/zclconf/go-cty v1.1.0/go.mod h1:xnAOWiHeOqg2nWS62VtQ7pbOu17FtxJNW8RLEih+O3s= github.com/zclconf/go-cty v1.2.0/go.mod h1:hOPWgoHbaTUnI5k4D2ld+GRpFJSCe6bCM7m1q/N4PQ8= -github.com/zclconf/go-cty v1.2.1/go.mod h1:hOPWgoHbaTUnI5k4D2ld+GRpFJSCe6bCM7m1q/N4PQ8= -github.com/zclconf/go-cty v1.8.0/go.mod h1:vVKLxnk3puL4qRAv72AO+W99LUD4da90g3uUAzyuvAk= -github.com/zclconf/go-cty v1.9.1/go.mod h1:vVKLxnk3puL4qRAv72AO+W99LUD4da90g3uUAzyuvAk= github.com/zclconf/go-cty v1.10.0 h1:mp9ZXQeIcN8kAwuqorjH+Q+njbJKjLrvB2yIh4q7U+0= github.com/zclconf/go-cty v1.10.0/go.mod h1:vVKLxnk3puL4qRAv72AO+W99LUD4da90g3uUAzyuvAk= github.com/zclconf/go-cty-debug v0.0.0-20191215020915-b22d67c1ba0b/go.mod h1:ZRKQfBXbGkpdV6QMzT3rU1kSTAnfu1dO8dPKjYprgj8= -github.com/zclconf/go-cty-yaml v1.0.1 h1:up11wlgAaDvlAGENcFDnZgkn0qUJurso7k6EpURKNF8= -github.com/zclconf/go-cty-yaml v1.0.1/go.mod h1:IP3Ylp0wQpYm50IHK8OZWKMu6sPJIUgKa8XhiVHura0= -go.opencensus.io v0.21.0/go.mod h1:mSImk1erAIZhrmZN+AvHh14ztQfjbGwt4TtuofqLduU= -go.opencensus.io v0.22.0/go.mod h1:+kGneAE2xo2IficOXnaByMWTGM9T73dGwxeWcUqIpI8= -go.opencensus.io v0.22.2/go.mod h1:yxeiOL68Rb0Xd1ddK5vPZ/oVn4vY4Ynel7k9FzqtOIw= -go.opencensus.io v0.22.3/go.mod h1:yxeiOL68Rb0Xd1ddK5vPZ/oVn4vY4Ynel7k9FzqtOIw= -go.opencensus.io v0.22.4 h1:LYy1Hy3MJdrCdMwwzxA/dRok4ejH+RwNGbuoD9fCjto= -go.opencensus.io v0.22.4/go.mod h1:yxeiOL68Rb0Xd1ddK5vPZ/oVn4vY4Ynel7k9FzqtOIw= go.opentelemetry.io/proto/otlp v0.7.0/go.mod h1:PqfVotwruBrMGOCsRd/89rSnXhoiJIqeYNgFYFoEGnI= golang.org/x/crypto v0.0.0-20190219172222-a4c6cb3142f2/go.mod h1:6SG95UA2DQfeDnfUPMdvaQW0Q7yPrPDi9nlGo2tz2b4= golang.org/x/crypto v0.0.0-20190308221718-c2843e01d9a2/go.mod h1:djNgcEr1/C05ACkg1iLfiJU5Ep61QUkGW8qpdssI0+w= -golang.org/x/crypto v0.0.0-20190426145343-a29dc8fdc734/go.mod h1:yigFU9vqHzYiE8UmvKecakEJjdnWj3jj499lnFckfCI= -golang.org/x/crypto v0.0.0-20190510104115-cbcb75029529/go.mod h1:yigFU9vqHzYiE8UmvKecakEJjdnWj3jj499lnFckfCI= -golang.org/x/crypto v0.0.0-20190605123033-f99c8df09eb5/go.mod h1:yigFU9vqHzYiE8UmvKecakEJjdnWj3jj499lnFckfCI= -golang.org/x/crypto v0.0.0-20191011191535-87dc89f01550/go.mod h1:yigFU9vqHzYiE8UmvKecakEJjdnWj3jj499lnFckfCI= -golang.org/x/crypto v0.0.0-20200302210943-78000ba7a073/go.mod h1:LzIPMQfyMNhhGPhUkYOs5KpL4U8rLKemX1yGLhDgUto= +golang.org/x/crypto v0.0.0-20200414173820-0848c9571904/go.mod h1:LzIPMQfyMNhhGPhUkYOs5KpL4U8rLKemX1yGLhDgUto= golang.org/x/crypto v0.0.0-20200622213623-75b288015ac9/go.mod h1:LzIPMQfyMNhhGPhUkYOs5KpL4U8rLKemX1yGLhDgUto= golang.org/x/crypto v0.0.0-20200820211705-5c72a883971a/go.mod h1:LzIPMQfyMNhhGPhUkYOs5KpL4U8rLKemX1yGLhDgUto= golang.org/x/crypto v0.0.0-20210322153248-0c34fe9e7dc2/go.mod h1:T9bdIzuCu7OtxOm1hfPfRQxPLYneinmdGuTeoZ9dtd4= -golang.org/x/crypto v0.0.0-20210421170649-83a5a9bb288b h1:7mWr3k41Qtv8XlltBkDkl8LoP3mpSgBW8BUoxtEdbXg= golang.org/x/crypto v0.0.0-20210421170649-83a5a9bb288b/go.mod h1:T9bdIzuCu7OtxOm1hfPfRQxPLYneinmdGuTeoZ9dtd4= golang.org/x/crypto v0.0.0-20210616213533-5ff15b29337e/go.mod h1:GvvjBRRGRdwPK5ydBHafDWAxML/pGHZbMvKqRZ5+Abc= +golang.org/x/crypto v0.0.0-20220622213112-05595931fe9d h1:sK3txAijHtOK88l68nt020reeT1ZdKLIYetKl95FzVY= +golang.org/x/crypto v0.0.0-20220622213112-05595931fe9d/go.mod h1:IxCIyHEi3zRg3s0A5j5BB6A9Jmi73HwBIUl50j+osU4= golang.org/x/exp v0.0.0-20190121172915-509febef88a4/go.mod h1:CJ0aWSM057203Lf6IL+f9T1iT9GByDxfZKAQTCR3kQA= -golang.org/x/exp v0.0.0-20190306152737-a1d7652674e8/go.mod h1:CJ0aWSM057203Lf6IL+f9T1iT9GByDxfZKAQTCR3kQA= -golang.org/x/exp v0.0.0-20190510132918-efd6b22b2522/go.mod h1:ZjyILWgesfNpC6sMxTJOJm9Kp84zZh5NQWvqDGG3Qr8= -golang.org/x/exp v0.0.0-20190829153037-c13cbed26979/go.mod h1:86+5VVa7VpoJ4kLfm080zCjGlMRFzhUhsZKEZO7MGek= -golang.org/x/exp v0.0.0-20191030013958-a1ab85dbe136/go.mod h1:JXzH8nQsPlswgeRAPE3MuO9GYsAcnJvJ4vnMwN/5qkY= -golang.org/x/exp v0.0.0-20191129062945-2f5052295587/go.mod h1:2RIsYlXP63K8oxa1u096TMicItID8zy7Y6sNkU49FU4= -golang.org/x/exp v0.0.0-20191227195350-da58074b4299/go.mod h1:2RIsYlXP63K8oxa1u096TMicItID8zy7Y6sNkU49FU4= -golang.org/x/exp v0.0.0-20200119233911-0405dc783f0a/go.mod h1:2RIsYlXP63K8oxa1u096TMicItID8zy7Y6sNkU49FU4= -golang.org/x/exp v0.0.0-20200207192155-f17229e696bd/go.mod h1:J/WKrq2StrnmMY6+EHIKF9dgMWnmCNThgcyBT1FY9mM= -golang.org/x/exp v0.0.0-20200224162631-6cc2880d07d6/go.mod h1:3jZMyOhIsHpP37uCMkUooju7aAi5cS1Q23tOzKc+0MU= -golang.org/x/image v0.0.0-20190227222117-0694c2d4d067/go.mod h1:kZ7UVZpmo3dzQBMxlp+ypCbDeSB+sBbTgSJuh5dn5js= -golang.org/x/image v0.0.0-20190802002840-cff245a6509b/go.mod h1:FeLwcggjj3mMvU+oOTbSwawSJRM1uh48EjtB4UJZlP0= golang.org/x/lint v0.0.0-20181026193005-c67002cb31c3/go.mod h1:UVdnD1Gm6xHRNCYTkRU2/jEulfH38KcIWyp/GAMgvoE= golang.org/x/lint v0.0.0-20190227174305-5b3e6a55c961/go.mod h1:wehouNa3lNwaWXcvxsM5YxQ5yQlVC4a0KAMCusXpPoU= -golang.org/x/lint v0.0.0-20190301231843-5614ed5bae6f/go.mod h1:UVdnD1Gm6xHRNCYTkRU2/jEulfH38KcIWyp/GAMgvoE= golang.org/x/lint v0.0.0-20190313153728-d0100b6bd8b3/go.mod h1:6SW0HCj/g11FgYtHlgUYUwCkIfeOF89ocIRzGO/8vkc= -golang.org/x/lint v0.0.0-20190409202823-959b441ac422/go.mod h1:6SW0HCj/g11FgYtHlgUYUwCkIfeOF89ocIRzGO/8vkc= -golang.org/x/lint v0.0.0-20190909230951-414d861bb4ac/go.mod h1:6SW0HCj/g11FgYtHlgUYUwCkIfeOF89ocIRzGO/8vkc= -golang.org/x/lint v0.0.0-20190930215403-16217165b5de/go.mod h1:6SW0HCj/g11FgYtHlgUYUwCkIfeOF89ocIRzGO/8vkc= -golang.org/x/lint v0.0.0-20191125180803-fdd1cda4f05f/go.mod h1:5qLYkcX4OjUUV8bRuDixDT3tpyyb+LUpUlRWLxfhWrs= -golang.org/x/lint v0.0.0-20200130185559-910be7a94367/go.mod h1:3xt1FjdF8hUf6vQPIChWIBhFzV8gjjsPE/fR3IyQdNY= -golang.org/x/lint v0.0.0-20200302205851-738671d3881b h1:Wh+f8QHJXR411sJR8/vRBTZ7YapZaRvUcLFFJhusH0k= -golang.org/x/lint v0.0.0-20200302205851-738671d3881b/go.mod h1:3xt1FjdF8hUf6vQPIChWIBhFzV8gjjsPE/fR3IyQdNY= -golang.org/x/mobile v0.0.0-20190312151609-d3739f865fa6/go.mod h1:z+o9i4GpDbdi3rU15maQ/Ox0txvL9dWGYEHz965HBQE= -golang.org/x/mobile v0.0.0-20190719004257-d2bd2a29d028/go.mod h1:E/iHnbuqvinMTCcRqshq8CkpyQDoeVncDDYHnLhea+o= -golang.org/x/mod v0.0.0-20190513183733-4bf6d317e70e/go.mod h1:mXi4GBBbnImb6dmsKGUJ2LatrhH/nqhxcFungHvyanc= -golang.org/x/mod v0.1.0/go.mod h1:0QHyrYULN0/3qlju5TqG8bIK38QM8yzMo5ekMj3DlcY= -golang.org/x/mod v0.1.1-0.20191105210325-c90efee705ee/go.mod h1:QqPTAvyqsEbceGzBzNggFXnrqF1CaUcvgkdR5Ot7KZg= -golang.org/x/mod v0.1.1-0.20191107180719-034126e5016b/go.mod h1:QqPTAvyqsEbceGzBzNggFXnrqF1CaUcvgkdR5Ot7KZg= -golang.org/x/mod v0.2.0/go.mod h1:s0Qsj1ACt9ePp/hMypM3fl4fZqREWJwdYDEqhRiZZUA= -golang.org/x/mod v0.3.0 h1:RM4zey1++hCTbCVQfnWeKs9/IEsaBLA8vTkd0WVtmH4= -golang.org/x/mod v0.3.0/go.mod h1:s0Qsj1ACt9ePp/hMypM3fl4fZqREWJwdYDEqhRiZZUA= -golang.org/x/net v0.0.0-20180530234432-1e491301e022/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4= golang.org/x/net v0.0.0-20180724234803-3673e40ba225/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4= golang.org/x/net v0.0.0-20180811021610-c39426892332/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4= golang.org/x/net v0.0.0-20180826012351-8a410e7b638d/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4= @@ -491,78 +274,33 @@ golang.org/x/net v0.0.0-20190108225652-1e06a53dbb7e/go.mod h1:mL1N/T3taQHkDXs73r golang.org/x/net v0.0.0-20190213061140-3a22650c66bd/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4= golang.org/x/net v0.0.0-20190311183353-d8887717615a/go.mod h1:t9HGtf8HONx5eT2rtn7q6eTqICYqUVnKs3thJo3Qplg= golang.org/x/net v0.0.0-20190404232315-eb5bcb51f2a3/go.mod h1:t9HGtf8HONx5eT2rtn7q6eTqICYqUVnKs3thJo3Qplg= -golang.org/x/net v0.0.0-20190501004415-9ce7a6920f09/go.mod h1:t9HGtf8HONx5eT2rtn7q6eTqICYqUVnKs3thJo3Qplg= -golang.org/x/net v0.0.0-20190503192946-f4e77d36d62c/go.mod h1:t9HGtf8HONx5eT2rtn7q6eTqICYqUVnKs3thJo3Qplg= golang.org/x/net v0.0.0-20190603091049-60506f45cf65/go.mod h1:HSz+uSET+XFnRR8LxR5pz3Of3rY3CfYBVs4xY44aLks= -golang.org/x/net v0.0.0-20190620200207-3b0461eec859/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s= -golang.org/x/net v0.0.0-20190628185345-da137c7871d7/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s= -golang.org/x/net v0.0.0-20190724013045-ca1201d0de80/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s= golang.org/x/net v0.0.0-20191009170851-d66e71096ffb/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s= -golang.org/x/net v0.0.0-20191209160850-c0dbc17a3553/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s= -golang.org/x/net v0.0.0-20200114155413-6afb5195e5aa/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s= -golang.org/x/net v0.0.0-20200202094626-16171245cfb2/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s= -golang.org/x/net v0.0.0-20200222125558-5a598a2470a0/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s= -golang.org/x/net v0.0.0-20200226121028-0de0cce0169b/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s= golang.org/x/net v0.0.0-20200301022130-244492dfa37a/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s= -golang.org/x/net v0.0.0-20200324143707-d3edc9973b7e/go.mod h1:qpuaurCH72eLCgpAm/N6yyVIVM9cpaDIP3A8BGJEC5A= -golang.org/x/net v0.0.0-20200501053045-e0ff5e5a1de5/go.mod h1:qpuaurCH72eLCgpAm/N6yyVIVM9cpaDIP3A8BGJEC5A= -golang.org/x/net v0.0.0-20200506145744-7e3656a0809f/go.mod h1:qpuaurCH72eLCgpAm/N6yyVIVM9cpaDIP3A8BGJEC5A= -golang.org/x/net v0.0.0-20200513185701-a91f0712d120/go.mod h1:qpuaurCH72eLCgpAm/N6yyVIVM9cpaDIP3A8BGJEC5A= -golang.org/x/net v0.0.0-20200520182314-0ba52f642ac2/go.mod h1:qpuaurCH72eLCgpAm/N6yyVIVM9cpaDIP3A8BGJEC5A= -golang.org/x/net v0.0.0-20200625001655-4c5254603344/go.mod h1:/O7V0waA8r7cgGh81Ro3o1hOxt32SMVPicZroKQ2sZA= -golang.org/x/net v0.0.0-20200707034311-ab3426394381/go.mod h1:/O7V0waA8r7cgGh81Ro3o1hOxt32SMVPicZroKQ2sZA= golang.org/x/net v0.0.0-20200822124328-c89045814202/go.mod h1:/O7V0waA8r7cgGh81Ro3o1hOxt32SMVPicZroKQ2sZA= golang.org/x/net v0.0.0-20201021035429-f5854403a974/go.mod h1:sp8m0HH+o8qH0wwXwYZr8TS3Oi6o0r6Gce1SSxlDquU= golang.org/x/net v0.0.0-20210119194325-5f4716e94777/go.mod h1:m0MpNAwzfU5UDzcl9v0D8zg8gWTRqZa9RBIspLL5mdg= golang.org/x/net v0.0.0-20210226172049-e18ecbb05110/go.mod h1:m0MpNAwzfU5UDzcl9v0D8zg8gWTRqZa9RBIspLL5mdg= -golang.org/x/net v0.0.0-20210326060303-6b1517762897 h1:KrsHThm5nFk34YtATK1LsThyGhGbGe1olrte/HInHvs= golang.org/x/net v0.0.0-20210326060303-6b1517762897/go.mod h1:uSPa2vr4CLtc/ILN5odXGNXS6mhrKVzTaCXzk9m6W3k= +golang.org/x/net v0.0.0-20211112202133-69e39bad7dc2 h1:CIJ76btIcR3eFI5EgSo6k1qKw9KJexJuRLI9G7Hp5wE= +golang.org/x/net v0.0.0-20211112202133-69e39bad7dc2/go.mod h1:9nx3DQGgdP8bBQD5qxJ1jj9UTztislL4KSBs9R2vV5Y= golang.org/x/oauth2 v0.0.0-20180821212333-d2e6202438be/go.mod h1:N/0e6XlmueqKjAGxoOufVs8QHGRruUQn6yWY3a++T0U= -golang.org/x/oauth2 v0.0.0-20190226205417-e64efc72b421/go.mod h1:gOpvHmFTYa4IltrdGE7lF6nIHvwfUNPOp7c8zoXwtLw= golang.org/x/oauth2 v0.0.0-20190604053449-0f29369cfe45/go.mod h1:gOpvHmFTYa4IltrdGE7lF6nIHvwfUNPOp7c8zoXwtLw= -golang.org/x/oauth2 v0.0.0-20191202225959-858c2ad4c8b6/go.mod h1:gOpvHmFTYa4IltrdGE7lF6nIHvwfUNPOp7c8zoXwtLw= -golang.org/x/oauth2 v0.0.0-20200107190931-bf48bf16ab8d h1:TzXSXBo42m9gQenoE3b9BGiEpg5IG2JkU5FkPIawgtw= golang.org/x/oauth2 v0.0.0-20200107190931-bf48bf16ab8d/go.mod h1:gOpvHmFTYa4IltrdGE7lF6nIHvwfUNPOp7c8zoXwtLw= golang.org/x/sync v0.0.0-20180314180146-1d60e4601c6f/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= golang.org/x/sync v0.0.0-20181108010431-42b317875d0f/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= golang.org/x/sync v0.0.0-20181221193216-37e7f081c4d4/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= -golang.org/x/sync v0.0.0-20190227155943-e225da77a7e6/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= golang.org/x/sync v0.0.0-20190423024810-112230192c58/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= -golang.org/x/sync v0.0.0-20190911185100-cd5d95a43a6e/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= -golang.org/x/sync v0.0.0-20200317015054-43a5402ce75a/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= -golang.org/x/sync v0.0.0-20200625203802-6e8e738ad208/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= -golang.org/x/sys v0.0.0-20180823144017-11551d06cbcc/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= golang.org/x/sys v0.0.0-20180830151530-49385e6e1522/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= golang.org/x/sys v0.0.0-20180905080454-ebe1bf3edb33/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= golang.org/x/sys v0.0.0-20190215142949-d0b11bdaac8a/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= -golang.org/x/sys v0.0.0-20190221075227-b4e8571b14e0/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= -golang.org/x/sys v0.0.0-20190222072716-a9d3bda3a223/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= -golang.org/x/sys v0.0.0-20190312061237-fead79001313/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/sys v0.0.0-20190412213103-97732733099d/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= -golang.org/x/sys v0.0.0-20190502145724-3ef323f4f1fd/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= -golang.org/x/sys v0.0.0-20190502175342-a43fa875dd82/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/sys v0.0.0-20190507160741-ecd444e8653b/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= -golang.org/x/sys v0.0.0-20190606165138-5da285871e9c/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= -golang.org/x/sys v0.0.0-20190624142023-c5567b49c5d0/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= -golang.org/x/sys v0.0.0-20190726091711-fc99dfbffb4e/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/sys v0.0.0-20190916202348-b4ddaad3f8a3/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= -golang.org/x/sys v0.0.0-20191001151750-bb3f8db39f24/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= -golang.org/x/sys v0.0.0-20191008105621-543471e840be/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= -golang.org/x/sys v0.0.0-20191026070338-33540a1f6037/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= -golang.org/x/sys v0.0.0-20191204072324-ce4227a45e2e/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= -golang.org/x/sys v0.0.0-20191228213918-04cbcbbfeed8/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= -golang.org/x/sys v0.0.0-20200113162924-86b910548bc1/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= -golang.org/x/sys v0.0.0-20200122134326-e047566fdf82/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= -golang.org/x/sys v0.0.0-20200202164722-d101bd2416d5/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= -golang.org/x/sys v0.0.0-20200212091648-12a6c2dcc1e4/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20200116001909-b77594299b42/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/sys v0.0.0-20200223170610-d5e6a3e2c0ae/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/sys v0.0.0-20200302150141-5c8b2ff67527/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/sys v0.0.0-20200323222414-85ca7c5b95cd/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= -golang.org/x/sys v0.0.0-20200331124033-c3d80250170d/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= -golang.org/x/sys v0.0.0-20200501052902-10377860bb8e/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= -golang.org/x/sys v0.0.0-20200511232937-7e40ca221e25/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= -golang.org/x/sys v0.0.0-20200515095857-1151b9dac4a9/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= -golang.org/x/sys v0.0.0-20200523222454-059865788121/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/sys v0.0.0-20200930185726-fdedc70b468f/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/sys v0.0.0-20201119102817-f84b799fce68/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/sys v0.0.0-20210119212857-b64e53b001e4/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= @@ -571,135 +309,43 @@ golang.org/x/sys v0.0.0-20210324051608-47abb6519492/go.mod h1:h1NjWce9XRLGQEsW7w golang.org/x/sys v0.0.0-20210502180810-71e4cd670f79/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/sys v0.0.0-20210615035016-665e8c7367d1/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.0.0-20210630005230-0f9fa26af87c/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= -golang.org/x/sys v0.0.0-20210927094055-39ccf1dd6fa6 h1:foEbQz/B0Oz6YIqu/69kfXPYeFQAuuMYFkjaqXzl5Wo= golang.org/x/sys v0.0.0-20210927094055-39ccf1dd6fa6/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= -golang.org/x/term v0.0.0-20201126162022-7de9c90e9dd1 h1:v+OssWQX+hTHEmOBgwxdZxK4zHq3yOs8F9J7mk0PY8E= +golang.org/x/sys v0.0.0-20220503163025-988cb79eb6c6/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= +golang.org/x/sys v0.0.0-20220715151400-c0bba94af5f8 h1:0A+M6Uqn+Eje4kHMK80dtF3JCXC4ykBgQG4Fe06QRhQ= +golang.org/x/sys v0.0.0-20220715151400-c0bba94af5f8/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/term v0.0.0-20201126162022-7de9c90e9dd1/go.mod h1:bj7SfCRtBDWHUb9snDiAeCFNEtKQo2Wmx5Cou7ajbmo= -golang.org/x/text v0.0.0-20170915032832-14c0d48ead0c/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ= golang.org/x/text v0.3.0/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ= -golang.org/x/text v0.3.1-0.20180807135948-17ff2d5776d2/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ= golang.org/x/text v0.3.2/go.mod h1:bEr9sfX3Q8Zfm5fL9x+3itogRgK3+ptLWKqgva+5dAk= golang.org/x/text v0.3.3/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ= -golang.org/x/text v0.3.5 h1:i6eZZ+zk0SOf0xgBpEpPD18qWcJda6q1sxt3S0kzyUQ= golang.org/x/text v0.3.5/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ= -golang.org/x/time v0.0.0-20181108054448-85acf8d2951c/go.mod h1:tRJNPiyCQ0inRvYxbN9jk5I+vvW/OXSQhTDSoE431IQ= -golang.org/x/time v0.0.0-20190308202827-9d24e82272b4/go.mod h1:tRJNPiyCQ0inRvYxbN9jk5I+vvW/OXSQhTDSoE431IQ= -golang.org/x/time v0.0.0-20191024005414-555d28b269f0/go.mod h1:tRJNPiyCQ0inRvYxbN9jk5I+vvW/OXSQhTDSoE431IQ= +golang.org/x/text v0.3.7 h1:olpwvP2KacW1ZWvsR7uQhoyTYvKAupfQrRGBFM352Gk= +golang.org/x/text v0.3.7/go.mod h1:u+2+/6zg+i71rQMx5EYifcz6MCKuco9NR6JIITiCfzQ= golang.org/x/tools v0.0.0-20180917221912-90fa682c2a6e/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ= golang.org/x/tools v0.0.0-20190114222345-bf090417da8b/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ= golang.org/x/tools v0.0.0-20190226205152-f727befe758c/go.mod h1:9Yl7xja0Znq3iFh3HoIrodX9oNMXvdceNzlUR8zjMvY= golang.org/x/tools v0.0.0-20190311212946-11955173bddd/go.mod h1:LCzVGOaR6xXOjkQ3onu1FJEFr0SW1gC7cKk1uF8kGRs= -golang.org/x/tools v0.0.0-20190312151545-0bb0c0a6e846/go.mod h1:LCzVGOaR6xXOjkQ3onu1FJEFr0SW1gC7cKk1uF8kGRs= -golang.org/x/tools v0.0.0-20190312170243-e65039ee4138/go.mod h1:LCzVGOaR6xXOjkQ3onu1FJEFr0SW1gC7cKk1uF8kGRs= -golang.org/x/tools v0.0.0-20190425150028-36563e24a262/go.mod h1:RgjU9mgBXZiqYHBnxXauZ1Gv1EHHAz9KjViQ78xBX0Q= -golang.org/x/tools v0.0.0-20190506145303-2d16b83fe98c/go.mod h1:RgjU9mgBXZiqYHBnxXauZ1Gv1EHHAz9KjViQ78xBX0Q= golang.org/x/tools v0.0.0-20190524140312-2c0ae7006135/go.mod h1:RgjU9mgBXZiqYHBnxXauZ1Gv1EHHAz9KjViQ78xBX0Q= -golang.org/x/tools v0.0.0-20190606124116-d0a3d012864b/go.mod h1:/rFqwRUd4F7ZHNgwSSTFct+R/Kf4OFW1sUzUTQQTgfc= -golang.org/x/tools v0.0.0-20190621195816-6e04913cbbac/go.mod h1:/rFqwRUd4F7ZHNgwSSTFct+R/Kf4OFW1sUzUTQQTgfc= -golang.org/x/tools v0.0.0-20190628153133-6cdbf07be9d0/go.mod h1:/rFqwRUd4F7ZHNgwSSTFct+R/Kf4OFW1sUzUTQQTgfc= -golang.org/x/tools v0.0.0-20190816200558-6889da9d5479/go.mod h1:b+2E5dAYhXwXZwtnZ6UAqBI28+e2cm9otk0dWdXHAEo= -golang.org/x/tools v0.0.0-20190911174233-4f2ddba30aff/go.mod h1:b+2E5dAYhXwXZwtnZ6UAqBI28+e2cm9otk0dWdXHAEo= -golang.org/x/tools v0.0.0-20191012152004-8de300cfc20a/go.mod h1:b+2E5dAYhXwXZwtnZ6UAqBI28+e2cm9otk0dWdXHAEo= -golang.org/x/tools v0.0.0-20191113191852-77e3bb0ad9e7/go.mod h1:b+2E5dAYhXwXZwtnZ6UAqBI28+e2cm9otk0dWdXHAEo= -golang.org/x/tools v0.0.0-20191115202509-3a792d9c32b2/go.mod h1:b+2E5dAYhXwXZwtnZ6UAqBI28+e2cm9otk0dWdXHAEo= -golang.org/x/tools v0.0.0-20191119224855-298f0cb1881e/go.mod h1:b+2E5dAYhXwXZwtnZ6UAqBI28+e2cm9otk0dWdXHAEo= -golang.org/x/tools v0.0.0-20191125144606-a911d9008d1f/go.mod h1:b+2E5dAYhXwXZwtnZ6UAqBI28+e2cm9otk0dWdXHAEo= -golang.org/x/tools v0.0.0-20191130070609-6e064ea0cf2d/go.mod h1:b+2E5dAYhXwXZwtnZ6UAqBI28+e2cm9otk0dWdXHAEo= -golang.org/x/tools v0.0.0-20191216173652-a0e659d51361/go.mod h1:TB2adYChydJhpapKDTa4BR/hXlZSLoq2Wpct/0txZ28= -golang.org/x/tools v0.0.0-20191227053925-7b8e75db28f4/go.mod h1:TB2adYChydJhpapKDTa4BR/hXlZSLoq2Wpct/0txZ28= -golang.org/x/tools v0.0.0-20200117161641-43d50277825c/go.mod h1:TB2adYChydJhpapKDTa4BR/hXlZSLoq2Wpct/0txZ28= -golang.org/x/tools v0.0.0-20200122220014-bf1340f18c4a/go.mod h1:TB2adYChydJhpapKDTa4BR/hXlZSLoq2Wpct/0txZ28= -golang.org/x/tools v0.0.0-20200130002326-2f3ba24bd6e7/go.mod h1:TB2adYChydJhpapKDTa4BR/hXlZSLoq2Wpct/0txZ28= -golang.org/x/tools v0.0.0-20200204074204-1cc6d1ef6c74/go.mod h1:TB2adYChydJhpapKDTa4BR/hXlZSLoq2Wpct/0txZ28= -golang.org/x/tools v0.0.0-20200207183749-b753a1ba74fa/go.mod h1:TB2adYChydJhpapKDTa4BR/hXlZSLoq2Wpct/0txZ28= -golang.org/x/tools v0.0.0-20200212150539-ea181f53ac56/go.mod h1:TB2adYChydJhpapKDTa4BR/hXlZSLoq2Wpct/0txZ28= -golang.org/x/tools v0.0.0-20200224181240-023911ca70b2/go.mod h1:TB2adYChydJhpapKDTa4BR/hXlZSLoq2Wpct/0txZ28= -golang.org/x/tools v0.0.0-20200227222343-706bc42d1f0d/go.mod h1:TB2adYChydJhpapKDTa4BR/hXlZSLoq2Wpct/0txZ28= -golang.org/x/tools v0.0.0-20200304193943-95d2e580d8eb/go.mod h1:o4KQGtdN14AW+yjsvvwRTJJuXz8XRtIHtEnmAXLyFUw= -golang.org/x/tools v0.0.0-20200312045724-11d5b4c81c7d/go.mod h1:o4KQGtdN14AW+yjsvvwRTJJuXz8XRtIHtEnmAXLyFUw= -golang.org/x/tools v0.0.0-20200331025713-a30bf2db82d4/go.mod h1:Sl4aGygMT6LrqrWclx+PTx3U+LnKx/seiNR+3G19Ar8= -golang.org/x/tools v0.0.0-20200501065659-ab2804fb9c9d/go.mod h1:EkVYQZoAsY45+roYkvgYkIh4xh/qjgUK9TdY2XT94GE= -golang.org/x/tools v0.0.0-20200512131952-2bc93b1c0c88/go.mod h1:EkVYQZoAsY45+roYkvgYkIh4xh/qjgUK9TdY2XT94GE= -golang.org/x/tools v0.0.0-20200515010526-7d3b6ebf133d/go.mod h1:EkVYQZoAsY45+roYkvgYkIh4xh/qjgUK9TdY2XT94GE= -golang.org/x/tools v0.0.0-20200618134242-20370b0cb4b2/go.mod h1:EkVYQZoAsY45+roYkvgYkIh4xh/qjgUK9TdY2XT94GE= -golang.org/x/tools v0.0.0-20200713011307-fd294ab11aed h1:+qzWo37K31KxduIYaBeMqJ8MUOyTayOQKpH9aDPLMSY= -golang.org/x/tools v0.0.0-20200713011307-fd294ab11aed/go.mod h1:njjCfa9FT2d7l9Bc6FUM5FLjQPp3cFF28FI3qnDFljA= -golang.org/x/xerrors v0.0.0-20190717185122-a985d3407aa7/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= -golang.org/x/xerrors v0.0.0-20191011141410-1b5146add898/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= -golang.org/x/xerrors v0.0.0-20191204190536-9bdfabe68543 h1:E7g+9GITq07hpfrRu66IVDexMakfv52eLZ2CXBWiKr4= golang.org/x/xerrors v0.0.0-20191204190536-9bdfabe68543/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= golang.org/x/xerrors v0.0.0-20200804184101-5ec99f83aff1/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= -google.golang.org/api v0.4.0/go.mod h1:8k5glujaEP+g9n7WNsDg8QP6cUVNI86fCNMcbazEtwE= -google.golang.org/api v0.7.0/go.mod h1:WtwebWUNSVBH/HAw79HIFXZNqEvBhG+Ra+ax0hx3E3M= -google.golang.org/api v0.8.0/go.mod h1:o4eAsZoiT+ibD93RtjEohWalFOjRDx6CVaqeizhEnKg= -google.golang.org/api v0.9.0/go.mod h1:o4eAsZoiT+ibD93RtjEohWalFOjRDx6CVaqeizhEnKg= -google.golang.org/api v0.13.0/go.mod h1:iLdEw5Ide6rF15KTC1Kkl0iskquN2gFfn9o9XIsbkAI= -google.golang.org/api v0.14.0/go.mod h1:iLdEw5Ide6rF15KTC1Kkl0iskquN2gFfn9o9XIsbkAI= -google.golang.org/api v0.15.0/go.mod h1:iLdEw5Ide6rF15KTC1Kkl0iskquN2gFfn9o9XIsbkAI= -google.golang.org/api v0.17.0/go.mod h1:BwFmGc8tA3vsd7r/7kR8DY7iEEGSU04BFxCo5jP/sfE= -google.golang.org/api v0.18.0/go.mod h1:BwFmGc8tA3vsd7r/7kR8DY7iEEGSU04BFxCo5jP/sfE= -google.golang.org/api v0.19.0/go.mod h1:BwFmGc8tA3vsd7r/7kR8DY7iEEGSU04BFxCo5jP/sfE= -google.golang.org/api v0.20.0/go.mod h1:BwFmGc8tA3vsd7r/7kR8DY7iEEGSU04BFxCo5jP/sfE= -google.golang.org/api v0.22.0/go.mod h1:BwFmGc8tA3vsd7r/7kR8DY7iEEGSU04BFxCo5jP/sfE= -google.golang.org/api v0.24.0/go.mod h1:lIXQywCXRcnZPGlsd8NbLnOjtAoL6em04bJ9+z0MncE= -google.golang.org/api v0.28.0/go.mod h1:lIXQywCXRcnZPGlsd8NbLnOjtAoL6em04bJ9+z0MncE= -google.golang.org/api v0.29.0 h1:BaiDisFir8O4IJxvAabCGGkQ6yCJegNQqSVoYUNAnbk= -google.golang.org/api v0.29.0/go.mod h1:Lcubydp8VUV7KeIHD9z2Bys/sm/vGKnG1UHuDBSrHWM= google.golang.org/appengine v1.1.0/go.mod h1:EbEs0AVv82hx2wNQdGPgUI5lhzA/G0D9YwlJXL52JkM= google.golang.org/appengine v1.4.0/go.mod h1:xpcJRLb0r/rnEns0DIKYYv+WjYCduHsrkT7/EB5XEv4= -google.golang.org/appengine v1.5.0/go.mod h1:xpcJRLb0r/rnEns0DIKYYv+WjYCduHsrkT7/EB5XEv4= -google.golang.org/appengine v1.6.1/go.mod h1:i06prIuMbXzDqacNJfV5OdTW448YApPu5ww/cMBSeb0= google.golang.org/appengine v1.6.5/go.mod h1:8WjMMxjGQR8xUklV/ARdw2HLXBOI7O7uCIDZVag1xfc= google.golang.org/appengine v1.6.6 h1:lMO5rYAqUxkmaj76jAkRUvt5JZgFymx/+Q5Mzfivuhc= google.golang.org/appengine v1.6.6/go.mod h1:8WjMMxjGQR8xUklV/ARdw2HLXBOI7O7uCIDZVag1xfc= -google.golang.org/genproto v0.0.0-20170818010345-ee236bd376b0/go.mod h1:JiN7NxoALGmiZfu7CAH4rXhgtRTLTxftemlI0sWmxmc= google.golang.org/genproto v0.0.0-20180817151627-c66870c02cf8/go.mod h1:JiN7NxoALGmiZfu7CAH4rXhgtRTLTxftemlI0sWmxmc= -google.golang.org/genproto v0.0.0-20190307195333-5fe7a883aa19/go.mod h1:VzzqZJRnGkLBvHegQrXjBqPurQTc5/KpmUdxsrq26oE= -google.golang.org/genproto v0.0.0-20190418145605-e7d98fc518a7/go.mod h1:VzzqZJRnGkLBvHegQrXjBqPurQTc5/KpmUdxsrq26oE= -google.golang.org/genproto v0.0.0-20190425155659-357c62f0e4bb/go.mod h1:VzzqZJRnGkLBvHegQrXjBqPurQTc5/KpmUdxsrq26oE= -google.golang.org/genproto v0.0.0-20190502173448-54afdca5d873/go.mod h1:VzzqZJRnGkLBvHegQrXjBqPurQTc5/KpmUdxsrq26oE= -google.golang.org/genproto v0.0.0-20190801165951-fa694d86fc64/go.mod h1:DMBHOl98Agz4BDEuKkezgsaosCRResVns1a3J2ZsMNc= google.golang.org/genproto v0.0.0-20190819201941-24fa4b261c55/go.mod h1:DMBHOl98Agz4BDEuKkezgsaosCRResVns1a3J2ZsMNc= -google.golang.org/genproto v0.0.0-20190911173649-1774047e7e51/go.mod h1:IbNlFCBrqXvoKpeg0TB2l7cyZUmoaFKYIwrEpbDKLA8= -google.golang.org/genproto v0.0.0-20191108220845-16a3f7862a1a/go.mod h1:n3cpQtvxv34hfy77yVDNjmbRyujviMdxYliBSkLhpCc= -google.golang.org/genproto v0.0.0-20191115194625-c23dd37a84c9/go.mod h1:n3cpQtvxv34hfy77yVDNjmbRyujviMdxYliBSkLhpCc= -google.golang.org/genproto v0.0.0-20191216164720-4f79533eabd1/go.mod h1:n3cpQtvxv34hfy77yVDNjmbRyujviMdxYliBSkLhpCc= -google.golang.org/genproto v0.0.0-20191230161307-f3c370f40bfb/go.mod h1:n3cpQtvxv34hfy77yVDNjmbRyujviMdxYliBSkLhpCc= -google.golang.org/genproto v0.0.0-20200115191322-ca5a22157cba/go.mod h1:n3cpQtvxv34hfy77yVDNjmbRyujviMdxYliBSkLhpCc= -google.golang.org/genproto v0.0.0-20200122232147-0452cf42e150/go.mod h1:n3cpQtvxv34hfy77yVDNjmbRyujviMdxYliBSkLhpCc= -google.golang.org/genproto v0.0.0-20200204135345-fa8e72b47b90/go.mod h1:GmwEX6Z4W5gMy59cAlVYjN9JhxgbQH6Gn+gFDQe2lzA= -google.golang.org/genproto v0.0.0-20200212174721-66ed5ce911ce/go.mod h1:55QSHmfGQM9UVYDPBsyGGes0y52j32PQ3BqQfXhyH3c= -google.golang.org/genproto v0.0.0-20200224152610-e50cd9704f63/go.mod h1:55QSHmfGQM9UVYDPBsyGGes0y52j32PQ3BqQfXhyH3c= -google.golang.org/genproto v0.0.0-20200228133532-8c2c7df3a383/go.mod h1:55QSHmfGQM9UVYDPBsyGGes0y52j32PQ3BqQfXhyH3c= -google.golang.org/genproto v0.0.0-20200305110556-506484158171/go.mod h1:55QSHmfGQM9UVYDPBsyGGes0y52j32PQ3BqQfXhyH3c= -google.golang.org/genproto v0.0.0-20200312145019-da6875a35672/go.mod h1:55QSHmfGQM9UVYDPBsyGGes0y52j32PQ3BqQfXhyH3c= -google.golang.org/genproto v0.0.0-20200331122359-1ee6d9798940/go.mod h1:55QSHmfGQM9UVYDPBsyGGes0y52j32PQ3BqQfXhyH3c= -google.golang.org/genproto v0.0.0-20200430143042-b979b6f78d84/go.mod h1:55QSHmfGQM9UVYDPBsyGGes0y52j32PQ3BqQfXhyH3c= -google.golang.org/genproto v0.0.0-20200511104702-f5ebc3bea380/go.mod h1:55QSHmfGQM9UVYDPBsyGGes0y52j32PQ3BqQfXhyH3c= google.golang.org/genproto v0.0.0-20200513103714-09dca8ec2884/go.mod h1:55QSHmfGQM9UVYDPBsyGGes0y52j32PQ3BqQfXhyH3c= -google.golang.org/genproto v0.0.0-20200515170657-fc4c6c6a6587/go.mod h1:YsZOwe1myG/8QRHRsmBRE1LrgQY60beZKjly0O1fX9U= google.golang.org/genproto v0.0.0-20200526211855-cb27e3aa2013/go.mod h1:NbSheEEYHJ7i3ixzK3sjbqSGDJWnxyFXZblF3eUsNvo= -google.golang.org/genproto v0.0.0-20200618031413-b414f8b61790/go.mod h1:jDfRM7FcilCzHH/e9qn6dsT145K34l5v+OpcnNgKAAA= google.golang.org/genproto v0.0.0-20200711021454-869866162049 h1:YFTFpQhgvrLrmxtiIncJxFXeCyq84ixuKWVCaCAi9Oc= google.golang.org/genproto v0.0.0-20200711021454-869866162049/go.mod h1:FWY/as6DDZQgahTzZj3fqbO1CbirC29ZNUFHwi0/+no= -google.golang.org/grpc v1.8.0/go.mod h1:yo6s7OP7yaDglbqo1J04qKzAhqBH6lvTonzMVmEdcZw= google.golang.org/grpc v1.19.0/go.mod h1:mqu4LbDTu4XGKhr4mRzUsmM4RtVoemTSY81AxZiDr8c= -google.golang.org/grpc v1.20.1/go.mod h1:10oTOabMzJvdu6/UiuZezV6QK5dSlG84ov/aaiqXj38= -google.golang.org/grpc v1.21.1/go.mod h1:oYelfM1adQP15Ek0mdvEgi9Df8B9CZIaU1084ijfRaM= google.golang.org/grpc v1.23.0/go.mod h1:Y5yQAOtifL1yxbo5wqy6BxZv8vAUGQwXBOALyacEbxg= google.golang.org/grpc v1.25.1/go.mod h1:c3i+UQWmh7LiEpx4sFZnkU36qjEYZ0imhYfXVyQciAY= -google.golang.org/grpc v1.26.0/go.mod h1:qbnxyOmOxrQa7FizSgH+ReBfzJrCY1pSN7KXBS8abTk= google.golang.org/grpc v1.27.0/go.mod h1:qbnxyOmOxrQa7FizSgH+ReBfzJrCY1pSN7KXBS8abTk= -google.golang.org/grpc v1.27.1/go.mod h1:qbnxyOmOxrQa7FizSgH+ReBfzJrCY1pSN7KXBS8abTk= -google.golang.org/grpc v1.28.0/go.mod h1:rpkK4SK4GF4Ach/+MFLZUBavHOvF2JJB5uozKKal+60= -google.golang.org/grpc v1.29.1/go.mod h1:itym6AZVZYACWQqET3MqgPpjcuV5QH3BxFS3IjizoKk= -google.golang.org/grpc v1.30.0 h1:M5a8xTlYTxwMn5ZFkwhRabsygDY5G8TYLyQDBxJNAxE= -google.golang.org/grpc v1.30.0/go.mod h1:N36X2cJ7JwdamYAgDz+s+rVMFjt3numwzf/HckM8pak= google.golang.org/grpc v1.33.1/go.mod h1:fr5YgcSWrqhRRxogOsw7RzIpsmvOZ6IcH4kBYTpR3n0= google.golang.org/grpc v1.36.0/go.mod h1:qjiiYl8FncCW8feJPdyg3v6XW24KsRHe+dy9BAGRRjU= -google.golang.org/grpc v1.46.0 h1:oCjezcn6g6A75TGoKYBPgKmVBLexhYLM6MebdrPApP8= -google.golang.org/grpc v1.46.0/go.mod h1:vN9eftEi1UMyUsIF80+uQXhHjbXYbm0uXoFCACuMGWk= -google.golang.org/grpc/cmd/protoc-gen-go-grpc v1.2.0/go.mod h1:DNq5QpG7LJqD2AamLZ7zvKE0DEpVl2BSEVjFycAAjRY= +google.golang.org/grpc v1.48.0 h1:rQOsyJ/8+ufEDJd/Gdsz7HG220Mh9HAhFHRGnIjda0w= +google.golang.org/grpc v1.48.0/go.mod h1:vN9eftEi1UMyUsIF80+uQXhHjbXYbm0uXoFCACuMGWk= google.golang.org/protobuf v0.0.0-20200109180630-ec00e32a8dfd/go.mod h1:DFci5gLYBciE7Vtevhsrf46CRTquxDuWsQurQQe4oz8= google.golang.org/protobuf v0.0.0-20200221191635-4d8936d0db64/go.mod h1:kwYJMbMJ01Woi6D6+Kah6886xMZcty6N08ah7+eCXa0= google.golang.org/protobuf v0.0.0-20200228230310-ab0ca4ff8a60/go.mod h1:cfTl7dwQJ+fmap5saPgwCLgHXTUD7jkjRqWcaiX5VyM= @@ -709,7 +355,6 @@ google.golang.org/protobuf v1.22.0/go.mod h1:EGpADcykh3NcUnDUJcl1+ZksZNG86OlYog2 google.golang.org/protobuf v1.23.0/go.mod h1:EGpADcykh3NcUnDUJcl1+ZksZNG86OlYog2l/sGQquU= google.golang.org/protobuf v1.23.1-0.20200526195155-81db48ad09cc/go.mod h1:EGpADcykh3NcUnDUJcl1+ZksZNG86OlYog2l/sGQquU= google.golang.org/protobuf v1.24.0/go.mod h1:r/3tXBNzIEhYS9I1OUVjXDlt8tc493IdKGjtUeSXeh4= -google.golang.org/protobuf v1.25.0 h1:Ejskq+SyPohKW+1uil0JJMtmHCgJPJ/qWTxr8qp+R4c= google.golang.org/protobuf v1.25.0/go.mod h1:9JNX74DMeImyA3h4bdi1ymwjUzf21/xIlbajtzgsN7c= google.golang.org/protobuf v1.26.0-rc.1/go.mod h1:jlhhOSvTdKEhbULTjvd4ARK9grFBp09yW+WbY/TyQbw= google.golang.org/protobuf v1.26.0/go.mod h1:9q0QmTI4eRPtz6boOQmLYwt+qCgq0jsYwAQnmE0givc= @@ -722,24 +367,15 @@ gopkg.in/check.v1 v1.0.0-20190902080502-41f04d3bba15/go.mod h1:Co6ibVJAznAaIkqp8 gopkg.in/check.v1 v1.0.0-20200227125254-8fa46927fb4f/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= gopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c h1:Hei/4ADfdWqJk1ZMxUNpqntNwaWcugrBjAiHlqqRiVk= gopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c/go.mod h1:JHkPIbrfpd72SG/EVd6muEfDQjcINNoR0C8j2r3qZ4Q= -gopkg.in/cheggaaa/pb.v1 v1.0.27/go.mod h1:V/YB90LKu/1FcN3WVnfiiE5oMCibMjukxqG/qStrOgw= -gopkg.in/errgo.v2 v2.1.0/go.mod h1:hNsd1EY+bozCKY1Ytp96fpM3vjJbqLJn88ws8XvfDNI= gopkg.in/warnings.v0 v0.1.2 h1:wFXVbFY8DY5/xOe1ECiWdKCzZlxgshcYVNkBHstARME= gopkg.in/warnings.v0 v0.1.2/go.mod h1:jksf8JmL6Qr/oQM2OXTHunEvvTAsrWBLb6OOjuVWRNI= gopkg.in/yaml.v2 v2.2.2/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI= gopkg.in/yaml.v2 v2.2.3/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI= gopkg.in/yaml.v2 v2.2.4/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI= -gopkg.in/yaml.v2 v2.3.0 h1:clyUAQHOM3G0M3f5vQj7LuJrETvjVot3Z5el9nffUtU= gopkg.in/yaml.v2 v2.3.0/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI= -gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c h1:dUUwHk2QECo/6vqA44rthZ8ie2QXMNeKRTHCNY2nXvo= gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= +gopkg.in/yaml.v3 v3.0.0/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= +gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA= +gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= honnef.co/go/tools v0.0.0-20190102054323-c2f93a96b099/go.mod h1:rf3lG4BRIbNafJWhAfAdb/ePZxsR/4RtNHQocxwk9r4= -honnef.co/go/tools v0.0.0-20190106161140-3f1c8253044a/go.mod h1:rf3lG4BRIbNafJWhAfAdb/ePZxsR/4RtNHQocxwk9r4= -honnef.co/go/tools v0.0.0-20190418001031-e561f6794a2a/go.mod h1:rf3lG4BRIbNafJWhAfAdb/ePZxsR/4RtNHQocxwk9r4= honnef.co/go/tools v0.0.0-20190523083050-ea95bdfd59fc/go.mod h1:rf3lG4BRIbNafJWhAfAdb/ePZxsR/4RtNHQocxwk9r4= -honnef.co/go/tools v0.0.1-2019.2.3/go.mod h1:a3bituU0lyd329TUQxRnasdCoJDkEUEAqEt0JzvZhAg= -honnef.co/go/tools v0.0.1-2020.1.3/go.mod h1:X/FiERA/W4tHapMX5mGpAtMSVEeEUOyHaw9vFzvIQ3k= -honnef.co/go/tools v0.0.1-2020.1.4/go.mod h1:X/FiERA/W4tHapMX5mGpAtMSVEeEUOyHaw9vFzvIQ3k= -rsc.io/binaryregexp v0.2.0/go.mod h1:qTv7/COck+e2FymRvadv62gMdZztPaShugOCi3I+8D8= -rsc.io/quote/v3 v3.1.0/go.mod h1:yEA65RcK8LyAZtP9Kv3t0HmxON59tX3rD+tICJqUlj0= -rsc.io/sampler v1.3.0/go.mod h1:T1hPZKmBbMNahiBKFy5HrXp6adAjACjK9JXDnKaTXpA= diff --git a/internal/controller/controller.go b/internal/controller/controller.go index a2024cd..19c9806 100644 --- a/internal/controller/controller.go +++ b/internal/controller/controller.go @@ -35,7 +35,7 @@ import ( log "github.com/sirupsen/logrus" - "github.com/dgrijalva/jwt-go" + jwt "github.com/golang-jwt/jwt/v4" "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" ) From 8d530c45ea126d6b0680b682af50059336374d14 Mon Sep 17 00:00:00 2001 From: kjubybot Date: Wed, 27 Jul 2022 12:38:57 +0300 Subject: [PATCH 50/51] updated goreleaser config --- .goreleaser.yml | 1 + 1 file changed, 1 insertion(+) diff --git a/.goreleaser.yml b/.goreleaser.yml index feafdbf..d28e2f6 100644 --- a/.goreleaser.yml +++ b/.goreleaser.yml @@ -4,6 +4,7 @@ before: builds: - env: - CGO_ENABLED=0 + main: ./cmd/decort mod_timestamp: '{{ .CommitTimestamp }}' flags: - -trimpath From 965b6013a6bde7448e9e0210ee0d3ff27b787921 Mon Sep 17 00:00:00 2001 From: kjubybot Date: Wed, 27 Jul 2022 13:50:03 +0300 Subject: [PATCH 51/51] updated docs and changelog --- CHANGELOG.md | 43 +---- docs/data-sources/account.md | 124 +++++++-------- docs/data-sources/account_audits_list.md | 24 +-- docs/data-sources/account_computes_list.md | 54 +++---- docs/data-sources/account_consumed_units.md | 24 +-- .../account_consumed_units_by_type.md | 16 +- docs/data-sources/account_deleted_list.md | 42 ++--- docs/data-sources/account_disks_list.md | 26 +-- docs/data-sources/account_flipgroups_list.md | 56 +++---- docs/data-sources/account_list.md | 42 ++--- docs/data-sources/account_reserved_units.md | 24 +-- docs/data-sources/account_rg_list.md | 86 +++++----- docs/data-sources/account_templates_list.md | 34 ++-- docs/data-sources/account_vins_list.md | 48 +++--- docs/data-sources/bservice.md | 88 +++++------ docs/data-sources/bservice_deleted_list.md | 64 ++++---- docs/data-sources/bservice_group.md | 86 +++++----- docs/data-sources/bservice_list.md | 64 ++++---- docs/data-sources/bservice_snapshot_list.md | 22 +-- docs/data-sources/disk.md | 101 ++++++++++-- docs/data-sources/disk_list.md | 145 +++++++++-------- docs/data-sources/extnet.md | 90 +++++------ docs/data-sources/extnet_computes_list.md | 36 ++--- docs/data-sources/extnet_default.md | 12 +- docs/data-sources/extnet_list.md | 24 +-- docs/data-sources/grid.md | 22 +-- docs/data-sources/grid_list.md | 28 ++-- docs/data-sources/image.md | 91 ++++++----- docs/data-sources/image_list.md | 85 ++++------ docs/data-sources/image_list_stacks.md | 48 +++--- docs/data-sources/kvmvm.md | 64 ++++---- docs/data-sources/location_url.md | 35 +++++ docs/data-sources/locations_list.md | 52 ++++++ docs/data-sources/pcidevice.md | 34 ++-- docs/data-sources/pcidevice_list.md | 36 ++--- docs/data-sources/resgroup.md | 38 ++--- docs/data-sources/rg_list.md | 90 +++++------ docs/data-sources/sep.md | 38 ++--- docs/data-sources/sep_config.md | 14 +- docs/data-sources/sep_consumption.md | 46 +++--- docs/data-sources/sep_disk_list.md | 16 +- docs/data-sources/sep_list.md | 44 +++--- docs/data-sources/sep_pool.md | 16 +- docs/data-sources/snapshot_list.md | 22 +-- docs/data-sources/vgpu.md | 25 ++- docs/data-sources/vins.md | 26 +-- docs/data-sources/vins_list.md | 50 +++--- docs/index.md | 18 +-- docs/resources/account.md | 148 +++++++++--------- docs/resources/bservice.md | 104 ++++++------ docs/resources/bservice_group.md | 104 ++++++------ docs/resources/cdrom_image.md | 100 ++++++------ docs/resources/delete_images.md | 25 +-- docs/resources/disk.md | 108 ++++++++++--- docs/resources/image.md | 104 ++++++------ docs/resources/kubernetes.md | 52 +++--- docs/resources/kubernetes_wg.md | 31 ++-- docs/resources/kvmvm.md | 68 ++++---- docs/resources/pcidevice.md | 44 +++--- docs/resources/pfw.md | 28 ++-- docs/resources/resgroup.md | 48 +++--- docs/resources/sep.md | 60 +++---- docs/resources/sep_config.md | 31 ++-- docs/resources/snapshot.md | 28 ++-- docs/resources/vins.md | 32 ++-- docs/resources/virtual_image.md | 106 ++++++------- 66 files changed, 1862 insertions(+), 1672 deletions(-) create mode 100644 docs/data-sources/location_url.md create mode 100644 docs/data-sources/locations_list.md diff --git a/CHANGELOG.md b/CHANGELOG.md index 88fa8aa..589e4d7 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,37 +1,10 @@ ### Bug fixes -- changing boot\_disk\_size in kvmvm -- downsizing CPU and RAM in kvmvm -- pfw recreation if public\_port\_end unspecified -- uninformative error message when retrying on 500 -- hardcoded 3 minute timeout +- fatal error when trying to retrieve compute boot disk if former does not have one +- ignored timeouts +- wrong handling of errors when attaching network interfaces and disks to kvmvm -### New datasources -- disk\_list -- rg\_list -- account\_list -- account\_computes\_list -- account\_disks\_list -- account\_vins\_list -- account\_audits\_list -- account -- account\_rg\_list -- account\_counsumed\_units -- account\_counsumed\_units\_by\_type -- account\_reserved\_units -- account\_templates\_list -- account\_deleted\_list -- bservice\_list -- bservice\_snapshot\_list -- bservice\_deleted\_list -- bservice -- bservice\_group -- extnet\_default -- extnet\_list -- extnet -- extnet\_computes\_list -- vins\_list - -### New resources -- account -- bservice -- bservice\_group +### New features +- parameter iotune in disk +- migrated to terraform SDKv2 +- admin mode (activated by environment variable DECORT\_ADMIN\_MODE) for resources: account, k8s, image, disk, resgroup, kvmvm, vins +- parameters sep\_id and pool in kvmvm diff --git a/docs/data-sources/account.md b/docs/data-sources/account.md index 958f041..36377b6 100644 --- a/docs/data-sources/account.md +++ b/docs/data-sources/account.md @@ -1,6 +1,6 @@ --- # generated by https://github.com/hashicorp/terraform-plugin-docs -page_title: "decort_account Data Source - terraform-provider-decort" +page_title: "decort_account Data Source - decort" subcategory: "" description: |- @@ -17,48 +17,48 @@ description: |- ### Required -- **account_id** (Number) +- `account_id` (Number) ### Optional -- **id** (String) The ID of this resource. -- **timeouts** (Block, Optional) (see [below for nested schema](#nestedblock--timeouts)) +- `timeouts` (Block, Optional) (see [below for nested schema](#nestedblock--timeouts)) ### Read-Only -- **account_name** (String) -- **acl** (List of Object) (see [below for nested schema](#nestedatt--acl)) -- **ckey** (String) -- **company** (String) -- **companyurl** (String) -- **computes** (List of Object) (see [below for nested schema](#nestedatt--computes)) -- **created_by** (String) -- **created_time** (Number) -- **dc_location** (String) -- **deactivation_time** (Number) -- **deleted_by** (String) -- **deleted_time** (Number) -- **displayname** (String) -- **guid** (Number) -- **machines** (List of Object) (see [below for nested schema](#nestedatt--machines)) -- **meta** (List of String) -- **resource_limits** (List of Object) (see [below for nested schema](#nestedatt--resource_limits)) -- **resources** (List of Object) (see [below for nested schema](#nestedatt--resources)) -- **send_access_emails** (Boolean) -- **service_account** (Boolean) -- **status** (String) -- **updated_time** (Number) -- **version** (Number) -- **vins** (List of Number) -- **vinses** (Number) +- `account_name` (String) +- `acl` (List of Object) (see [below for nested schema](#nestedatt--acl)) +- `ckey` (String) +- `company` (String) +- `companyurl` (String) +- `computes` (List of Object) (see [below for nested schema](#nestedatt--computes)) +- `created_by` (String) +- `created_time` (Number) +- `dc_location` (String) +- `deactivation_time` (Number) +- `deleted_by` (String) +- `deleted_time` (Number) +- `displayname` (String) +- `guid` (Number) +- `id` (String) The ID of this resource. +- `machines` (List of Object) (see [below for nested schema](#nestedatt--machines)) +- `meta` (List of String) +- `resource_limits` (List of Object) (see [below for nested schema](#nestedatt--resource_limits)) +- `resources` (List of Object) (see [below for nested schema](#nestedatt--resources)) +- `send_access_emails` (Boolean) +- `service_account` (Boolean) +- `status` (String) +- `updated_time` (Number) +- `version` (Number) +- `vins` (List of Number) +- `vinses` (Number) ### Nested Schema for `timeouts` Optional: -- **default** (String) -- **read** (String) +- `default` (String) +- `read` (String) @@ -66,13 +66,13 @@ Optional: Read-Only: -- **can_be_deleted** (Boolean) -- **explicit** (Boolean) -- **guid** (String) -- **right** (String) -- **status** (String) -- **type** (String) -- **user_group_id** (String) +- `can_be_deleted` (Boolean) +- `explicit` (Boolean) +- `guid` (String) +- `right` (String) +- `status` (String) +- `type` (String) +- `user_group_id` (String) @@ -80,8 +80,8 @@ Read-Only: Read-Only: -- **started** (Number) -- **stopped** (Number) +- `started` (Number) +- `stopped` (Number) @@ -89,8 +89,8 @@ Read-Only: Read-Only: -- **halted** (Number) -- **running** (Number) +- `halted` (Number) +- `running` (Number) @@ -98,12 +98,12 @@ Read-Only: Read-Only: -- **cu_c** (Number) -- **cu_d** (Number) -- **cu_i** (Number) -- **cu_m** (Number) -- **cu_np** (Number) -- **gpu_units** (Number) +- `cu_c` (Number) +- `cu_d` (Number) +- `cu_i` (Number) +- `cu_m` (Number) +- `cu_np` (Number) +- `gpu_units` (Number) @@ -111,20 +111,20 @@ Read-Only: Read-Only: -- **current** (List of Object) (see [below for nested schema](#nestedobjatt--resources--current)) -- **reserved** (List of Object) (see [below for nested schema](#nestedobjatt--resources--reserved)) +- `current` (List of Object) (see [below for nested schema](#nestedobjatt--resources--current)) +- `reserved` (List of Object) (see [below for nested schema](#nestedobjatt--resources--reserved)) ### Nested Schema for `resources.current` Read-Only: -- **cpu** (Number) -- **disksize** (Number) -- **extips** (Number) -- **exttraffic** (Number) -- **gpu** (Number) -- **ram** (Number) +- `cpu` (Number) +- `disksize` (Number) +- `extips` (Number) +- `exttraffic` (Number) +- `gpu` (Number) +- `ram` (Number) @@ -132,11 +132,11 @@ Read-Only: Read-Only: -- **cpu** (Number) -- **disksize** (Number) -- **extips** (Number) -- **exttraffic** (Number) -- **gpu** (Number) -- **ram** (Number) +- `cpu` (Number) +- `disksize` (Number) +- `extips` (Number) +- `exttraffic` (Number) +- `gpu` (Number) +- `ram` (Number) diff --git a/docs/data-sources/account_audits_list.md b/docs/data-sources/account_audits_list.md index 34353e7..9248026 100644 --- a/docs/data-sources/account_audits_list.md +++ b/docs/data-sources/account_audits_list.md @@ -1,6 +1,6 @@ --- # generated by https://github.com/hashicorp/terraform-plugin-docs -page_title: "decort_account_audits_list Data Source - terraform-provider-decort" +page_title: "decort_account_audits_list Data Source - decort" subcategory: "" description: |- @@ -17,24 +17,24 @@ description: |- ### Required -- **account_id** (Number) ID of the account +- `account_id` (Number) ID of the account ### Optional -- **id** (String) The ID of this resource. -- **timeouts** (Block, Optional) (see [below for nested schema](#nestedblock--timeouts)) +- `timeouts` (Block, Optional) (see [below for nested schema](#nestedblock--timeouts)) ### Read-Only -- **items** (List of Object) Search Result (see [below for nested schema](#nestedatt--items)) +- `id` (String) The ID of this resource. +- `items` (List of Object) Search Result (see [below for nested schema](#nestedatt--items)) ### Nested Schema for `timeouts` Optional: -- **default** (String) -- **read** (String) +- `default` (String) +- `read` (String) @@ -42,10 +42,10 @@ Optional: Read-Only: -- **call** (String) -- **responsetime** (Number) -- **statuscode** (Number) -- **timestamp** (Number) -- **user** (String) +- `call` (String) +- `responsetime` (Number) +- `statuscode` (Number) +- `timestamp` (Number) +- `user` (String) diff --git a/docs/data-sources/account_computes_list.md b/docs/data-sources/account_computes_list.md index 963108a..127ed03 100644 --- a/docs/data-sources/account_computes_list.md +++ b/docs/data-sources/account_computes_list.md @@ -1,6 +1,6 @@ --- # generated by https://github.com/hashicorp/terraform-plugin-docs -page_title: "decort_account_computes_list Data Source - terraform-provider-decort" +page_title: "decort_account_computes_list Data Source - decort" subcategory: "" description: |- @@ -17,24 +17,24 @@ description: |- ### Required -- **account_id** (Number) ID of the account +- `account_id` (Number) ID of the account ### Optional -- **id** (String) The ID of this resource. -- **timeouts** (Block, Optional) (see [below for nested schema](#nestedblock--timeouts)) +- `timeouts` (Block, Optional) (see [below for nested schema](#nestedblock--timeouts)) ### Read-Only -- **items** (List of Object) Search Result (see [below for nested schema](#nestedatt--items)) +- `id` (String) The ID of this resource. +- `items` (List of Object) Search Result (see [below for nested schema](#nestedatt--items)) ### Nested Schema for `timeouts` Optional: -- **default** (String) -- **read** (String) +- `default` (String) +- `read` (String) @@ -42,25 +42,25 @@ Optional: Read-Only: -- **account_id** (Number) -- **account_name** (String) -- **compute_id** (Number) -- **compute_name** (String) -- **cpus** (Number) -- **created_by** (String) -- **created_time** (Number) -- **deleted_by** (String) -- **deleted_time** (Number) -- **ram** (Number) -- **registered** (Boolean) -- **rg_id** (Number) -- **rg_name** (String) -- **status** (String) -- **tech_status** (String) -- **total_disks_size** (Number) -- **updated_by** (String) -- **updated_time** (Number) -- **user_managed** (Boolean) -- **vins_connected** (Number) +- `account_id` (Number) +- `account_name` (String) +- `compute_id` (Number) +- `compute_name` (String) +- `cpus` (Number) +- `created_by` (String) +- `created_time` (Number) +- `deleted_by` (String) +- `deleted_time` (Number) +- `ram` (Number) +- `registered` (Boolean) +- `rg_id` (Number) +- `rg_name` (String) +- `status` (String) +- `tech_status` (String) +- `total_disks_size` (Number) +- `updated_by` (String) +- `updated_time` (Number) +- `user_managed` (Boolean) +- `vins_connected` (Number) diff --git a/docs/data-sources/account_consumed_units.md b/docs/data-sources/account_consumed_units.md index 84b0ac5..1781a07 100644 --- a/docs/data-sources/account_consumed_units.md +++ b/docs/data-sources/account_consumed_units.md @@ -1,6 +1,6 @@ --- # generated by https://github.com/hashicorp/terraform-plugin-docs -page_title: "decort_account_consumed_units Data Source - terraform-provider-decort" +page_title: "decort_account_consumed_units Data Source - decort" subcategory: "" description: |- @@ -17,28 +17,28 @@ description: |- ### Required -- **account_id** (Number) ID of the account +- `account_id` (Number) ID of the account ### Optional -- **id** (String) The ID of this resource. -- **timeouts** (Block, Optional) (see [below for nested schema](#nestedblock--timeouts)) +- `timeouts` (Block, Optional) (see [below for nested schema](#nestedblock--timeouts)) ### Read-Only -- **cu_c** (Number) -- **cu_d** (Number) -- **cu_i** (Number) -- **cu_m** (Number) -- **cu_np** (Number) -- **gpu_units** (Number) +- `cu_c` (Number) +- `cu_d` (Number) +- `cu_i` (Number) +- `cu_m` (Number) +- `cu_np` (Number) +- `gpu_units` (Number) +- `id` (String) The ID of this resource. ### Nested Schema for `timeouts` Optional: -- **default** (String) -- **read** (String) +- `default` (String) +- `read` (String) diff --git a/docs/data-sources/account_consumed_units_by_type.md b/docs/data-sources/account_consumed_units_by_type.md index 8ad6632..211430f 100644 --- a/docs/data-sources/account_consumed_units_by_type.md +++ b/docs/data-sources/account_consumed_units_by_type.md @@ -1,6 +1,6 @@ --- # generated by https://github.com/hashicorp/terraform-plugin-docs -page_title: "decort_account_consumed_units_by_type Data Source - terraform-provider-decort" +page_title: "decort_account_consumed_units_by_type Data Source - decort" subcategory: "" description: |- @@ -17,24 +17,24 @@ description: |- ### Required -- **account_id** (Number) ID of the account -- **cu_type** (String) cloud unit resource type +- `account_id` (Number) ID of the account +- `cu_type` (String) cloud unit resource type ### Optional -- **id** (String) The ID of this resource. -- **timeouts** (Block, Optional) (see [below for nested schema](#nestedblock--timeouts)) +- `timeouts` (Block, Optional) (see [below for nested schema](#nestedblock--timeouts)) ### Read-Only -- **cu_result** (Number) +- `cu_result` (Number) +- `id` (String) The ID of this resource. ### Nested Schema for `timeouts` Optional: -- **default** (String) -- **read** (String) +- `default` (String) +- `read` (String) diff --git a/docs/data-sources/account_deleted_list.md b/docs/data-sources/account_deleted_list.md index 0a321c1..55c2c8c 100644 --- a/docs/data-sources/account_deleted_list.md +++ b/docs/data-sources/account_deleted_list.md @@ -1,6 +1,6 @@ --- # generated by https://github.com/hashicorp/terraform-plugin-docs -page_title: "decort_account_deleted_list Data Source - terraform-provider-decort" +page_title: "decort_account_deleted_list Data Source - decort" subcategory: "" description: |- @@ -17,22 +17,22 @@ description: |- ### Optional -- **id** (String) The ID of this resource. -- **page** (Number) Page number -- **size** (Number) Page size -- **timeouts** (Block, Optional) (see [below for nested schema](#nestedblock--timeouts)) +- `page` (Number) Page number +- `size` (Number) Page size +- `timeouts` (Block, Optional) (see [below for nested schema](#nestedblock--timeouts)) ### Read-Only -- **items** (List of Object) (see [below for nested schema](#nestedatt--items)) +- `id` (String) The ID of this resource. +- `items` (List of Object) (see [below for nested schema](#nestedatt--items)) ### Nested Schema for `timeouts` Optional: -- **default** (String) -- **read** (String) +- `default` (String) +- `read` (String) @@ -40,24 +40,24 @@ Optional: Read-Only: -- **account_id** (Number) -- **account_name** (String) -- **acl** (List of Object) (see [below for nested schema](#nestedobjatt--items--acl)) -- **created_time** (Number) -- **deleted_time** (Number) -- **status** (String) -- **updated_time** (Number) +- `account_id` (Number) +- `account_name` (String) +- `acl` (List of Object) (see [below for nested schema](#nestedobjatt--items--acl)) +- `created_time` (Number) +- `deleted_time` (Number) +- `status` (String) +- `updated_time` (Number) ### Nested Schema for `items.acl` Read-Only: -- **explicit** (Boolean) -- **guid** (String) -- **right** (String) -- **status** (String) -- **type** (String) -- **user_group_id** (String) +- `explicit` (Boolean) +- `guid` (String) +- `right` (String) +- `status` (String) +- `type` (String) +- `user_group_id` (String) diff --git a/docs/data-sources/account_disks_list.md b/docs/data-sources/account_disks_list.md index ac8b5ae..a150455 100644 --- a/docs/data-sources/account_disks_list.md +++ b/docs/data-sources/account_disks_list.md @@ -1,6 +1,6 @@ --- # generated by https://github.com/hashicorp/terraform-plugin-docs -page_title: "decort_account_disks_list Data Source - terraform-provider-decort" +page_title: "decort_account_disks_list Data Source - decort" subcategory: "" description: |- @@ -17,24 +17,24 @@ description: |- ### Required -- **account_id** (Number) ID of the account +- `account_id` (Number) ID of the account ### Optional -- **id** (String) The ID of this resource. -- **timeouts** (Block, Optional) (see [below for nested schema](#nestedblock--timeouts)) +- `timeouts` (Block, Optional) (see [below for nested schema](#nestedblock--timeouts)) ### Read-Only -- **items** (List of Object) Search Result (see [below for nested schema](#nestedatt--items)) +- `id` (String) The ID of this resource. +- `items` (List of Object) Search Result (see [below for nested schema](#nestedatt--items)) ### Nested Schema for `timeouts` Optional: -- **default** (String) -- **read** (String) +- `default` (String) +- `read` (String) @@ -42,11 +42,11 @@ Optional: Read-Only: -- **disk_id** (Number) -- **disk_name** (String) -- **pool** (String) -- **sep_id** (Number) -- **size_max** (Number) -- **type** (String) +- `disk_id` (Number) +- `disk_name` (String) +- `pool` (String) +- `sep_id` (Number) +- `size_max` (Number) +- `type` (String) diff --git a/docs/data-sources/account_flipgroups_list.md b/docs/data-sources/account_flipgroups_list.md index e97a6d6..a8785b4 100644 --- a/docs/data-sources/account_flipgroups_list.md +++ b/docs/data-sources/account_flipgroups_list.md @@ -1,6 +1,6 @@ --- # generated by https://github.com/hashicorp/terraform-plugin-docs -page_title: "decort_account_flipgroups_list Data Source - terraform-provider-decort" +page_title: "decort_account_flipgroups_list Data Source - decort" subcategory: "" description: |- @@ -17,24 +17,24 @@ description: |- ### Required -- **account_id** (Number) ID of the account +- `account_id` (Number) ID of the account ### Optional -- **id** (String) The ID of this resource. -- **timeouts** (Block, Optional) (see [below for nested schema](#nestedblock--timeouts)) +- `timeouts` (Block, Optional) (see [below for nested schema](#nestedblock--timeouts)) ### Read-Only -- **items** (List of Object) Search Result (see [below for nested schema](#nestedatt--items)) +- `id` (String) The ID of this resource. +- `items` (List of Object) Search Result (see [below for nested schema](#nestedatt--items)) ### Nested Schema for `timeouts` Optional: -- **default** (String) -- **read** (String) +- `default` (String) +- `read` (String) @@ -42,26 +42,26 @@ Optional: Read-Only: -- **account_id** (Number) -- **client_type** (String) -- **conn_type** (String) -- **created_by** (String) -- **created_time** (Number) -- **default_gw** (String) -- **deleted_by** (String) -- **deleted_time** (Number) -- **desc** (String) -- **fg_id** (Number) -- **fg_name** (String) -- **gid** (Number) -- **guid** (Number) -- **ip** (String) -- **milestones** (Number) -- **net_id** (Number) -- **net_type** (String) -- **netmask** (Number) -- **status** (String) -- **updated_by** (String) -- **updated_time** (Number) +- `account_id` (Number) +- `client_type` (String) +- `conn_type` (String) +- `created_by` (String) +- `created_time` (Number) +- `default_gw` (String) +- `deleted_by` (String) +- `deleted_time` (Number) +- `desc` (String) +- `fg_id` (Number) +- `fg_name` (String) +- `gid` (Number) +- `guid` (Number) +- `ip` (String) +- `milestones` (Number) +- `net_id` (Number) +- `net_type` (String) +- `netmask` (Number) +- `status` (String) +- `updated_by` (String) +- `updated_time` (Number) diff --git a/docs/data-sources/account_list.md b/docs/data-sources/account_list.md index de553c0..86d0062 100644 --- a/docs/data-sources/account_list.md +++ b/docs/data-sources/account_list.md @@ -1,6 +1,6 @@ --- # generated by https://github.com/hashicorp/terraform-plugin-docs -page_title: "decort_account_list Data Source - terraform-provider-decort" +page_title: "decort_account_list Data Source - decort" subcategory: "" description: |- @@ -17,22 +17,22 @@ description: |- ### Optional -- **id** (String) The ID of this resource. -- **page** (Number) Page number -- **size** (Number) Page size -- **timeouts** (Block, Optional) (see [below for nested schema](#nestedblock--timeouts)) +- `page` (Number) Page number +- `size` (Number) Page size +- `timeouts` (Block, Optional) (see [below for nested schema](#nestedblock--timeouts)) ### Read-Only -- **items** (List of Object) (see [below for nested schema](#nestedatt--items)) +- `id` (String) The ID of this resource. +- `items` (List of Object) (see [below for nested schema](#nestedatt--items)) ### Nested Schema for `timeouts` Optional: -- **default** (String) -- **read** (String) +- `default` (String) +- `read` (String) @@ -40,24 +40,24 @@ Optional: Read-Only: -- **account_id** (Number) -- **account_name** (String) -- **acl** (List of Object) (see [below for nested schema](#nestedobjatt--items--acl)) -- **created_time** (Number) -- **deleted_time** (Number) -- **status** (String) -- **updated_time** (Number) +- `account_id` (Number) +- `account_name` (String) +- `acl` (List of Object) (see [below for nested schema](#nestedobjatt--items--acl)) +- `created_time` (Number) +- `deleted_time` (Number) +- `status` (String) +- `updated_time` (Number) ### Nested Schema for `items.acl` Read-Only: -- **explicit** (Boolean) -- **guid** (String) -- **right** (String) -- **status** (String) -- **type** (String) -- **user_group_id** (String) +- `explicit` (Boolean) +- `guid` (String) +- `right` (String) +- `status` (String) +- `type` (String) +- `user_group_id` (String) diff --git a/docs/data-sources/account_reserved_units.md b/docs/data-sources/account_reserved_units.md index 26f3627..94cfb4d 100644 --- a/docs/data-sources/account_reserved_units.md +++ b/docs/data-sources/account_reserved_units.md @@ -1,6 +1,6 @@ --- # generated by https://github.com/hashicorp/terraform-plugin-docs -page_title: "decort_account_reserved_units Data Source - terraform-provider-decort" +page_title: "decort_account_reserved_units Data Source - decort" subcategory: "" description: |- @@ -17,28 +17,28 @@ description: |- ### Required -- **account_id** (Number) ID of the account +- `account_id` (Number) ID of the account ### Optional -- **id** (String) The ID of this resource. -- **timeouts** (Block, Optional) (see [below for nested schema](#nestedblock--timeouts)) +- `timeouts` (Block, Optional) (see [below for nested schema](#nestedblock--timeouts)) ### Read-Only -- **cu_c** (Number) -- **cu_d** (Number) -- **cu_i** (Number) -- **cu_m** (Number) -- **cu_np** (Number) -- **gpu_units** (Number) +- `cu_c` (Number) +- `cu_d` (Number) +- `cu_i` (Number) +- `cu_m` (Number) +- `cu_np` (Number) +- `gpu_units` (Number) +- `id` (String) The ID of this resource. ### Nested Schema for `timeouts` Optional: -- **default** (String) -- **read** (String) +- `default` (String) +- `read` (String) diff --git a/docs/data-sources/account_rg_list.md b/docs/data-sources/account_rg_list.md index 7690a9d..3c8a855 100644 --- a/docs/data-sources/account_rg_list.md +++ b/docs/data-sources/account_rg_list.md @@ -1,6 +1,6 @@ --- # generated by https://github.com/hashicorp/terraform-plugin-docs -page_title: "decort_account_rg_list Data Source - terraform-provider-decort" +page_title: "decort_account_rg_list Data Source - decort" subcategory: "" description: |- @@ -17,24 +17,24 @@ description: |- ### Required -- **account_id** (Number) ID of the account +- `account_id` (Number) ID of the account ### Optional -- **id** (String) The ID of this resource. -- **timeouts** (Block, Optional) (see [below for nested schema](#nestedblock--timeouts)) +- `timeouts` (Block, Optional) (see [below for nested schema](#nestedblock--timeouts)) ### Read-Only -- **items** (List of Object) Search Result (see [below for nested schema](#nestedatt--items)) +- `id` (String) The ID of this resource. +- `items` (List of Object) Search Result (see [below for nested schema](#nestedatt--items)) ### Nested Schema for `timeouts` Optional: -- **default** (String) -- **read** (String) +- `default` (String) +- `read` (String) @@ -42,27 +42,27 @@ Optional: Read-Only: -- **computes** (List of Object) (see [below for nested schema](#nestedobjatt--items--computes)) -- **created_by** (String) -- **created_time** (Number) -- **deleted_by** (String) -- **deleted_time** (Number) -- **milestones** (Number) -- **resources** (List of Object) (see [below for nested schema](#nestedobjatt--items--resources)) -- **rg_id** (Number) -- **rg_name** (String) -- **status** (String) -- **updated_by** (String) -- **updated_time** (Number) -- **vinses** (Number) +- `computes` (List of Object) (see [below for nested schema](#nestedobjatt--items--computes)) +- `created_by` (String) +- `created_time` (Number) +- `deleted_by` (String) +- `deleted_time` (Number) +- `milestones` (Number) +- `resources` (List of Object) (see [below for nested schema](#nestedobjatt--items--resources)) +- `rg_id` (Number) +- `rg_name` (String) +- `status` (String) +- `updated_by` (String) +- `updated_time` (Number) +- `vinses` (Number) ### Nested Schema for `items.computes` Read-Only: -- **started** (Number) -- **stopped** (Number) +- `started` (Number) +- `stopped` (Number) @@ -70,21 +70,21 @@ Read-Only: Read-Only: -- **consumed** (List of Object) (see [below for nested schema](#nestedobjatt--items--resources--consumed)) -- **limits** (List of Object) (see [below for nested schema](#nestedobjatt--items--resources--limits)) -- **reserved** (List of Object) (see [below for nested schema](#nestedobjatt--items--resources--reserved)) +- `consumed` (List of Object) (see [below for nested schema](#nestedobjatt--items--resources--consumed)) +- `limits` (List of Object) (see [below for nested schema](#nestedobjatt--items--resources--limits)) +- `reserved` (List of Object) (see [below for nested schema](#nestedobjatt--items--resources--reserved)) ### Nested Schema for `items.resources.consumed` Read-Only: -- **cpu** (Number) -- **disksize** (Number) -- **extips** (Number) -- **exttraffic** (Number) -- **gpu** (Number) -- **ram** (Number) +- `cpu` (Number) +- `disksize` (Number) +- `extips` (Number) +- `exttraffic` (Number) +- `gpu` (Number) +- `ram` (Number) @@ -92,12 +92,12 @@ Read-Only: Read-Only: -- **cpu** (Number) -- **disksize** (Number) -- **extips** (Number) -- **exttraffic** (Number) -- **gpu** (Number) -- **ram** (Number) +- `cpu` (Number) +- `disksize` (Number) +- `extips` (Number) +- `exttraffic` (Number) +- `gpu` (Number) +- `ram` (Number) @@ -105,11 +105,11 @@ Read-Only: Read-Only: -- **cpu** (Number) -- **disksize** (Number) -- **extips** (Number) -- **exttraffic** (Number) -- **gpu** (Number) -- **ram** (Number) +- `cpu` (Number) +- `disksize` (Number) +- `extips` (Number) +- `exttraffic` (Number) +- `gpu` (Number) +- `ram` (Number) diff --git a/docs/data-sources/account_templates_list.md b/docs/data-sources/account_templates_list.md index 690a54d..40f8da2 100644 --- a/docs/data-sources/account_templates_list.md +++ b/docs/data-sources/account_templates_list.md @@ -1,6 +1,6 @@ --- # generated by https://github.com/hashicorp/terraform-plugin-docs -page_title: "decort_account_templates_list Data Source - terraform-provider-decort" +page_title: "decort_account_templates_list Data Source - decort" subcategory: "" description: |- @@ -17,24 +17,24 @@ description: |- ### Required -- **account_id** (Number) ID of the account +- `account_id` (Number) ID of the account ### Optional -- **id** (String) The ID of this resource. -- **timeouts** (Block, Optional) (see [below for nested schema](#nestedblock--timeouts)) +- `timeouts` (Block, Optional) (see [below for nested schema](#nestedblock--timeouts)) ### Read-Only -- **items** (List of Object) Search Result (see [below for nested schema](#nestedatt--items)) +- `id` (String) The ID of this resource. +- `items` (List of Object) Search Result (see [below for nested schema](#nestedatt--items)) ### Nested Schema for `timeouts` Optional: -- **default** (String) -- **read** (String) +- `default` (String) +- `read` (String) @@ -42,15 +42,15 @@ Optional: Read-Only: -- **account_id** (Number) -- **desc** (String) -- **public** (Boolean) -- **size** (Number) -- **status** (String) -- **template_id** (Number) -- **template_name** (String) -- **type** (String) -- **unc_path** (String) -- **username** (String) +- `account_id` (Number) +- `desc` (String) +- `public` (Boolean) +- `size` (Number) +- `status` (String) +- `template_id` (Number) +- `template_name` (String) +- `type` (String) +- `unc_path` (String) +- `username` (String) diff --git a/docs/data-sources/account_vins_list.md b/docs/data-sources/account_vins_list.md index c574cda..873d3e0 100644 --- a/docs/data-sources/account_vins_list.md +++ b/docs/data-sources/account_vins_list.md @@ -1,6 +1,6 @@ --- # generated by https://github.com/hashicorp/terraform-plugin-docs -page_title: "decort_account_vins_list Data Source - terraform-provider-decort" +page_title: "decort_account_vins_list Data Source - decort" subcategory: "" description: |- @@ -17,24 +17,24 @@ description: |- ### Required -- **account_id** (Number) ID of the account +- `account_id` (Number) ID of the account ### Optional -- **id** (String) The ID of this resource. -- **timeouts** (Block, Optional) (see [below for nested schema](#nestedblock--timeouts)) +- `timeouts` (Block, Optional) (see [below for nested schema](#nestedblock--timeouts)) ### Read-Only -- **items** (List of Object) Search Result (see [below for nested schema](#nestedatt--items)) +- `id` (String) The ID of this resource. +- `items` (List of Object) Search Result (see [below for nested schema](#nestedatt--items)) ### Nested Schema for `timeouts` Optional: -- **default** (String) -- **read** (String) +- `default` (String) +- `read` (String) @@ -42,22 +42,22 @@ Optional: Read-Only: -- **account_id** (Number) -- **account_name** (String) -- **computes** (Number) -- **created_by** (String) -- **created_time** (Number) -- **deleted_by** (String) -- **deleted_time** (Number) -- **external_ip** (String) -- **network** (String) -- **pri_vnf_dev_id** (Number) -- **rg_id** (Number) -- **rg_name** (String) -- **status** (String) -- **updated_by** (String) -- **updated_time** (Number) -- **vin_id** (Number) -- **vin_name** (String) +- `account_id` (Number) +- `account_name` (String) +- `computes` (Number) +- `created_by` (String) +- `created_time` (Number) +- `deleted_by` (String) +- `deleted_time` (Number) +- `external_ip` (String) +- `network` (String) +- `pri_vnf_dev_id` (Number) +- `rg_id` (Number) +- `rg_name` (String) +- `status` (String) +- `updated_by` (String) +- `updated_time` (Number) +- `vin_id` (Number) +- `vin_name` (String) diff --git a/docs/data-sources/bservice.md b/docs/data-sources/bservice.md index c581e67..1c2a576 100644 --- a/docs/data-sources/bservice.md +++ b/docs/data-sources/bservice.md @@ -1,6 +1,6 @@ --- # generated by https://github.com/hashicorp/terraform-plugin-docs -page_title: "decort_bservice Data Source - terraform-provider-decort" +page_title: "decort_bservice Data Source - decort" subcategory: "" description: |- @@ -17,52 +17,52 @@ description: |- ### Required -- **service_id** (Number) +- `service_id` (Number) ### Optional -- **id** (String) The ID of this resource. -- **timeouts** (Block, Optional) (see [below for nested schema](#nestedblock--timeouts)) +- `timeouts` (Block, Optional) (see [below for nested schema](#nestedblock--timeouts)) ### Read-Only -- **account_id** (Number) -- **account_name** (String) -- **base_domain** (String) -- **computes** (List of Object) (see [below for nested schema](#nestedatt--computes)) -- **cpu_total** (Number) -- **created_by** (String) -- **created_time** (Number) -- **deleted_by** (String) -- **deleted_time** (Number) -- **disk_total** (String) -- **gid** (Number) -- **groups** (List of Number) -- **groups_name** (List of String) -- **guid** (Number) -- **milestones** (Number) -- **parent_srv_id** (Number) -- **parent_srv_type** (String) -- **ram_total** (Number) -- **rg_id** (Number) -- **rg_name** (String) -- **service_name** (String) -- **snapshots** (List of Object) (see [below for nested schema](#nestedatt--snapshots)) -- **ssh_key** (String) -- **ssh_user** (String) -- **status** (String) -- **tech_status** (String) -- **updated_by** (String) -- **updated_time** (Number) -- **user_managed** (Boolean) +- `account_id` (Number) +- `account_name` (String) +- `base_domain` (String) +- `computes` (List of Object) (see [below for nested schema](#nestedatt--computes)) +- `cpu_total` (Number) +- `created_by` (String) +- `created_time` (Number) +- `deleted_by` (String) +- `deleted_time` (Number) +- `disk_total` (String) +- `gid` (Number) +- `groups` (List of Number) +- `groups_name` (List of String) +- `guid` (Number) +- `id` (String) The ID of this resource. +- `milestones` (Number) +- `parent_srv_id` (Number) +- `parent_srv_type` (String) +- `ram_total` (Number) +- `rg_id` (Number) +- `rg_name` (String) +- `service_name` (String) +- `snapshots` (List of Object) (see [below for nested schema](#nestedatt--snapshots)) +- `ssh_key` (String) +- `ssh_user` (String) +- `status` (String) +- `tech_status` (String) +- `updated_by` (String) +- `updated_time` (Number) +- `user_managed` (Boolean) ### Nested Schema for `timeouts` Optional: -- **default** (String) -- **read** (String) +- `default` (String) +- `read` (String) @@ -70,11 +70,11 @@ Optional: Read-Only: -- **compgroup_id** (Number) -- **compgroup_name** (String) -- **compgroup_role** (String) -- **id** (Number) -- **name** (String) +- `compgroup_id` (Number) +- `compgroup_name` (String) +- `compgroup_role` (String) +- `id` (Number) +- `name` (String) @@ -82,9 +82,9 @@ Read-Only: Read-Only: -- **guid** (String) -- **label** (String) -- **timestamp** (Number) -- **valid** (Boolean) +- `guid` (String) +- `label` (String) +- `timestamp` (Number) +- `valid` (Boolean) diff --git a/docs/data-sources/bservice_deleted_list.md b/docs/data-sources/bservice_deleted_list.md index 53c980e..9db67b2 100644 --- a/docs/data-sources/bservice_deleted_list.md +++ b/docs/data-sources/bservice_deleted_list.md @@ -1,6 +1,6 @@ --- # generated by https://github.com/hashicorp/terraform-plugin-docs -page_title: "decort_bservice_deleted_list Data Source - terraform-provider-decort" +page_title: "decort_bservice_deleted_list Data Source - decort" subcategory: "" description: |- @@ -17,24 +17,24 @@ description: |- ### Optional -- **account_id** (Number) ID of the account to query for BasicService instances -- **id** (String) The ID of this resource. -- **page** (Number) Page number -- **rg_id** (Number) ID of the resource group to query for BasicService instances -- **size** (Number) Page size -- **timeouts** (Block, Optional) (see [below for nested schema](#nestedblock--timeouts)) +- `account_id` (Number) ID of the account to query for BasicService instances +- `page` (Number) Page number +- `rg_id` (Number) ID of the resource group to query for BasicService instances +- `size` (Number) Page size +- `timeouts` (Block, Optional) (see [below for nested schema](#nestedblock--timeouts)) ### Read-Only -- **items** (List of Object) (see [below for nested schema](#nestedatt--items)) +- `id` (String) The ID of this resource. +- `items` (List of Object) (see [below for nested schema](#nestedatt--items)) ### Nested Schema for `timeouts` Optional: -- **default** (String) -- **read** (String) +- `default` (String) +- `read` (String) @@ -42,27 +42,27 @@ Optional: Read-Only: -- **account_id** (Number) -- **account_name** (String) -- **base_domain** (String) -- **created_by** (String) -- **created_time** (Number) -- **deleted_by** (String) -- **deleted_time** (Number) -- **gid** (Number) -- **groups** (List of Number) -- **guid** (Number) -- **parent_srv_id** (Number) -- **parent_srv_type** (String) -- **rg_id** (Number) -- **rg_name** (String) -- **service_id** (Number) -- **service_name** (String) -- **ssh_user** (String) -- **status** (String) -- **tech_status** (String) -- **updated_by** (String) -- **updated_time** (Number) -- **user_managed** (Boolean) +- `account_id` (Number) +- `account_name` (String) +- `base_domain` (String) +- `created_by` (String) +- `created_time` (Number) +- `deleted_by` (String) +- `deleted_time` (Number) +- `gid` (Number) +- `groups` (List of Number) +- `guid` (Number) +- `parent_srv_id` (Number) +- `parent_srv_type` (String) +- `rg_id` (Number) +- `rg_name` (String) +- `service_id` (Number) +- `service_name` (String) +- `ssh_user` (String) +- `status` (String) +- `tech_status` (String) +- `updated_by` (String) +- `updated_time` (Number) +- `user_managed` (Boolean) diff --git a/docs/data-sources/bservice_group.md b/docs/data-sources/bservice_group.md index 8a90fa6..d72055d 100644 --- a/docs/data-sources/bservice_group.md +++ b/docs/data-sources/bservice_group.md @@ -1,6 +1,6 @@ --- # generated by https://github.com/hashicorp/terraform-plugin-docs -page_title: "decort_bservice_group Data Source - terraform-provider-decort" +page_title: "decort_bservice_group Data Source - decort" subcategory: "" description: |- @@ -17,54 +17,54 @@ description: |- ### Required -- **compgroup_id** (Number) -- **service_id** (Number) +- `compgroup_id` (Number) +- `service_id` (Number) ### Optional -- **id** (String) The ID of this resource. -- **timeouts** (Block, Optional) (see [below for nested schema](#nestedblock--timeouts)) +- `timeouts` (Block, Optional) (see [below for nested schema](#nestedblock--timeouts)) ### Read-Only -- **account_id** (Number) -- **account_name** (String) -- **compgroup_name** (String) -- **computes** (List of Object) (see [below for nested schema](#nestedatt--computes)) -- **consistency** (Boolean) -- **cpu** (Number) -- **created_by** (String) -- **created_time** (Number) -- **deleted_by** (String) -- **deleted_time** (Number) -- **disk** (Number) -- **driver** (String) -- **extnets** (List of Number) -- **gid** (Number) -- **guid** (Number) -- **image_id** (Number) -- **milestones** (Number) -- **parents** (List of Number) -- **ram** (Number) -- **rg_id** (Number) -- **rg_name** (String) -- **role** (String) -- **sep_id** (Number) -- **seq_no** (Number) -- **status** (String) -- **tech_status** (String) -- **timeout_start** (Number) -- **updated_by** (String) -- **updated_time** (Number) -- **vinses** (List of Number) +- `account_id` (Number) +- `account_name` (String) +- `compgroup_name` (String) +- `computes` (List of Object) (see [below for nested schema](#nestedatt--computes)) +- `consistency` (Boolean) +- `cpu` (Number) +- `created_by` (String) +- `created_time` (Number) +- `deleted_by` (String) +- `deleted_time` (Number) +- `disk` (Number) +- `driver` (String) +- `extnets` (List of Number) +- `gid` (Number) +- `guid` (Number) +- `id` (String) The ID of this resource. +- `image_id` (Number) +- `milestones` (Number) +- `parents` (List of Number) +- `ram` (Number) +- `rg_id` (Number) +- `rg_name` (String) +- `role` (String) +- `sep_id` (Number) +- `seq_no` (Number) +- `status` (String) +- `tech_status` (String) +- `timeout_start` (Number) +- `updated_by` (String) +- `updated_time` (Number) +- `vinses` (List of Number) ### Nested Schema for `timeouts` Optional: -- **default** (String) -- **read** (String) +- `default` (String) +- `read` (String) @@ -72,17 +72,17 @@ Optional: Read-Only: -- **id** (Number) -- **ip_addresses** (List of String) -- **name** (String) -- **os_users** (List of Object) (see [below for nested schema](#nestedobjatt--computes--os_users)) +- `id` (Number) +- `ip_addresses` (List of String) +- `name` (String) +- `os_users` (List of Object) (see [below for nested schema](#nestedobjatt--computes--os_users)) ### Nested Schema for `computes.os_users` Read-Only: -- **login** (String) -- **password** (String) +- `login` (String) +- `password` (String) diff --git a/docs/data-sources/bservice_list.md b/docs/data-sources/bservice_list.md index e464d39..9107f2f 100644 --- a/docs/data-sources/bservice_list.md +++ b/docs/data-sources/bservice_list.md @@ -1,6 +1,6 @@ --- # generated by https://github.com/hashicorp/terraform-plugin-docs -page_title: "decort_bservice_list Data Source - terraform-provider-decort" +page_title: "decort_bservice_list Data Source - decort" subcategory: "" description: |- @@ -17,24 +17,24 @@ description: |- ### Optional -- **account_id** (Number) ID of the account to query for BasicService instances -- **id** (String) The ID of this resource. -- **page** (Number) Page number -- **rg_id** (Number) ID of the resource group to query for BasicService instances -- **size** (Number) Page size -- **timeouts** (Block, Optional) (see [below for nested schema](#nestedblock--timeouts)) +- `account_id` (Number) ID of the account to query for BasicService instances +- `page` (Number) Page number +- `rg_id` (Number) ID of the resource group to query for BasicService instances +- `size` (Number) Page size +- `timeouts` (Block, Optional) (see [below for nested schema](#nestedblock--timeouts)) ### Read-Only -- **items** (List of Object) (see [below for nested schema](#nestedatt--items)) +- `id` (String) The ID of this resource. +- `items` (List of Object) (see [below for nested schema](#nestedatt--items)) ### Nested Schema for `timeouts` Optional: -- **default** (String) -- **read** (String) +- `default` (String) +- `read` (String) @@ -42,27 +42,27 @@ Optional: Read-Only: -- **account_id** (Number) -- **account_name** (String) -- **base_domain** (String) -- **created_by** (String) -- **created_time** (Number) -- **deleted_by** (String) -- **deleted_time** (Number) -- **gid** (Number) -- **groups** (List of Number) -- **guid** (Number) -- **parent_srv_id** (Number) -- **parent_srv_type** (String) -- **rg_id** (Number) -- **rg_name** (String) -- **service_id** (Number) -- **service_name** (String) -- **ssh_user** (String) -- **status** (String) -- **tech_status** (String) -- **updated_by** (String) -- **updated_time** (Number) -- **user_managed** (Boolean) +- `account_id` (Number) +- `account_name` (String) +- `base_domain` (String) +- `created_by` (String) +- `created_time` (Number) +- `deleted_by` (String) +- `deleted_time` (Number) +- `gid` (Number) +- `groups` (List of Number) +- `guid` (Number) +- `parent_srv_id` (Number) +- `parent_srv_type` (String) +- `rg_id` (Number) +- `rg_name` (String) +- `service_id` (Number) +- `service_name` (String) +- `ssh_user` (String) +- `status` (String) +- `tech_status` (String) +- `updated_by` (String) +- `updated_time` (Number) +- `user_managed` (Boolean) diff --git a/docs/data-sources/bservice_snapshot_list.md b/docs/data-sources/bservice_snapshot_list.md index c75cd5f..536116d 100644 --- a/docs/data-sources/bservice_snapshot_list.md +++ b/docs/data-sources/bservice_snapshot_list.md @@ -1,6 +1,6 @@ --- # generated by https://github.com/hashicorp/terraform-plugin-docs -page_title: "decort_bservice_snapshot_list Data Source - terraform-provider-decort" +page_title: "decort_bservice_snapshot_list Data Source - decort" subcategory: "" description: |- @@ -17,24 +17,24 @@ description: |- ### Required -- **service_id** (Number) ID of the BasicService instance +- `service_id` (Number) ID of the BasicService instance ### Optional -- **id** (String) The ID of this resource. -- **timeouts** (Block, Optional) (see [below for nested schema](#nestedblock--timeouts)) +- `timeouts` (Block, Optional) (see [below for nested schema](#nestedblock--timeouts)) ### Read-Only -- **items** (List of Object) (see [below for nested schema](#nestedatt--items)) +- `id` (String) The ID of this resource. +- `items` (List of Object) (see [below for nested schema](#nestedatt--items)) ### Nested Schema for `timeouts` Optional: -- **default** (String) -- **read** (String) +- `default` (String) +- `read` (String) @@ -42,9 +42,9 @@ Optional: Read-Only: -- **guid** (String) -- **label** (String) -- **timestamp** (Number) -- **valid** (Boolean) +- `guid` (String) +- `label` (String) +- `timestamp` (Number) +- `valid` (Boolean) diff --git a/docs/data-sources/disk.md b/docs/data-sources/disk.md index 099f502..85bdb36 100644 --- a/docs/data-sources/disk.md +++ b/docs/data-sources/disk.md @@ -1,6 +1,6 @@ --- # generated by https://github.com/hashicorp/terraform-plugin-docs -page_title: "decort_disk Data Source - terraform-provider-decort" +page_title: "decort_disk Data Source - decort" subcategory: "" description: |- @@ -15,31 +15,100 @@ description: |- ## Schema +### Required + +- `disk_id` (Number) + ### Optional -- **account_id** (Number) ID of the account this disk belongs to. If disk ID is specified, then account ID is ignored. -- **disk_id** (Number) ID of the disk to get. If disk ID is specified, then disk name and account ID are ignored. -- **id** (String) The ID of this resource. -- **name** (String) Name of this disk. NOTE: disk names are NOT unique within an account. If disk ID is specified, disk name is ignored. -- **timeouts** (Block, Optional) (see [below for nested schema](#nestedblock--timeouts)) +- `timeouts` (Block, Optional) (see [below for nested schema](#nestedblock--timeouts)) ### Read-Only -- **account_name** (String) Name of the account this disk belongs to. If account ID is specified, account name is ignored. -- **description** (String) User-defined text description of this disk. -- **image_id** (Number) ID of the image, which this disk was cloned from (valid for disk clones only). -- **pool** (String) Pool where this disk is located. -- **sep_id** (Number) Storage end-point provider serving this disk. -- **sep_type** (String) Type of the storage end-point provider serving this disk. -- **size** (Number) Size of the disk in GB. -- **type** (String) Type of this disk. E.g. D for data disks, B for boot. +- `account_id` (Number) +- `account_name` (String) +- `acl` (String) +- `boot_partition` (Number) +- `compute_id` (Number) +- `compute_name` (String) +- `created_time` (Number) +- `deleted_time` (Number) +- `desc` (String) +- `destruction_time` (Number) +- `devicename` (String) +- `disk_name` (String) +- `disk_path` (String) +- `gid` (Number) +- `guid` (Number) +- `id` (String) The ID of this resource. +- `image_id` (Number) +- `images` (List of String) +- `iotune` (List of Object) (see [below for nested schema](#nestedatt--iotune)) +- `iqn` (String) +- `login` (String) +- `milestones` (Number) +- `order` (Number) +- `params` (String) +- `parent_id` (Number) +- `passwd` (String) +- `pci_slot` (Number) +- `pool` (String) +- `purge_attempts` (Number) +- `purge_time` (Number) +- `reality_device_number` (Number) +- `reference_id` (String) +- `res_id` (String) +- `res_name` (String) +- `role` (String) +- `sep_id` (Number) +- `sep_type` (String) +- `size_max` (Number) +- `size_used` (Number) +- `snapshots` (List of Object) (see [below for nested schema](#nestedatt--snapshots)) +- `status` (String) +- `tech_status` (String) +- `type` (String) +- `vmid` (Number) ### Nested Schema for `timeouts` Optional: -- **default** (String) -- **read** (String) +- `default` (String) +- `read` (String) + + + +### Nested Schema for `iotune` + +Read-Only: + +- `read_bytes_sec` (Number) +- `read_bytes_sec_max` (Number) +- `read_iops_sec` (Number) +- `read_iops_sec_max` (Number) +- `size_iops_sec` (Number) +- `total_bytes_sec` (Number) +- `total_bytes_sec_max` (Number) +- `total_iops_sec` (Number) +- `total_iops_sec_max` (Number) +- `write_bytes_sec` (Number) +- `write_bytes_sec_max` (Number) +- `write_iops_sec` (Number) +- `write_iops_sec_max` (Number) + + + +### Nested Schema for `snapshots` + +Read-Only: + +- `guid` (String) +- `label` (String) +- `res_id` (String) +- `snap_set_guid` (String) +- `snap_set_time` (Number) +- `timestamp` (Number) diff --git a/docs/data-sources/disk_list.md b/docs/data-sources/disk_list.md index 2095104..b595ce0 100644 --- a/docs/data-sources/disk_list.md +++ b/docs/data-sources/disk_list.md @@ -1,6 +1,6 @@ --- # generated by https://github.com/hashicorp/terraform-plugin-docs -page_title: "decort_disk_list Data Source - terraform-provider-decort" +page_title: "decort_disk_list Data Source - decort" subcategory: "" description: |- @@ -17,24 +17,24 @@ description: |- ### Optional -- **account_id** (Number) ID of the account the disks belong to -- **id** (String) The ID of this resource. -- **page** (Number) Page number -- **size** (Number) Page size -- **timeouts** (Block, Optional) (see [below for nested schema](#nestedblock--timeouts)) -- **type** (String) type of the disks +- `account_id` (Number) ID of the account the disks belong to +- `page` (Number) Page number +- `size` (Number) Page size +- `timeouts` (Block, Optional) (see [below for nested schema](#nestedblock--timeouts)) +- `type` (String) type of the disks ### Read-Only -- **items** (List of Object) (see [below for nested schema](#nestedatt--items)) +- `id` (String) The ID of this resource. +- `items` (List of Object) (see [below for nested schema](#nestedatt--items)) ### Nested Schema for `timeouts` Optional: -- **default** (String) -- **read** (String) +- `default` (String) +- `read` (String) @@ -42,64 +42,83 @@ Optional: Read-Only: -- **account_id** (Number) -- **account_name** (String) -- **acl** (String) -- **boot_partition** (Number) -- **compute_id** (Number) -- **compute_name** (String) -- **created_time** (Number) -- **deleted_time** (Number) -- **desc** (String) -- **destruction_time** (Number) -- **devicename** (String) -- **disk_id** (Number) -- **disk_path** (String) -- **gid** (Number) -- **guid** (Number) -- **image_id** (Number) -- **images** (List of String) -- **iotune** (String) -- **iqn** (String) -- **login** (String) -- **machine_id** (Number) -- **machine_name** (String) -- **milestones** (Number) -- **name** (String) -- **order** (Number) -- **params** (String) -- **parent_id** (Number) -- **passwd** (String) -- **pci_slot** (Number) -- **pool** (String) -- **purge_attempts** (Number) -- **purge_time** (Number) -- **reality_device_number** (Number) -- **reference_id** (String) -- **res_id** (String) -- **res_name** (String) -- **role** (String) -- **sep_id** (Number) -- **sep_type** (String) -- **size_max** (Number) -- **size_used** (Number) -- **snapshots** (List of Object) (see [below for nested schema](#nestedobjatt--items--snapshots)) -- **status** (String) -- **tech_status** (String) -- **type** (String) -- **update_by** (Number) -- **vmid** (Number) +- `account_id` (Number) +- `account_name` (String) +- `acl` (String) +- `boot_partition` (Number) +- `compute_id` (Number) +- `compute_name` (String) +- `created_time` (Number) +- `deleted_time` (Number) +- `desc` (String) +- `destruction_time` (Number) +- `devicename` (String) +- `disk_id` (Number) +- `disk_name` (String) +- `disk_path` (String) +- `gid` (Number) +- `guid` (Number) +- `image_id` (Number) +- `images` (List of String) +- `iotune` (List of Object) (see [below for nested schema](#nestedobjatt--items--iotune)) +- `iqn` (String) +- `login` (String) +- `machine_id` (Number) +- `machine_name` (String) +- `milestones` (Number) +- `order` (Number) +- `params` (String) +- `parent_id` (Number) +- `passwd` (String) +- `pci_slot` (Number) +- `pool` (String) +- `purge_attempts` (Number) +- `purge_time` (Number) +- `reality_device_number` (Number) +- `reference_id` (String) +- `res_id` (String) +- `res_name` (String) +- `role` (String) +- `sep_id` (Number) +- `sep_type` (String) +- `size_max` (Number) +- `size_used` (Number) +- `snapshots` (List of Object) (see [below for nested schema](#nestedobjatt--items--snapshots)) +- `status` (String) +- `tech_status` (String) +- `type` (String) +- `vmid` (Number) + + +### Nested Schema for `items.iotune` + +Read-Only: + +- `read_bytes_sec` (Number) +- `read_bytes_sec_max` (Number) +- `read_iops_sec` (Number) +- `read_iops_sec_max` (Number) +- `size_iops_sec` (Number) +- `total_bytes_sec` (Number) +- `total_bytes_sec_max` (Number) +- `total_iops_sec` (Number) +- `total_iops_sec_max` (Number) +- `write_bytes_sec` (Number) +- `write_bytes_sec_max` (Number) +- `write_iops_sec` (Number) +- `write_iops_sec_max` (Number) + ### Nested Schema for `items.snapshots` Read-Only: -- **guid** (String) -- **label** (String) -- **res_id** (String) -- **snap_set_guid** (String) -- **snap_set_time** (Number) -- **timestamp** (Number) +- `guid` (String) +- `label` (String) +- `res_id` (String) +- `snap_set_guid` (String) +- `snap_set_time` (Number) +- `timestamp` (Number) diff --git a/docs/data-sources/extnet.md b/docs/data-sources/extnet.md index dedadab..df4bdf6 100644 --- a/docs/data-sources/extnet.md +++ b/docs/data-sources/extnet.md @@ -1,6 +1,6 @@ --- # generated by https://github.com/hashicorp/terraform-plugin-docs -page_title: "decort_extnet Data Source - terraform-provider-decort" +page_title: "decort_extnet Data Source - decort" subcategory: "" description: |- @@ -17,49 +17,49 @@ description: |- ### Required -- **net_id** (Number) +- `net_id` (Number) ### Optional -- **id** (String) The ID of this resource. -- **timeouts** (Block, Optional) (see [below for nested schema](#nestedblock--timeouts)) +- `timeouts` (Block, Optional) (see [below for nested schema](#nestedblock--timeouts)) ### Read-Only -- **check__ips** (List of String) -- **check_ips** (List of String) -- **ckey** (String) -- **default** (Boolean) -- **default_qos** (List of Object) (see [below for nested schema](#nestedatt--default_qos)) -- **desc** (String) -- **dns** (List of String) -- **excluded** (List of String) -- **free_ips** (Number) -- **gateway** (String) -- **gid** (Number) -- **guid** (Number) -- **ipcidr** (String) -- **meta** (List of String) meta -- **milestones** (Number) -- **net_name** (String) -- **network** (String) -- **network_id** (Number) -- **pre_reservations_num** (Number) -- **prefix** (Number) -- **pri_vnf_dev_id** (Number) -- **reservations** (List of Object) (see [below for nested schema](#nestedatt--reservations)) -- **shared_with** (List of Number) -- **status** (String) -- **vlan_id** (Number) -- **vnfs** (List of Object) (see [below for nested schema](#nestedatt--vnfs)) +- `check__ips` (List of String) +- `check_ips` (List of String) +- `ckey` (String) +- `default` (Boolean) +- `default_qos` (List of Object) (see [below for nested schema](#nestedatt--default_qos)) +- `desc` (String) +- `dns` (List of String) +- `excluded` (List of String) +- `free_ips` (Number) +- `gateway` (String) +- `gid` (Number) +- `guid` (Number) +- `id` (String) The ID of this resource. +- `ipcidr` (String) +- `meta` (List of String) meta +- `milestones` (Number) +- `net_name` (String) +- `network` (String) +- `network_id` (Number) +- `pre_reservations_num` (Number) +- `prefix` (Number) +- `pri_vnf_dev_id` (Number) +- `reservations` (List of Object) (see [below for nested schema](#nestedatt--reservations)) +- `shared_with` (List of Number) +- `status` (String) +- `vlan_id` (Number) +- `vnfs` (List of Object) (see [below for nested schema](#nestedatt--vnfs)) ### Nested Schema for `timeouts` Optional: -- **default** (String) -- **read** (String) +- `default` (String) +- `read` (String) @@ -67,10 +67,10 @@ Optional: Read-Only: -- **e_rate** (Number) -- **guid** (String) -- **in_burst** (Number) -- **in_rate** (Number) +- `e_rate` (Number) +- `guid` (String) +- `in_burst` (Number) +- `in_rate` (Number) @@ -78,14 +78,14 @@ Read-Only: Read-Only: -- **client_type** (String) -- **desc** (String) -- **domainname** (String) -- **hostname** (String) -- **ip** (String) -- **mac** (String) -- **type** (String) -- **vm_id** (Number) +- `client_type` (String) +- `desc` (String) +- `domainname` (String) +- `hostname` (String) +- `ip` (String) +- `mac` (String) +- `type` (String) +- `vm_id` (Number) @@ -93,6 +93,6 @@ Read-Only: Read-Only: -- **dhcp** (Number) +- `dhcp` (Number) diff --git a/docs/data-sources/extnet_computes_list.md b/docs/data-sources/extnet_computes_list.md index 76d4161..311e135 100644 --- a/docs/data-sources/extnet_computes_list.md +++ b/docs/data-sources/extnet_computes_list.md @@ -1,6 +1,6 @@ --- # generated by https://github.com/hashicorp/terraform-plugin-docs -page_title: "decort_extnet_computes_list Data Source - terraform-provider-decort" +page_title: "decort_extnet_computes_list Data Source - decort" subcategory: "" description: |- @@ -17,24 +17,24 @@ description: |- ### Required -- **account_id** (Number) filter by account ID +- `account_id` (Number) filter by account ID ### Optional -- **id** (String) The ID of this resource. -- **timeouts** (Block, Optional) (see [below for nested schema](#nestedblock--timeouts)) +- `timeouts` (Block, Optional) (see [below for nested schema](#nestedblock--timeouts)) ### Read-Only -- **items** (List of Object) (see [below for nested schema](#nestedatt--items)) +- `id` (String) The ID of this resource. +- `items` (List of Object) (see [below for nested schema](#nestedatt--items)) ### Nested Schema for `timeouts` Optional: -- **default** (String) -- **read** (String) +- `default` (String) +- `read` (String) @@ -42,22 +42,22 @@ Optional: Read-Only: -- **account_id** (Number) -- **account_name** (String) -- **extnets** (List of Object) (see [below for nested schema](#nestedobjatt--items--extnets)) -- **id** (Number) -- **name** (String) -- **rg_id** (Number) -- **rg_name** (String) +- `account_id` (Number) +- `account_name` (String) +- `extnets` (List of Object) (see [below for nested schema](#nestedobjatt--items--extnets)) +- `id` (Number) +- `name` (String) +- `rg_id` (Number) +- `rg_name` (String) ### Nested Schema for `items.extnets` Read-Only: -- **ipaddr** (String) -- **ipcidr** (String) -- **name** (String) -- **net_id** (Number) +- `ipaddr` (String) +- `ipcidr` (String) +- `name` (String) +- `net_id` (Number) diff --git a/docs/data-sources/extnet_default.md b/docs/data-sources/extnet_default.md index ca7ea93..4a53cd3 100644 --- a/docs/data-sources/extnet_default.md +++ b/docs/data-sources/extnet_default.md @@ -1,6 +1,6 @@ --- # generated by https://github.com/hashicorp/terraform-plugin-docs -page_title: "decort_extnet_default Data Source - terraform-provider-decort" +page_title: "decort_extnet_default Data Source - decort" subcategory: "" description: |- @@ -17,19 +17,19 @@ description: |- ### Optional -- **id** (String) The ID of this resource. -- **timeouts** (Block, Optional) (see [below for nested schema](#nestedblock--timeouts)) +- `timeouts` (Block, Optional) (see [below for nested schema](#nestedblock--timeouts)) ### Read-Only -- **net_id** (Number) +- `id` (String) The ID of this resource. +- `net_id` (Number) ### Nested Schema for `timeouts` Optional: -- **default** (String) -- **read** (String) +- `default` (String) +- `read` (String) diff --git a/docs/data-sources/extnet_list.md b/docs/data-sources/extnet_list.md index e0bc2c8..493aa29 100644 --- a/docs/data-sources/extnet_list.md +++ b/docs/data-sources/extnet_list.md @@ -1,6 +1,6 @@ --- # generated by https://github.com/hashicorp/terraform-plugin-docs -page_title: "decort_extnet_list Data Source - terraform-provider-decort" +page_title: "decort_extnet_list Data Source - decort" subcategory: "" description: |- @@ -17,23 +17,23 @@ description: |- ### Optional -- **account_id** (Number) filter by account ID -- **id** (String) The ID of this resource. -- **page** (Number) Page number -- **size** (Number) Page size -- **timeouts** (Block, Optional) (see [below for nested schema](#nestedblock--timeouts)) +- `account_id` (Number) filter by account ID +- `page` (Number) Page number +- `size` (Number) Page size +- `timeouts` (Block, Optional) (see [below for nested schema](#nestedblock--timeouts)) ### Read-Only -- **items** (List of Object) (see [below for nested schema](#nestedatt--items)) +- `id` (String) The ID of this resource. +- `items` (List of Object) (see [below for nested schema](#nestedatt--items)) ### Nested Schema for `timeouts` Optional: -- **default** (String) -- **read** (String) +- `default` (String) +- `read` (String) @@ -41,8 +41,8 @@ Optional: Read-Only: -- **ipcidr** (String) -- **name** (String) -- **net_id** (Number) +- `ipcidr` (String) +- `name` (String) +- `net_id` (Number) diff --git a/docs/data-sources/grid.md b/docs/data-sources/grid.md index 485b964..f438382 100644 --- a/docs/data-sources/grid.md +++ b/docs/data-sources/grid.md @@ -1,6 +1,6 @@ --- # generated by https://github.com/hashicorp/terraform-plugin-docs -page_title: "decort_grid Data Source - terraform-provider-decort" +page_title: "decort_grid Data Source - decort" subcategory: "" description: |- @@ -17,27 +17,27 @@ description: |- ### Required -- **grid_id** (Number) +- `grid_id` (Number) ### Optional -- **timeouts** (Block, Optional) (see [below for nested schema](#nestedblock--timeouts)) +- `timeouts` (Block, Optional) (see [below for nested schema](#nestedblock--timeouts)) ### Read-Only -- **flag** (String) -- **gid** (Number) -- **guid** (Number) -- **id** (Number) The ID of this resource. -- **location_code** (String) -- **name** (String) +- `flag` (String) +- `gid` (Number) +- `guid` (Number) +- `id` (Number) The ID of this resource. +- `location_code` (String) +- `name` (String) ### Nested Schema for `timeouts` Optional: -- **default** (String) -- **read** (String) +- `default` (String) +- `read` (String) diff --git a/docs/data-sources/grid_list.md b/docs/data-sources/grid_list.md index 1a98ff8..030b1fa 100644 --- a/docs/data-sources/grid_list.md +++ b/docs/data-sources/grid_list.md @@ -1,6 +1,6 @@ --- # generated by https://github.com/hashicorp/terraform-plugin-docs -page_title: "decort_grid_list Data Source - terraform-provider-decort" +page_title: "decort_grid_list Data Source - decort" subcategory: "" description: |- @@ -17,22 +17,22 @@ description: |- ### Optional -- **id** (String) The ID of this resource. -- **page** (Number) page number -- **size** (Number) page size -- **timeouts** (Block, Optional) (see [below for nested schema](#nestedblock--timeouts)) +- `page` (Number) page number +- `size` (Number) page size +- `timeouts` (Block, Optional) (see [below for nested schema](#nestedblock--timeouts)) ### Read-Only -- **items** (List of Object) grid list (see [below for nested schema](#nestedatt--items)) +- `id` (String) The ID of this resource. +- `items` (List of Object) grid list (see [below for nested schema](#nestedatt--items)) ### Nested Schema for `timeouts` Optional: -- **default** (String) -- **read** (String) +- `default` (String) +- `read` (String) @@ -40,11 +40,11 @@ Optional: Read-Only: -- **flag** (String) -- **gid** (Number) -- **guid** (Number) -- **id** (Number) -- **location_code** (String) -- **name** (String) +- `flag` (String) +- `gid` (Number) +- `guid` (Number) +- `id` (Number) +- `location_code` (String) +- `name` (String) diff --git a/docs/data-sources/image.md b/docs/data-sources/image.md index bc5f002..83faaa0 100644 --- a/docs/data-sources/image.md +++ b/docs/data-sources/image.md @@ -1,6 +1,6 @@ --- # generated by https://github.com/hashicorp/terraform-plugin-docs -page_title: "decort_image Data Source - terraform-provider-decort" +page_title: "decort_image Data Source - decort" subcategory: "" description: |- @@ -17,61 +17,58 @@ description: |- ### Required -- **image_id** (Number) image id +- `image_id` (Number) ### Optional -- **id** (String) The ID of this resource. -- **shared_with** (List of Number) -- **timeouts** (Block, Optional) (see [below for nested schema](#nestedblock--timeouts)) +- `show_all` (Boolean) +- `timeouts` (Block, Optional) (see [below for nested schema](#nestedblock--timeouts)) ### Read-Only -- **account_id** (Number) AccountId to make the image exclusive -- **architecture** (String) binary architecture of this image, one of X86_64 of PPC64_LE -- **boot_type** (String) Boot type of image bios or uefi -- **bootable** (Boolean) Does this image boot OS -- **computeci_id** (Number) -- **desc** (String) -- **drivers** (List of String) List of types of compute suitable for image. Example: [ "KVM_X86" ] -- **enabled** (Boolean) -- **gid** (Number) grid (platform) ID where this template should be create in -- **guid** (Number) -- **history** (List of Object) (see [below for nested schema](#nestedatt--history)) -- **hot_resize** (Boolean) Does this machine supports hot resize -- **image_type** (String) Image type linux, windows or other -- **last_modified** (Number) -- **link_to** (Number) -- **meta** (List of String) meta -- **milestones** (Number) -- **name** (String) Name of the rescue disk -- **password** (String) Optional password for the image -- **password_dl** (String) password for upload binary media -- **permanently** (Boolean) Whether to completely delete the image -- **pool_name** (String) pool for image create -- **provider_name** (String) -- **purge_attempts** (Number) -- **reference_id** (String) -- **res_id** (String) -- **res_name** (String) -- **rescuecd** (Boolean) -- **sep_id** (Number) storage endpoint provider ID -- **size** (Number) image size -- **status** (String) status -- **tech_status** (String) tech atatus -- **unc_path** (String) unc path -- **url** (String) URL where to download media from -- **username** (String) Optional username for the image -- **username_dl** (String) username for upload binary media -- **version** (String) version +- `account_id` (Number) +- `acl` (String) +- `architecture` (String) +- `boot_type` (String) +- `bootable` (Boolean) +- `ckey` (String) +- `compute_ci_id` (Number) +- `deleted_time` (String) +- `desc` (String) +- `drivers` (List of String) +- `enabled` (Boolean) +- `gid` (Number) +- `guid` (Number) +- `history` (List of Object) (see [below for nested schema](#nestedatt--history)) +- `hot_resize` (Boolean) +- `id` (String) The ID of this resource. +- `image_name` (String) +- `last_modified` (Number) +- `link_to` (Number) +- `milestones` (Number) +- `password` (String) +- `pool_name` (String) +- `provider_name` (String) +- `purge_attempts` (Number) +- `res_id` (String) +- `rescuecd` (Boolean) +- `sep_id` (Number) +- `shared_with` (List of Number) +- `size` (Number) +- `status` (String) +- `tech_status` (String) +- `type` (String) +- `unc_path` (String) +- `username` (String) +- `version` (String) ### Nested Schema for `timeouts` Optional: -- **default** (String) -- **read** (String) +- `default` (String) +- `read` (String) @@ -79,8 +76,8 @@ Optional: Read-Only: -- **guid** (String) -- **id** (Number) -- **timestamp** (Number) +- `guid` (String) +- `id` (Number) +- `timestamp` (Number) diff --git a/docs/data-sources/image_list.md b/docs/data-sources/image_list.md index 6e562a1..fbf21e1 100644 --- a/docs/data-sources/image_list.md +++ b/docs/data-sources/image_list.md @@ -1,6 +1,6 @@ --- # generated by https://github.com/hashicorp/terraform-plugin-docs -page_title: "decort_image_list Data Source - terraform-provider-decort" +page_title: "decort_image_list Data Source - decort" subcategory: "" description: |- @@ -17,24 +17,23 @@ description: |- ### Optional -- **id** (String) The ID of this resource. -- **page** (Number) page number -- **sep_id** (Number) filter images by storage endpoint provider ID -- **shared_with** (Number) filter images by account ID availability -- **size** (Number) page size -- **timeouts** (Block, Optional) (see [below for nested schema](#nestedblock--timeouts)) +- `account_id` (Number) optional account ID to include account images +- `page` (Number) page number +- `size` (Number) page size +- `timeouts` (Block, Optional) (see [below for nested schema](#nestedblock--timeouts)) ### Read-Only -- **items** (List of Object) image list (see [below for nested schema](#nestedatt--items)) +- `id` (String) The ID of this resource. +- `items` (List of Object) image list (see [below for nested schema](#nestedatt--items)) ### Nested Schema for `timeouts` Optional: -- **default** (String) -- **read** (String) +- `default` (String) +- `read` (String) @@ -42,53 +41,23 @@ Optional: Read-Only: -- **account_id** (Number) -- **architecture** (String) -- **boot_type** (String) -- **bootable** (Boolean) -- **computeci_id** (Number) -- **desc** (String) -- **drivers** (List of String) -- **enabled** (Boolean) -- **gid** (Number) -- **guid** (Number) -- **history** (List of Object) (see [below for nested schema](#nestedobjatt--items--history)) -- **hot_resize** (Boolean) -- **image_id** (Number) -- **image_type** (String) -- **last_modified** (Number) -- **link_to** (Number) -- **meta** (List of String) -- **milestones** (Number) -- **name** (String) -- **password** (String) -- **password_dl** (String) -- **permanently** (Boolean) -- **pool_name** (String) -- **provider_name** (String) -- **purge_attempts** (Number) -- **reference_id** (String) -- **res_id** (String) -- **res_name** (String) -- **rescuecd** (Boolean) -- **sep_id** (Number) -- **shared_with** (List of Number) -- **size** (Number) -- **status** (String) -- **tech_status** (String) -- **unc_path** (String) -- **url** (String) -- **username** (String) -- **username_dl** (String) -- **version** (String) - - -### Nested Schema for `items.history` - -Read-Only: - -- **guid** (String) -- **id** (Number) -- **timestamp** (Number) +- `account_id` (Number) +- `architecture` (String) +- `boot_type` (String) +- `bootable` (Boolean) +- `cdrom` (Boolean) +- `desc` (String) +- `drivers` (List of String) +- `hot_resize` (Boolean) +- `image_id` (Number) +- `image_name` (String) +- `link_to` (Number) +- `pool_name` (String) +- `sep_id` (Number) +- `size` (Number) +- `status` (String) +- `type` (String) +- `username` (String) +- `virtual` (Boolean) diff --git a/docs/data-sources/image_list_stacks.md b/docs/data-sources/image_list_stacks.md index 76c007f..e3ba873 100644 --- a/docs/data-sources/image_list_stacks.md +++ b/docs/data-sources/image_list_stacks.md @@ -1,6 +1,6 @@ --- # generated by https://github.com/hashicorp/terraform-plugin-docs -page_title: "decort_image_list_stacks Data Source - terraform-provider-decort" +page_title: "decort_image_list_stacks Data Source - decort" subcategory: "" description: |- @@ -17,26 +17,26 @@ description: |- ### Required -- **image_id** (Number) image id +- `image_id` (Number) image id ### Optional -- **id** (String) The ID of this resource. -- **page** (Number) page number -- **size** (Number) page size -- **timeouts** (Block, Optional) (see [below for nested schema](#nestedblock--timeouts)) +- `page` (Number) page number +- `size` (Number) page size +- `timeouts` (Block, Optional) (see [below for nested schema](#nestedblock--timeouts)) ### Read-Only -- **items** (List of Object) items of stacks list (see [below for nested schema](#nestedatt--items)) +- `id` (String) The ID of this resource. +- `items` (List of Object) items of stacks list (see [below for nested schema](#nestedatt--items)) ### Nested Schema for `timeouts` Optional: -- **default** (String) -- **read** (String) +- `default` (String) +- `read` (String) @@ -44,20 +44,20 @@ Optional: Read-Only: -- **api_key** (String) -- **api_url** (String) -- **app_id** (String) -- **desc** (String) -- **drivers** (List of String) -- **error** (Number) -- **guid** (Number) -- **id** (Number) -- **images** (List of Number) -- **login** (String) -- **name** (String) -- **passwd** (String) -- **reference_id** (String) -- **status** (String) -- **type** (String) +- `api_key` (String) +- `api_url` (String) +- `app_id` (String) +- `desc` (String) +- `drivers` (List of String) +- `error` (Number) +- `guid` (Number) +- `id` (Number) +- `images` (List of Number) +- `login` (String) +- `name` (String) +- `passwd` (String) +- `reference_id` (String) +- `status` (String) +- `type` (String) diff --git a/docs/data-sources/kvmvm.md b/docs/data-sources/kvmvm.md index 4cbb1d5..7aab86c 100644 --- a/docs/data-sources/kvmvm.md +++ b/docs/data-sources/kvmvm.md @@ -1,6 +1,6 @@ --- # generated by https://github.com/hashicorp/terraform-plugin-docs -page_title: "decort_kvmvm Data Source - terraform-provider-decort" +page_title: "decort_kvmvm Data Source - decort" subcategory: "" description: |- @@ -17,46 +17,46 @@ description: |- ### Optional -- **compute_id** (Number) ID of the compute instance. If ID is specified, name and resource group ID are ignored. -- **id** (String) The ID of this resource. -- **name** (String) Name of this compute instance. NOTE: this parameter is case sensitive. -- **network** (Block Set, Max: 8) Network connection(s) for this compute. (see [below for nested schema](#nestedblock--network)) -- **rg_id** (Number) ID of the resource group where this compute instance is located. -- **started** (Boolean) Is compute started. -- **timeouts** (Block, Optional) (see [below for nested schema](#nestedblock--timeouts)) +- `compute_id` (Number) ID of the compute instance. If ID is specified, name and resource group ID are ignored. +- `name` (String) Name of this compute instance. NOTE: this parameter is case sensitive. +- `network` (Block Set, Max: 8) Network connection(s) for this compute. (see [below for nested schema](#nestedblock--network)) +- `rg_id` (Number) ID of the resource group where this compute instance is located. +- `started` (Boolean) Is compute started. +- `timeouts` (Block, Optional) (see [below for nested schema](#nestedblock--timeouts)) ### Read-Only -- **account_id** (Number) ID of the account this compute instance belongs to. -- **account_name** (String) Name of the account this compute instance belongs to. -- **boot_disk_id** (Number) This compute instance boot disk ID. -- **boot_disk_size** (Number) This compute instance boot disk size in GB. -- **cloud_init** (String) Placeholder for cloud_init parameters. -- **cpu** (Number) Number of CPUs allocated for this compute instance. -- **description** (String) User-defined text description of this compute instance. -- **driver** (String) Hardware architecture of this compute instance. -- **extra_disks** (Set of Number) IDs of the extra disk(s) attached to this compute. -- **image_id** (Number) ID of the OS image this compute instance is based on. -- **image_name** (String) Name of the OS image this compute instance is based on. -- **os_users** (List of Object) Guest OS users provisioned on this compute instance. (see [below for nested schema](#nestedatt--os_users)) -- **ram** (Number) Amount of RAM in MB allocated for this compute instance. -- **rg_name** (String) Name of the resource group where this compute instance is located. +- `account_id` (Number) ID of the account this compute instance belongs to. +- `account_name` (String) Name of the account this compute instance belongs to. +- `boot_disk_id` (Number) This compute instance boot disk ID. +- `boot_disk_size` (Number) This compute instance boot disk size in GB. +- `cloud_init` (String) Placeholder for cloud_init parameters. +- `cpu` (Number) Number of CPUs allocated for this compute instance. +- `description` (String) User-defined text description of this compute instance. +- `driver` (String) Hardware architecture of this compute instance. +- `extra_disks` (Set of Number) IDs of the extra disk(s) attached to this compute. +- `id` (String) The ID of this resource. +- `image_id` (Number) ID of the OS image this compute instance is based on. +- `image_name` (String) Name of the OS image this compute instance is based on. +- `os_users` (List of Object) Guest OS users provisioned on this compute instance. (see [below for nested schema](#nestedatt--os_users)) +- `ram` (Number) Amount of RAM in MB allocated for this compute instance. +- `rg_name` (String) Name of the resource group where this compute instance is located. ### Nested Schema for `network` Required: -- **net_id** (Number) ID of the network for this connection. -- **net_type** (String) Type of the network for this connection, either EXTNET or VINS. +- `net_id` (Number) ID of the network for this connection. +- `net_type` (String) Type of the network for this connection, either EXTNET or VINS. Optional: -- **ip_address** (String) Optional IP address to assign to this connection. This IP should belong to the selected network and free for use. +- `ip_address` (String) Optional IP address to assign to this connection. This IP should belong to the selected network and free for use. Read-Only: -- **mac** (String) MAC address associated with this connection. MAC address is assigned automatically. +- `mac` (String) MAC address associated with this connection. MAC address is assigned automatically. @@ -64,8 +64,8 @@ Read-Only: Optional: -- **default** (String) -- **read** (String) +- `default` (String) +- `read` (String) @@ -73,9 +73,9 @@ Optional: Read-Only: -- **guid** (String) -- **login** (String) -- **password** (String) -- **public_key** (String) +- `guid` (String) +- `login` (String) +- `password` (String) +- `public_key` (String) diff --git a/docs/data-sources/location_url.md b/docs/data-sources/location_url.md new file mode 100644 index 0000000..aefcb5b --- /dev/null +++ b/docs/data-sources/location_url.md @@ -0,0 +1,35 @@ +--- +# generated by https://github.com/hashicorp/terraform-plugin-docs +page_title: "decort_location_url Data Source - decort" +subcategory: "" +description: |- + +--- + +# decort_location_url (Data Source) + + + + + + +## Schema + +### Optional + +- `timeouts` (Block, Optional) (see [below for nested schema](#nestedblock--timeouts)) + +### Read-Only + +- `id` (String) The ID of this resource. +- `url` (String) Location url + + +### Nested Schema for `timeouts` + +Optional: + +- `default` (String) +- `read` (String) + + diff --git a/docs/data-sources/locations_list.md b/docs/data-sources/locations_list.md new file mode 100644 index 0000000..f80e38e --- /dev/null +++ b/docs/data-sources/locations_list.md @@ -0,0 +1,52 @@ +--- +# generated by https://github.com/hashicorp/terraform-plugin-docs +page_title: "decort_locations_list Data Source - decort" +subcategory: "" +description: |- + +--- + +# decort_locations_list (Data Source) + + + + + + +## Schema + +### Optional + +- `page` (Number) page number +- `size` (Number) page size +- `timeouts` (Block, Optional) (see [below for nested schema](#nestedblock--timeouts)) + +### Read-Only + +- `id` (String) The ID of this resource. +- `items` (List of Object) Locations list (see [below for nested schema](#nestedatt--items)) + + +### Nested Schema for `timeouts` + +Optional: + +- `default` (String) +- `read` (String) + + + +### Nested Schema for `items` + +Read-Only: + +- `ckey` (String) +- `flag` (String) +- `gid` (Number) +- `guid` (Number) +- `id` (Number) +- `location_code` (String) +- `meta` (List of String) +- `name` (String) + + diff --git a/docs/data-sources/pcidevice.md b/docs/data-sources/pcidevice.md index ea44fb4..a3c6a09 100644 --- a/docs/data-sources/pcidevice.md +++ b/docs/data-sources/pcidevice.md @@ -1,6 +1,6 @@ --- # generated by https://github.com/hashicorp/terraform-plugin-docs -page_title: "decort_pcidevice Data Source - terraform-provider-decort" +page_title: "decort_pcidevice Data Source - decort" subcategory: "" description: |- @@ -17,33 +17,33 @@ description: |- ### Required -- **device_id** (Number) +- `device_id` (Number) ### Optional -- **id** (String) The ID of this resource. -- **timeouts** (Block, Optional) (see [below for nested schema](#nestedblock--timeouts)) +- `timeouts` (Block, Optional) (see [below for nested schema](#nestedblock--timeouts)) ### Read-Only -- **ckey** (String) -- **compute_id** (Number) -- **description** (String) -- **guid** (Number) -- **hw_path** (String) -- **meta** (List of String) -- **name** (String) -- **rg_id** (Number) -- **stack_id** (Number) -- **status** (String) -- **system_name** (String) +- `ckey` (String) +- `compute_id` (Number) +- `description` (String) +- `guid` (Number) +- `hw_path` (String) +- `id` (String) The ID of this resource. +- `meta` (List of String) +- `name` (String) +- `rg_id` (Number) +- `stack_id` (Number) +- `status` (String) +- `system_name` (String) ### Nested Schema for `timeouts` Optional: -- **default** (String) -- **read** (String) +- `default` (String) +- `read` (String) diff --git a/docs/data-sources/pcidevice_list.md b/docs/data-sources/pcidevice_list.md index ed65321..1555214 100644 --- a/docs/data-sources/pcidevice_list.md +++ b/docs/data-sources/pcidevice_list.md @@ -1,6 +1,6 @@ --- # generated by https://github.com/hashicorp/terraform-plugin-docs -page_title: "decort_pcidevice_list Data Source - terraform-provider-decort" +page_title: "decort_pcidevice_list Data Source - decort" subcategory: "" description: |- @@ -17,20 +17,20 @@ description: |- ### Optional -- **id** (String) The ID of this resource. -- **timeouts** (Block, Optional) (see [below for nested schema](#nestedblock--timeouts)) +- `timeouts` (Block, Optional) (see [below for nested schema](#nestedblock--timeouts)) ### Read-Only -- **items** (List of Object) pcidevice list (see [below for nested schema](#nestedatt--items)) +- `id` (String) The ID of this resource. +- `items` (List of Object) pcidevice list (see [below for nested schema](#nestedatt--items)) ### Nested Schema for `timeouts` Optional: -- **default** (String) -- **read** (String) +- `default` (String) +- `read` (String) @@ -38,17 +38,17 @@ Optional: Read-Only: -- **ckey** (String) -- **compute_id** (Number) -- **description** (String) -- **device_id** (Number) -- **guid** (Number) -- **hw_path** (String) -- **meta** (List of String) -- **name** (String) -- **rg_id** (Number) -- **stack_id** (Number) -- **status** (String) -- **system_name** (String) +- `ckey` (String) +- `compute_id` (Number) +- `description` (String) +- `device_id` (Number) +- `guid` (Number) +- `hw_path` (String) +- `meta` (List of String) +- `name` (String) +- `rg_id` (Number) +- `stack_id` (Number) +- `status` (String) +- `system_name` (String) diff --git a/docs/data-sources/resgroup.md b/docs/data-sources/resgroup.md index eeeef1c..8bed732 100644 --- a/docs/data-sources/resgroup.md +++ b/docs/data-sources/resgroup.md @@ -1,6 +1,6 @@ --- # generated by https://github.com/hashicorp/terraform-plugin-docs -page_title: "decort_resgroup Data Source - terraform-provider-decort" +page_title: "decort_resgroup Data Source - decort" subcategory: "" description: |- @@ -17,30 +17,30 @@ description: |- ### Required -- **account_id** (Number) Unique ID of the account, which this resource group belongs to. +- `account_id` (Number) Unique ID of the account, which this resource group belongs to. ### Optional -- **id** (String) The ID of this resource. -- **name** (String) Name of the resource group. Names are case sensitive and unique within the context of an account. -- **rg_id** (Number) Unique ID of the resource group. If this ID is specified, then resource group name is ignored. -- **timeouts** (Block, Optional) (see [below for nested schema](#nestedblock--timeouts)) +- `name` (String) Name of the resource group. Names are case sensitive and unique within the context of an account. +- `rg_id` (Number) Unique ID of the resource group. If this ID is specified, then resource group name is ignored. +- `timeouts` (Block, Optional) (see [below for nested schema](#nestedblock--timeouts)) ### Read-Only -- **account_name** (String) Name of the account, which this resource group belongs to. -- **def_net_id** (Number) ID of the default network for this resource group (if any). -- **def_net_type** (String) Type of the default network for this resource group. -- **description** (String) User-defined text description of this resource group. -- **quota** (List of Object) Quota settings for this resource group. (see [below for nested schema](#nestedatt--quota)) +- `account_name` (String) Name of the account, which this resource group belongs to. +- `def_net_id` (Number) ID of the default network for this resource group (if any). +- `def_net_type` (String) Type of the default network for this resource group. +- `description` (String) User-defined text description of this resource group. +- `id` (String) The ID of this resource. +- `quota` (List of Object) Quota settings for this resource group. (see [below for nested schema](#nestedatt--quota)) ### Nested Schema for `timeouts` Optional: -- **default** (String) -- **read** (String) +- `default` (String) +- `read` (String) @@ -48,11 +48,11 @@ Optional: Read-Only: -- **cpu** (Number) -- **disk** (Number) -- **ext_ips** (Number) -- **ext_traffic** (Number) -- **gpu_units** (Number) -- **ram** (Number) +- `cpu` (Number) +- `disk` (Number) +- `ext_ips` (Number) +- `ext_traffic` (Number) +- `gpu_units` (Number) +- `ram` (Number) diff --git a/docs/data-sources/rg_list.md b/docs/data-sources/rg_list.md index ddaea6d..b733529 100644 --- a/docs/data-sources/rg_list.md +++ b/docs/data-sources/rg_list.md @@ -1,6 +1,6 @@ --- # generated by https://github.com/hashicorp/terraform-plugin-docs -page_title: "decort_rg_list Data Source - terraform-provider-decort" +page_title: "decort_rg_list Data Source - decort" subcategory: "" description: |- @@ -17,23 +17,23 @@ description: |- ### Optional -- **id** (String) The ID of this resource. -- **includedeleted** (Boolean) included deleted resource groups -- **page** (Number) Page number -- **size** (Number) Page size -- **timeouts** (Block, Optional) (see [below for nested schema](#nestedblock--timeouts)) +- `includedeleted` (Boolean) included deleted resource groups +- `page` (Number) Page number +- `size` (Number) Page size +- `timeouts` (Block, Optional) (see [below for nested schema](#nestedblock--timeouts)) ### Read-Only -- **items** (List of Object) (see [below for nested schema](#nestedatt--items)) +- `id` (String) The ID of this resource. +- `items` (List of Object) (see [below for nested schema](#nestedatt--items)) ### Nested Schema for `timeouts` Optional: -- **default** (String) -- **read** (String) +- `default` (String) +- `read` (String) @@ -41,42 +41,42 @@ Optional: Read-Only: -- **account_id** (Number) -- **account_name** (String) -- **acl** (List of Object) (see [below for nested schema](#nestedobjatt--items--acl)) -- **created_by** (String) -- **created_time** (Number) -- **def_net_id** (Number) -- **def_net_type** (String) -- **deleted_by** (String) -- **deleted_time** (Number) -- **desc** (String) -- **gid** (Number) -- **guid** (Number) -- **lock_status** (String) -- **milestones** (Number) -- **name** (String) -- **register_computes** (Boolean) -- **resource_limits** (List of Object) (see [below for nested schema](#nestedobjatt--items--resource_limits)) -- **rg_id** (Number) -- **secret** (String) -- **status** (String) -- **updated_by** (String) -- **updated_time** (Number) -- **vins** (List of Number) -- **vms** (List of Number) +- `account_id` (Number) +- `account_name` (String) +- `acl` (List of Object) (see [below for nested schema](#nestedobjatt--items--acl)) +- `created_by` (String) +- `created_time` (Number) +- `def_net_id` (Number) +- `def_net_type` (String) +- `deleted_by` (String) +- `deleted_time` (Number) +- `desc` (String) +- `gid` (Number) +- `guid` (Number) +- `lock_status` (String) +- `milestones` (Number) +- `name` (String) +- `register_computes` (Boolean) +- `resource_limits` (List of Object) (see [below for nested schema](#nestedobjatt--items--resource_limits)) +- `rg_id` (Number) +- `secret` (String) +- `status` (String) +- `updated_by` (String) +- `updated_time` (Number) +- `vins` (List of Number) +- `vms` (List of Number) ### Nested Schema for `items.acl` Read-Only: -- **explicit** (Boolean) -- **guid** (String) -- **right** (String) -- **status** (String) -- **type** (String) -- **user_group_id** (String) +- `explicit` (Boolean) +- `guid` (String) +- `right` (String) +- `status` (String) +- `type` (String) +- `user_group_id` (String) @@ -84,11 +84,11 @@ Read-Only: Read-Only: -- **cu_c** (Number) -- **cu_d** (Number) -- **cu_i** (Number) -- **cu_m** (Number) -- **cu_np** (Number) -- **gpu_units** (Number) +- `cu_c` (Number) +- `cu_d` (Number) +- `cu_i` (Number) +- `cu_m` (Number) +- `cu_np` (Number) +- `gpu_units` (Number) diff --git a/docs/data-sources/sep.md b/docs/data-sources/sep.md index 85d29a2..ef46667 100644 --- a/docs/data-sources/sep.md +++ b/docs/data-sources/sep.md @@ -1,6 +1,6 @@ --- # generated by https://github.com/hashicorp/terraform-plugin-docs -page_title: "decort_sep Data Source - terraform-provider-decort" +page_title: "decort_sep Data Source - decort" subcategory: "" description: |- @@ -17,35 +17,35 @@ description: |- ### Required -- **sep_id** (Number) sep type des id +- `sep_id` (Number) sep type des id ### Optional -- **id** (String) The ID of this resource. -- **timeouts** (Block, Optional) (see [below for nested schema](#nestedblock--timeouts)) +- `timeouts` (Block, Optional) (see [below for nested schema](#nestedblock--timeouts)) ### Read-Only -- **ckey** (String) -- **config** (String) -- **consumed_by** (List of Number) -- **desc** (String) -- **gid** (Number) -- **guid** (Number) -- **meta** (List of String) -- **milestones** (Number) -- **name** (String) -- **obj_status** (String) -- **provided_by** (List of Number) -- **tech_status** (String) -- **type** (String) +- `ckey` (String) +- `config` (String) +- `consumed_by` (List of Number) +- `desc` (String) +- `gid` (Number) +- `guid` (Number) +- `id` (String) The ID of this resource. +- `meta` (List of String) +- `milestones` (Number) +- `name` (String) +- `obj_status` (String) +- `provided_by` (List of Number) +- `tech_status` (String) +- `type` (String) ### Nested Schema for `timeouts` Optional: -- **default** (String) -- **read** (String) +- `default` (String) +- `read` (String) diff --git a/docs/data-sources/sep_config.md b/docs/data-sources/sep_config.md index a676bdf..ed0c734 100644 --- a/docs/data-sources/sep_config.md +++ b/docs/data-sources/sep_config.md @@ -1,6 +1,6 @@ --- # generated by https://github.com/hashicorp/terraform-plugin-docs -page_title: "decort_sep_config Data Source - terraform-provider-decort" +page_title: "decort_sep_config Data Source - decort" subcategory: "" description: |- @@ -17,23 +17,23 @@ description: |- ### Required -- **sep_id** (Number) storage endpoint provider ID +- `sep_id` (Number) storage endpoint provider ID ### Optional -- **id** (String) The ID of this resource. -- **timeouts** (Block, Optional) (see [below for nested schema](#nestedblock--timeouts)) +- `timeouts` (Block, Optional) (see [below for nested schema](#nestedblock--timeouts)) ### Read-Only -- **config** (String) sep config json string +- `config` (String) sep config json string +- `id` (String) The ID of this resource. ### Nested Schema for `timeouts` Optional: -- **default** (String) -- **read** (String) +- `default` (String) +- `read` (String) diff --git a/docs/data-sources/sep_consumption.md b/docs/data-sources/sep_consumption.md index 6929b1e..dbbd037 100644 --- a/docs/data-sources/sep_consumption.md +++ b/docs/data-sources/sep_consumption.md @@ -1,6 +1,6 @@ --- # generated by https://github.com/hashicorp/terraform-plugin-docs -page_title: "decort_sep_consumption Data Source - terraform-provider-decort" +page_title: "decort_sep_consumption Data Source - decort" subcategory: "" description: |- @@ -17,26 +17,26 @@ description: |- ### Required -- **sep_id** (Number) sep id +- `sep_id` (Number) sep id ### Optional -- **id** (String) The ID of this resource. -- **timeouts** (Block, Optional) (see [below for nested schema](#nestedblock--timeouts)) +- `timeouts` (Block, Optional) (see [below for nested schema](#nestedblock--timeouts)) ### Read-Only -- **by_pool** (List of Object) consumption divided by pool (see [below for nested schema](#nestedatt--by_pool)) -- **total** (List of Object) total consumption (see [below for nested schema](#nestedatt--total)) -- **type** (String) sep type +- `by_pool` (List of Object) consumption divided by pool (see [below for nested schema](#nestedatt--by_pool)) +- `id` (String) The ID of this resource. +- `total` (List of Object) total consumption (see [below for nested schema](#nestedatt--total)) +- `type` (String) sep type ### Nested Schema for `timeouts` Optional: -- **default** (String) -- **read** (String) +- `default` (String) +- `read` (String) @@ -44,13 +44,13 @@ Optional: Read-Only: -- **disk_count** (Number) -- **disk_usage** (Number) -- **name** (String) -- **snapshot_count** (Number) -- **snapshot_usage** (Number) -- **usage** (Number) -- **usage_limit** (Number) +- `disk_count` (Number) +- `disk_usage` (Number) +- `name` (String) +- `snapshot_count` (Number) +- `snapshot_usage` (Number) +- `usage` (Number) +- `usage_limit` (Number) @@ -58,12 +58,12 @@ Read-Only: Read-Only: -- **capacity_limit** (Number) -- **disk_count** (Number) -- **disk_usage** (Number) -- **snapshot_count** (Number) -- **snapshot_usage** (Number) -- **usage** (Number) -- **usage_limit** (Number) +- `capacity_limit` (Number) +- `disk_count` (Number) +- `disk_usage` (Number) +- `snapshot_count` (Number) +- `snapshot_usage` (Number) +- `usage` (Number) +- `usage_limit` (Number) diff --git a/docs/data-sources/sep_disk_list.md b/docs/data-sources/sep_disk_list.md index 827a141..6b756e1 100644 --- a/docs/data-sources/sep_disk_list.md +++ b/docs/data-sources/sep_disk_list.md @@ -1,6 +1,6 @@ --- # generated by https://github.com/hashicorp/terraform-plugin-docs -page_title: "decort_sep_disk_list Data Source - terraform-provider-decort" +page_title: "decort_sep_disk_list Data Source - decort" subcategory: "" description: |- @@ -17,24 +17,24 @@ description: |- ### Required -- **sep_id** (Number) storage endpoint provider ID +- `sep_id` (Number) storage endpoint provider ID ### Optional -- **id** (String) The ID of this resource. -- **pool_name** (String) pool name -- **timeouts** (Block, Optional) (see [below for nested schema](#nestedblock--timeouts)) +- `pool_name` (String) pool name +- `timeouts` (Block, Optional) (see [below for nested schema](#nestedblock--timeouts)) ### Read-Only -- **items** (List of Number) sep disk list +- `id` (String) The ID of this resource. +- `items` (List of Number) sep disk list ### Nested Schema for `timeouts` Optional: -- **default** (String) -- **read** (String) +- `default` (String) +- `read` (String) diff --git a/docs/data-sources/sep_list.md b/docs/data-sources/sep_list.md index caad0b2..b024ac5 100644 --- a/docs/data-sources/sep_list.md +++ b/docs/data-sources/sep_list.md @@ -1,6 +1,6 @@ --- # generated by https://github.com/hashicorp/terraform-plugin-docs -page_title: "decort_sep_list Data Source - terraform-provider-decort" +page_title: "decort_sep_list Data Source - decort" subcategory: "" description: |- @@ -17,22 +17,22 @@ description: |- ### Optional -- **id** (String) The ID of this resource. -- **page** (Number) page number -- **size** (Number) page size -- **timeouts** (Block, Optional) (see [below for nested schema](#nestedblock--timeouts)) +- `page` (Number) page number +- `size` (Number) page size +- `timeouts` (Block, Optional) (see [below for nested schema](#nestedblock--timeouts)) ### Read-Only -- **items** (List of Object) sep list (see [below for nested schema](#nestedatt--items)) +- `id` (String) The ID of this resource. +- `items` (List of Object) sep list (see [below for nested schema](#nestedatt--items)) ### Nested Schema for `timeouts` Optional: -- **default** (String) -- **read** (String) +- `default` (String) +- `read` (String) @@ -40,19 +40,19 @@ Optional: Read-Only: -- **ckey** (String) -- **config** (String) -- **consumed_by** (List of Number) -- **desc** (String) -- **gid** (Number) -- **guid** (Number) -- **meta** (List of String) -- **milestones** (Number) -- **name** (String) -- **obj_status** (String) -- **provided_by** (List of Number) -- **sep_id** (Number) -- **tech_status** (String) -- **type** (String) +- `ckey` (String) +- `config` (String) +- `consumed_by` (List of Number) +- `desc` (String) +- `gid` (Number) +- `guid` (Number) +- `meta` (List of String) +- `milestones` (Number) +- `name` (String) +- `obj_status` (String) +- `provided_by` (List of Number) +- `sep_id` (Number) +- `tech_status` (String) +- `type` (String) diff --git a/docs/data-sources/sep_pool.md b/docs/data-sources/sep_pool.md index a70a366..2d41033 100644 --- a/docs/data-sources/sep_pool.md +++ b/docs/data-sources/sep_pool.md @@ -1,6 +1,6 @@ --- # generated by https://github.com/hashicorp/terraform-plugin-docs -page_title: "decort_sep_pool Data Source - terraform-provider-decort" +page_title: "decort_sep_pool Data Source - decort" subcategory: "" description: |- @@ -17,24 +17,24 @@ description: |- ### Required -- **pool_name** (String) pool name -- **sep_id** (Number) storage endpoint provider ID +- `pool_name` (String) pool name +- `sep_id` (Number) storage endpoint provider ID ### Optional -- **id** (String) The ID of this resource. -- **timeouts** (Block, Optional) (see [below for nested schema](#nestedblock--timeouts)) +- `timeouts` (Block, Optional) (see [below for nested schema](#nestedblock--timeouts)) ### Read-Only -- **pool** (String) +- `id` (String) The ID of this resource. +- `pool` (String) ### Nested Schema for `timeouts` Optional: -- **default** (String) -- **read** (String) +- `default` (String) +- `read` (String) diff --git a/docs/data-sources/snapshot_list.md b/docs/data-sources/snapshot_list.md index 4954d87..f43b222 100644 --- a/docs/data-sources/snapshot_list.md +++ b/docs/data-sources/snapshot_list.md @@ -1,6 +1,6 @@ --- # generated by https://github.com/hashicorp/terraform-plugin-docs -page_title: "decort_snapshot_list Data Source - terraform-provider-decort" +page_title: "decort_snapshot_list Data Source - decort" subcategory: "" description: |- @@ -17,24 +17,24 @@ description: |- ### Required -- **compute_id** (Number) ID of the compute instance to create snapshot for. +- `compute_id` (Number) ID of the compute instance to create snapshot for. ### Optional -- **id** (String) The ID of this resource. -- **timeouts** (Block, Optional) (see [below for nested schema](#nestedblock--timeouts)) +- `timeouts` (Block, Optional) (see [below for nested schema](#nestedblock--timeouts)) ### Read-Only -- **items** (List of Object) snapshot list (see [below for nested schema](#nestedatt--items)) +- `id` (String) The ID of this resource. +- `items` (List of Object) snapshot list (see [below for nested schema](#nestedatt--items)) ### Nested Schema for `timeouts` Optional: -- **default** (String) -- **read** (String) +- `default` (String) +- `read` (String) @@ -42,9 +42,9 @@ Optional: Read-Only: -- **disks** (List of Number) -- **guid** (String) -- **label** (String) -- **timestamp** (Number) +- `disks` (List of Number) +- `guid` (String) +- `label` (String) +- `timestamp` (Number) diff --git a/docs/data-sources/vgpu.md b/docs/data-sources/vgpu.md index 853bc45..8d4f467 100644 --- a/docs/data-sources/vgpu.md +++ b/docs/data-sources/vgpu.md @@ -1,6 +1,6 @@ --- # generated by https://github.com/hashicorp/terraform-plugin-docs -page_title: "decort_vgpu Data Source - terraform-provider-decort" +page_title: "decort_vgpu Data Source - decort" subcategory: "" description: |- @@ -17,21 +17,18 @@ description: |- ### Required -- **vgpu_id** (Number) - -### Optional - -- **id** (String) The ID of this resource. +- `vgpu_id` (Number) ### Read-Only -- **account_id** (Number) -- **mode** (String) -- **pgpu** (Number) -- **profile_id** (Number) -- **ram** (Number) -- **status** (String) -- **type** (String) -- **vm_id** (Number) +- `account_id` (Number) +- `id` (String) The ID of this resource. +- `mode` (String) +- `pgpu` (Number) +- `profile_id` (Number) +- `ram` (Number) +- `status` (String) +- `type` (String) +- `vm_id` (Number) diff --git a/docs/data-sources/vins.md b/docs/data-sources/vins.md index d67266d..b3731df 100644 --- a/docs/data-sources/vins.md +++ b/docs/data-sources/vins.md @@ -1,6 +1,6 @@ --- # generated by https://github.com/hashicorp/terraform-plugin-docs -page_title: "decort_vins Data Source - terraform-provider-decort" +page_title: "decort_vins Data Source - decort" subcategory: "" description: |- @@ -17,29 +17,29 @@ description: |- ### Required -- **name** (String) Name of the ViNS. Names are case sensitive and unique within the context of an account or resource group. +- `name` (String) Name of the ViNS. Names are case sensitive and unique within the context of an account or resource group. ### Optional -- **account_id** (Number) Unique ID of the account, which this ViNS belongs to. -- **id** (String) The ID of this resource. -- **rg_id** (Number) Unique ID of the resource group, where this ViNS is belongs to (for ViNS created at resource group level, 0 otherwise). -- **timeouts** (Block, Optional) (see [below for nested schema](#nestedblock--timeouts)) +- `account_id` (Number) Unique ID of the account, which this ViNS belongs to. +- `rg_id` (Number) Unique ID of the resource group, where this ViNS is belongs to (for ViNS created at resource group level, 0 otherwise). +- `timeouts` (Block, Optional) (see [below for nested schema](#nestedblock--timeouts)) ### Read-Only -- **account_name** (String) Name of the account, which this ViNS belongs to. -- **description** (String) User-defined text description of this ViNS. -- **ext_ip_addr** (String) IP address of the external connection (valid for ViNS connected to external network, empty string otherwise). -- **ext_net_id** (Number) ID of the external network this ViNS is connected to (-1 means no external connection). -- **ipcidr** (String) Network address used by this ViNS. +- `account_name` (String) Name of the account, which this ViNS belongs to. +- `description` (String) User-defined text description of this ViNS. +- `ext_ip_addr` (String) IP address of the external connection (valid for ViNS connected to external network, empty string otherwise). +- `ext_net_id` (Number) ID of the external network this ViNS is connected to (-1 means no external connection). +- `id` (String) The ID of this resource. +- `ipcidr` (String) Network address used by this ViNS. ### Nested Schema for `timeouts` Optional: -- **default** (String) -- **read** (String) +- `default` (String) +- `read` (String) diff --git a/docs/data-sources/vins_list.md b/docs/data-sources/vins_list.md index 4268af8..7710b0a 100644 --- a/docs/data-sources/vins_list.md +++ b/docs/data-sources/vins_list.md @@ -1,6 +1,6 @@ --- # generated by https://github.com/hashicorp/terraform-plugin-docs -page_title: "decort_vins_list Data Source - terraform-provider-decort" +page_title: "decort_vins_list Data Source - decort" subcategory: "" description: |- @@ -17,23 +17,23 @@ description: |- ### Optional -- **id** (String) The ID of this resource. -- **include_deleted** (Boolean) include deleted computes -- **page** (Number) Page number -- **size** (Number) Page size -- **timeouts** (Block, Optional) (see [below for nested schema](#nestedblock--timeouts)) +- `include_deleted` (Boolean) include deleted computes +- `page` (Number) Page number +- `size` (Number) Page size +- `timeouts` (Block, Optional) (see [below for nested schema](#nestedblock--timeouts)) ### Read-Only -- **items** (List of Object) (see [below for nested schema](#nestedatt--items)) +- `id` (String) The ID of this resource. +- `items` (List of Object) (see [below for nested schema](#nestedatt--items)) ### Nested Schema for `timeouts` Optional: -- **default** (String) -- **read** (String) +- `default` (String) +- `read` (String) @@ -41,21 +41,21 @@ Optional: Read-Only: -- **account_id** (Number) -- **account_name** (String) -- **created_by** (String) -- **created_time** (Number) -- **deleted_by** (String) -- **deleted_time** (Number) -- **external_ip** (String) -- **network** (String) -- **rg_id** (Number) -- **rg_name** (String) -- **status** (String) -- **updated_by** (String) -- **updated_time** (Number) -- **vins_id** (Number) -- **vins_name** (String) -- **vxlan_id** (Number) +- `account_id` (Number) +- `account_name` (String) +- `created_by` (String) +- `created_time` (Number) +- `deleted_by` (String) +- `deleted_time` (Number) +- `external_ip` (String) +- `network` (String) +- `rg_id` (Number) +- `rg_name` (String) +- `status` (String) +- `updated_by` (String) +- `updated_time` (Number) +- `vins_id` (Number) +- `vins_name` (String) +- `vxlan_id` (Number) diff --git a/docs/index.md b/docs/index.md index 971cd87..8bd9bca 100644 --- a/docs/index.md +++ b/docs/index.md @@ -17,15 +17,15 @@ description: |- ### Required -- **authenticator** (String) Authentication mode to use when connecting to DECORT cloud API. Should be one of 'oauth2', 'legacy' or 'jwt'. -- **controller_url** (String) URL of DECORT Cloud controller to use. API calls will be directed to this URL. +- `authenticator` (String) Authentication mode to use when connecting to DECORT cloud API. Should be one of 'oauth2', 'legacy' or 'jwt'. +- `controller_url` (String) URL of DECORT Cloud controller to use. API calls will be directed to this URL. ### Optional -- **allow_unverified_ssl** (Boolean) If true, DECORT API will not verify SSL certificates. Use this with caution and in trusted environments only! -- **app_id** (String) Application ID to access DECORT cloud API in 'oauth2' authentication mode. -- **app_secret** (String) Application secret to access DECORT cloud API in 'oauth2' authentication mode. -- **jwt** (String) JWT to access DECORT cloud API in 'jwt' authentication mode. -- **oauth2_url** (String) OAuth2 application URL in 'oauth2' authentication mode. -- **password** (String) User password for DECORT cloud API operations in 'legacy' authentication mode. -- **user** (String) User name for DECORT cloud API operations in 'legacy' authentication mode. +- `allow_unverified_ssl` (Boolean) If true, DECORT API will not verify SSL certificates. Use this with caution and in trusted environments only! +- `app_id` (String) Application ID to access DECORT cloud API in 'oauth2' authentication mode. +- `app_secret` (String) Application secret to access DECORT cloud API in 'oauth2' authentication mode. +- `jwt` (String) JWT to access DECORT cloud API in 'jwt' authentication mode. +- `oauth2_url` (String) OAuth2 application URL in 'oauth2' authentication mode. +- `password` (String) User password for DECORT cloud API operations in 'legacy' authentication mode. +- `user` (String) User name for DECORT cloud API operations in 'legacy' authentication mode. diff --git a/docs/resources/account.md b/docs/resources/account.md index c0d5edd..ca26a16 100644 --- a/docs/resources/account.md +++ b/docs/resources/account.md @@ -1,6 +1,6 @@ --- # generated by https://github.com/hashicorp/terraform-plugin-docs -page_title: "decort_account Resource - terraform-provider-decort" +page_title: "decort_account Resource - decort" subcategory: "" description: |- @@ -17,58 +17,58 @@ description: |- ### Required -- **account_name** (String) account name -- **username** (String) username of owner the account +- `account_name` (String) account name +- `username` (String) username of owner the account ### Optional -- **account_id** (Number) -- **emailaddress** (String) email -- **enable** (Boolean) enable/disable account -- **id** (String) The ID of this resource. -- **permanently** (Boolean) whether to completely delete the account -- **resource_limits** (Block List, Max: 1) (see [below for nested schema](#nestedblock--resource_limits)) -- **restore** (Boolean) restore a deleted account -- **send_access_emails** (Boolean) if true send emails when a user is granted access to resources -- **timeouts** (Block, Optional) (see [below for nested schema](#nestedblock--timeouts)) -- **users** (Block List) (see [below for nested schema](#nestedblock--users)) +- `account_id` (Number) +- `emailaddress` (String) email +- `enable` (Boolean) enable/disable account +- `permanently` (Boolean) whether to completely delete the account +- `resource_limits` (Block List, Max: 1) (see [below for nested schema](#nestedblock--resource_limits)) +- `restore` (Boolean) restore a deleted account +- `send_access_emails` (Boolean) if true send emails when a user is granted access to resources +- `timeouts` (Block, Optional) (see [below for nested schema](#nestedblock--timeouts)) +- `users` (Block List) (see [below for nested schema](#nestedblock--users)) ### Read-Only -- **acl** (List of Object) (see [below for nested schema](#nestedatt--acl)) -- **ckey** (String) -- **company** (String) -- **companyurl** (String) -- **computes** (List of Object) (see [below for nested schema](#nestedatt--computes)) -- **created_by** (String) -- **created_time** (Number) -- **dc_location** (String) -- **deactivation_time** (Number) -- **deleted_by** (String) -- **deleted_time** (Number) -- **displayname** (String) -- **guid** (Number) -- **machines** (List of Object) (see [below for nested schema](#nestedatt--machines)) -- **meta** (List of String) -- **resources** (List of Object) (see [below for nested schema](#nestedatt--resources)) -- **service_account** (Boolean) -- **status** (String) -- **updated_time** (Number) -- **version** (Number) -- **vins** (List of Number) -- **vinses** (Number) +- `acl` (List of Object) (see [below for nested schema](#nestedatt--acl)) +- `ckey` (String) +- `company` (String) +- `companyurl` (String) +- `computes` (List of Object) (see [below for nested schema](#nestedatt--computes)) +- `created_by` (String) +- `created_time` (Number) +- `dc_location` (String) +- `deactivation_time` (Number) +- `deleted_by` (String) +- `deleted_time` (Number) +- `displayname` (String) +- `guid` (Number) +- `id` (String) The ID of this resource. +- `machines` (List of Object) (see [below for nested schema](#nestedatt--machines)) +- `meta` (List of String) +- `resources` (List of Object) (see [below for nested schema](#nestedatt--resources)) +- `service_account` (Boolean) +- `status` (String) +- `updated_time` (Number) +- `version` (Number) +- `vins` (List of Number) +- `vinses` (Number) ### Nested Schema for `resource_limits` Optional: -- **cu_c** (Number) -- **cu_d** (Number) -- **cu_i** (Number) -- **cu_m** (Number) -- **cu_np** (Number) -- **gpu_units** (Number) +- `cu_c` (Number) +- `cu_d` (Number) +- `cu_i` (Number) +- `cu_m` (Number) +- `cu_np` (Number) +- `gpu_units` (Number) @@ -76,11 +76,11 @@ Optional: Optional: -- **create** (String) -- **default** (String) -- **delete** (String) -- **read** (String) -- **update** (String) +- `create` (String) +- `default` (String) +- `delete` (String) +- `read` (String) +- `update` (String) @@ -88,12 +88,12 @@ Optional: Required: -- **access_type** (String) -- **user_id** (String) +- `access_type` (String) +- `user_id` (String) Optional: -- **recursive_delete** (Boolean) +- `recursive_delete` (Boolean) @@ -101,13 +101,13 @@ Optional: Read-Only: -- **can_be_deleted** (Boolean) -- **explicit** (Boolean) -- **guid** (String) -- **right** (String) -- **status** (String) -- **type** (String) -- **user_group_id** (String) +- `can_be_deleted` (Boolean) +- `explicit` (Boolean) +- `guid` (String) +- `right` (String) +- `status` (String) +- `type` (String) +- `user_group_id` (String) @@ -115,8 +115,8 @@ Read-Only: Read-Only: -- **started** (Number) -- **stopped** (Number) +- `started` (Number) +- `stopped` (Number) @@ -124,8 +124,8 @@ Read-Only: Read-Only: -- **halted** (Number) -- **running** (Number) +- `halted` (Number) +- `running` (Number) @@ -133,20 +133,20 @@ Read-Only: Read-Only: -- **current** (List of Object) (see [below for nested schema](#nestedobjatt--resources--current)) -- **reserved** (List of Object) (see [below for nested schema](#nestedobjatt--resources--reserved)) +- `current` (List of Object) (see [below for nested schema](#nestedobjatt--resources--current)) +- `reserved` (List of Object) (see [below for nested schema](#nestedobjatt--resources--reserved)) ### Nested Schema for `resources.current` Read-Only: -- **cpu** (Number) -- **disksize** (Number) -- **extips** (Number) -- **exttraffic** (Number) -- **gpu** (Number) -- **ram** (Number) +- `cpu` (Number) +- `disksize` (Number) +- `extips` (Number) +- `exttraffic` (Number) +- `gpu` (Number) +- `ram` (Number) @@ -154,11 +154,11 @@ Read-Only: Read-Only: -- **cpu** (Number) -- **disksize** (Number) -- **extips** (Number) -- **exttraffic** (Number) -- **gpu** (Number) -- **ram** (Number) +- `cpu` (Number) +- `disksize` (Number) +- `extips` (Number) +- `exttraffic` (Number) +- `gpu` (Number) +- `ram` (Number) diff --git a/docs/resources/bservice.md b/docs/resources/bservice.md index 0f52bf8..b9884e6 100644 --- a/docs/resources/bservice.md +++ b/docs/resources/bservice.md @@ -1,6 +1,6 @@ --- # generated by https://github.com/hashicorp/terraform-plugin-docs -page_title: "decort_bservice Resource - terraform-provider-decort" +page_title: "decort_bservice Resource - decort" subcategory: "" description: |- @@ -17,62 +17,62 @@ description: |- ### Required -- **rg_id** (Number) ID of the Resource Group where this service will be placed -- **service_name** (String) Name of the service +- `rg_id` (Number) ID of the Resource Group where this service will be placed +- `service_name` (String) Name of the service ### Optional -- **enable** (Boolean) if set to False, Basic service will be deleted to recycle bin. Otherwise destroyed immediately -- **id** (String) The ID of this resource. -- **permanently** (Boolean) if set to False, Basic service will be deleted to recycle bin. Otherwise destroyed immediately -- **restore** (Boolean) Restores BasicService instance -- **service_id** (Number) -- **snapshots** (Block List) (see [below for nested schema](#nestedblock--snapshots)) -- **ssh_key** (String) SSH key to deploy for the specified user. Same key will be deployed to all computes of the service. -- **ssh_user** (String) name of the user to deploy SSH key for. Pass empty string if no SSH key deployment is required -- **start** (Boolean) Start service. Starting a service technically means starting computes from all service groups according to group relations -- **timeouts** (Block, Optional) (see [below for nested schema](#nestedblock--timeouts)) +- `enable` (Boolean) if set to False, Basic service will be deleted to recycle bin. Otherwise destroyed immediately +- `permanently` (Boolean) if set to False, Basic service will be deleted to recycle bin. Otherwise destroyed immediately +- `restore` (Boolean) Restores BasicService instance +- `service_id` (Number) +- `snapshots` (Block List) (see [below for nested schema](#nestedblock--snapshots)) +- `ssh_key` (String) SSH key to deploy for the specified user. Same key will be deployed to all computes of the service. +- `ssh_user` (String) name of the user to deploy SSH key for. Pass empty string if no SSH key deployment is required +- `start` (Boolean) Start service. Starting a service technically means starting computes from all service groups according to group relations +- `timeouts` (Block, Optional) (see [below for nested schema](#nestedblock--timeouts)) ### Read-Only -- **account_id** (Number) -- **account_name** (String) -- **base_domain** (String) -- **computes** (List of Object) (see [below for nested schema](#nestedatt--computes)) -- **cpu_total** (Number) -- **created_by** (String) -- **created_time** (Number) -- **deleted_by** (String) -- **deleted_time** (Number) -- **disk_total** (String) -- **gid** (Number) -- **groups** (List of Number) -- **groups_name** (List of String) -- **guid** (Number) -- **milestones** (Number) -- **parent_srv_id** (Number) -- **parent_srv_type** (String) -- **ram_total** (Number) -- **rg_name** (String) -- **status** (String) -- **tech_status** (String) -- **updated_by** (String) -- **updated_time** (Number) -- **user_managed** (Boolean) +- `account_id` (Number) +- `account_name` (String) +- `base_domain` (String) +- `computes` (List of Object) (see [below for nested schema](#nestedatt--computes)) +- `cpu_total` (Number) +- `created_by` (String) +- `created_time` (Number) +- `deleted_by` (String) +- `deleted_time` (Number) +- `disk_total` (String) +- `gid` (Number) +- `groups` (List of Number) +- `groups_name` (List of String) +- `guid` (Number) +- `id` (String) The ID of this resource. +- `milestones` (Number) +- `parent_srv_id` (Number) +- `parent_srv_type` (String) +- `ram_total` (Number) +- `rg_name` (String) +- `status` (String) +- `tech_status` (String) +- `updated_by` (String) +- `updated_time` (Number) +- `user_managed` (Boolean) ### Nested Schema for `snapshots` Optional: -- **label** (String) -- **rollback** (Boolean) +- `label` (String) +- `rollback` (Boolean) Read-Only: -- **guid** (String) -- **timestamp** (Number) -- **valid** (Boolean) +- `guid` (String) +- `timestamp` (Number) +- `valid` (Boolean) @@ -80,11 +80,11 @@ Read-Only: Optional: -- **create** (String) -- **default** (String) -- **delete** (String) -- **read** (String) -- **update** (String) +- `create` (String) +- `default` (String) +- `delete` (String) +- `read` (String) +- `update` (String) @@ -92,10 +92,10 @@ Optional: Read-Only: -- **compgroup_id** (Number) -- **compgroup_name** (String) -- **compgroup_role** (String) -- **id** (Number) -- **name** (String) +- `compgroup_id` (Number) +- `compgroup_name` (String) +- `compgroup_role` (String) +- `id` (Number) +- `name` (String) diff --git a/docs/resources/bservice_group.md b/docs/resources/bservice_group.md index 5ab6a26..9e0af6b 100644 --- a/docs/resources/bservice_group.md +++ b/docs/resources/bservice_group.md @@ -1,6 +1,6 @@ --- # generated by https://github.com/hashicorp/terraform-plugin-docs -page_title: "decort_bservice_group Resource - terraform-provider-decort" +page_title: "decort_bservice_group Resource - decort" subcategory: "" description: |- @@ -17,63 +17,63 @@ description: |- ### Required -- **comp_count** (Number) computes number. Defines how many computes must be there in the group -- **compgroup_name** (String) name of the Compute Group to add -- **cpu** (Number) compute CPU number. All computes in the group have the same CPU count -- **disk** (Number) compute boot disk size in GB -- **driver** (String) compute driver like a KVM_X86, KVM_PPC, etc. -- **image_id** (Number) OS image ID to create computes from -- **ram** (Number) compute RAM volume in MB. All computes in the group have the same RAM volume -- **service_id** (Number) ID of the Basic Service to add a group to +- `comp_count` (Number) computes number. Defines how many computes must be there in the group +- `compgroup_name` (String) name of the Compute Group to add +- `cpu` (Number) compute CPU number. All computes in the group have the same CPU count +- `disk` (Number) compute boot disk size in GB +- `driver` (String) compute driver like a KVM_X86, KVM_PPC, etc. +- `image_id` (Number) OS image ID to create computes from +- `ram` (Number) compute RAM volume in MB. All computes in the group have the same RAM volume +- `service_id` (Number) ID of the Basic Service to add a group to ### Optional -- **compgroup_id** (Number) -- **extnets** (List of Number) list of external networks to connect computes to -- **force_stop** (Boolean) force stop Compute Group -- **force_update** (Boolean) force resize Compute Group -- **id** (String) The ID of this resource. -- **mode** (String) (RELATIVE;ABSOLUTE) either delta or absolute value of computes -- **parents** (List of Number) -- **remove_computes** (List of Number) -- **role** (String) group role tag. Can be empty string, does not have to be unique -- **start** (Boolean) Start the specified Compute Group within BasicService -- **timeout_start** (Number) time of Compute Group readiness -- **timeouts** (Block, Optional) (see [below for nested schema](#nestedblock--timeouts)) -- **vinses** (List of Number) list of ViNSes to connect computes to +- `compgroup_id` (Number) +- `extnets` (List of Number) list of external networks to connect computes to +- `force_stop` (Boolean) force stop Compute Group +- `force_update` (Boolean) force resize Compute Group +- `mode` (String) (RELATIVE;ABSOLUTE) either delta or absolute value of computes +- `parents` (List of Number) +- `remove_computes` (List of Number) +- `role` (String) group role tag. Can be empty string, does not have to be unique +- `start` (Boolean) Start the specified Compute Group within BasicService +- `timeout_start` (Number) time of Compute Group readiness +- `timeouts` (Block, Optional) (see [below for nested schema](#nestedblock--timeouts)) +- `vinses` (List of Number) list of ViNSes to connect computes to ### Read-Only -- **account_id** (Number) -- **account_name** (String) -- **computes** (List of Object) (see [below for nested schema](#nestedatt--computes)) -- **consistency** (Boolean) -- **created_by** (String) -- **created_time** (Number) -- **deleted_by** (String) -- **deleted_time** (Number) -- **gid** (Number) -- **guid** (Number) -- **milestones** (Number) -- **rg_id** (Number) -- **rg_name** (String) -- **sep_id** (Number) -- **seq_no** (Number) -- **status** (String) -- **tech_status** (String) -- **updated_by** (String) -- **updated_time** (Number) +- `account_id` (Number) +- `account_name` (String) +- `computes` (List of Object) (see [below for nested schema](#nestedatt--computes)) +- `consistency` (Boolean) +- `created_by` (String) +- `created_time` (Number) +- `deleted_by` (String) +- `deleted_time` (Number) +- `gid` (Number) +- `guid` (Number) +- `id` (String) The ID of this resource. +- `milestones` (Number) +- `rg_id` (Number) +- `rg_name` (String) +- `sep_id` (Number) +- `seq_no` (Number) +- `status` (String) +- `tech_status` (String) +- `updated_by` (String) +- `updated_time` (Number) ### Nested Schema for `timeouts` Optional: -- **create** (String) -- **default** (String) -- **delete** (String) -- **read** (String) -- **update** (String) +- `create` (String) +- `default` (String) +- `delete` (String) +- `read` (String) +- `update` (String) @@ -81,17 +81,17 @@ Optional: Read-Only: -- **id** (Number) -- **ip_addresses** (List of String) -- **name** (String) -- **os_users** (List of Object) (see [below for nested schema](#nestedobjatt--computes--os_users)) +- `id` (Number) +- `ip_addresses` (List of String) +- `name` (String) +- `os_users` (List of Object) (see [below for nested schema](#nestedobjatt--computes--os_users)) ### Nested Schema for `computes.os_users` Read-Only: -- **login** (String) -- **password** (String) +- `login` (String) +- `password` (String) diff --git a/docs/resources/cdrom_image.md b/docs/resources/cdrom_image.md index da72956..6d7caac 100644 --- a/docs/resources/cdrom_image.md +++ b/docs/resources/cdrom_image.md @@ -1,6 +1,6 @@ --- # generated by https://github.com/hashicorp/terraform-plugin-docs -page_title: "decort_cdrom_image Resource - terraform-provider-decort" +page_title: "decort_cdrom_image Resource - decort" subcategory: "" description: |- @@ -17,64 +17,64 @@ description: |- ### Required -- **drivers** (List of String) List of types of compute suitable for image. Example: [ "KVM_X86" ] -- **gid** (Number) grid (platform) ID where this template should be create in -- **name** (String) Name of the rescue disk -- **url** (String) URL where to download ISO from +- `drivers` (List of String) List of types of compute suitable for image. Example: [ "KVM_X86" ] +- `gid` (Number) grid (platform) ID where this template should be create in +- `name` (String) Name of the rescue disk +- `url` (String) URL where to download ISO from ### Optional -- **account_id** (Number) AccountId to make the image exclusive -- **architecture** (String) binary architecture of this image, one of X86_64 of PPC64_LE -- **bootable** (Boolean) Does this image boot OS -- **computeci_id** (Number) -- **enabled** (Boolean) -- **enabled_stacks** (List of String) -- **hot_resize** (Boolean) Does this machine supports hot resize -- **id** (String) The ID of this resource. -- **password** (String) Optional password for the image -- **password_dl** (String) password for upload binary media -- **permanently** (Boolean) Whether to completely delete the image -- **pool_name** (String) pool for image create -- **sep_id** (Number) storage endpoint provider ID -- **shared_with** (List of Number) -- **timeouts** (Block, Optional) (see [below for nested schema](#nestedblock--timeouts)) -- **username** (String) Optional username for the image -- **username_dl** (String) username for upload binary media +- `account_id` (Number) AccountId to make the image exclusive +- `architecture` (String) binary architecture of this image, one of X86_64 of PPC64_LE +- `bootable` (Boolean) Does this image boot OS +- `computeci_id` (Number) +- `enabled` (Boolean) +- `enabled_stacks` (List of String) +- `hot_resize` (Boolean) Does this machine supports hot resize +- `password` (String) Optional password for the image +- `password_dl` (String) password for upload binary media +- `permanently` (Boolean) Whether to completely delete the image +- `pool_name` (String) pool for image create +- `sep_id` (Number) storage endpoint provider ID +- `shared_with` (List of Number) +- `timeouts` (Block, Optional) (see [below for nested schema](#nestedblock--timeouts)) +- `username` (String) Optional username for the image +- `username_dl` (String) username for upload binary media ### Read-Only -- **boot_type** (String) Boot type of image bios or uefi -- **desc** (String) -- **guid** (Number) -- **history** (List of Object) (see [below for nested schema](#nestedatt--history)) -- **image_id** (Number) image id -- **image_type** (String) Image type linux, windows or other -- **link_to** (Number) -- **meta** (List of String) meta -- **milestones** (Number) -- **provider_name** (String) -- **purge_attempts** (Number) -- **reference_id** (String) -- **res_id** (String) -- **res_name** (String) -- **rescuecd** (Boolean) -- **size** (Number) image size -- **status** (String) status -- **tech_status** (String) tech atatus -- **unc_path** (String) unc path -- **version** (String) version +- `boot_type` (String) Boot type of image bios or uefi +- `desc` (String) +- `guid` (Number) +- `history` (List of Object) (see [below for nested schema](#nestedatt--history)) +- `id` (String) The ID of this resource. +- `image_id` (Number) image id +- `image_type` (String) Image type linux, windows or other +- `link_to` (Number) +- `meta` (List of String) meta +- `milestones` (Number) +- `provider_name` (String) +- `purge_attempts` (Number) +- `reference_id` (String) +- `res_id` (String) +- `res_name` (String) +- `rescuecd` (Boolean) +- `size` (Number) image size +- `status` (String) status +- `tech_status` (String) tech atatus +- `unc_path` (String) unc path +- `version` (String) version ### Nested Schema for `timeouts` Optional: -- **create** (String) -- **default** (String) -- **delete** (String) -- **read** (String) -- **update** (String) +- `create` (String) +- `default` (String) +- `delete` (String) +- `read` (String) +- `update` (String) @@ -82,8 +82,8 @@ Optional: Read-Only: -- **guid** (String) -- **id** (Number) -- **timestamp** (Number) +- `guid` (String) +- `id` (Number) +- `timestamp` (Number) diff --git a/docs/resources/delete_images.md b/docs/resources/delete_images.md index 0bc352e..6be6e06 100644 --- a/docs/resources/delete_images.md +++ b/docs/resources/delete_images.md @@ -1,6 +1,6 @@ --- # generated by https://github.com/hashicorp/terraform-plugin-docs -page_title: "decort_delete_images Resource - terraform-provider-decort" +page_title: "decort_delete_images Resource - decort" subcategory: "" description: |- @@ -17,24 +17,27 @@ description: |- ### Required -- **image_ids** (List of Number) images ids for deleting -- **reason** (String) reason for deleting the images +- `image_ids` (List of Number) images ids for deleting +- `reason` (String) reason for deleting the images ### Optional -- **id** (String) The ID of this resource. -- **permanently** (Boolean) whether to completely delete the images -- **timeouts** (Block, Optional) (see [below for nested schema](#nestedblock--timeouts)) +- `permanently` (Boolean) whether to completely delete the images +- `timeouts` (Block, Optional) (see [below for nested schema](#nestedblock--timeouts)) + +### Read-Only + +- `id` (String) The ID of this resource. ### Nested Schema for `timeouts` Optional: -- **create** (String) -- **default** (String) -- **delete** (String) -- **read** (String) -- **update** (String) +- `create` (String) +- `default` (String) +- `delete` (String) +- `read` (String) +- `update` (String) diff --git a/docs/resources/disk.md b/docs/resources/disk.md index b19e57f..b7e746a 100644 --- a/docs/resources/disk.md +++ b/docs/resources/disk.md @@ -1,6 +1,6 @@ --- # generated by https://github.com/hashicorp/terraform-plugin-docs -page_title: "decort_disk Resource - terraform-provider-decort" +page_title: "decort_disk Resource - decort" subcategory: "" description: |- @@ -17,35 +17,105 @@ description: |- ### Required -- **account_id** (Number) ID of the account this disk belongs to. -- **name** (String) Name of this disk. NOTE: disk names are NOT unique within an account. If disk ID is specified, disk name is ignored. -- **size** (Number) Size of the disk in GB. Note, that existing disks can only be grown in size. +- `account_id` (Number) +- `disk_name` (String) +- `gid` (Number) +- `size_max` (Number) ### Optional -- **description** (String) Optional user-defined text description of this disk. -- **disk_id** (Number) ID of the disk to get. If disk ID is specified, then disk name and account ID are ignored. -- **id** (String) The ID of this resource. -- **pool** (String) Pool where this disk is located. Cannot be changed for existing disk. -- **sep_id** (Number) Storage end-point provider serving this disk. Cannot be changed for existing disk. -- **timeouts** (Block, Optional) (see [below for nested schema](#nestedblock--timeouts)) +- `desc` (String) +- `detach` (Boolean) detach disk from machine first +- `iotune` (Block List, Max: 1) (see [below for nested schema](#nestedblock--iotune)) +- `permanently` (Boolean) whether to completely delete the disk, works only with non attached disks +- `pool` (String) +- `reason` (String) reason for an action +- `restore` (Boolean) restore deleting disk +- `sep_id` (Number) +- `timeouts` (Block, Optional) (see [below for nested schema](#nestedblock--timeouts)) +- `type` (String) ### Read-Only -- **account_name** (String) Name of the account this disk belongs to. -- **image_id** (Number) ID of the image, which this disk was cloned from (if ever cloned). -- **sep_type** (String) Type of the storage end-point provider serving this disk. -- **type** (String) Type of this disk. +- `account_name` (String) +- `acl` (String) +- `boot_partition` (Number) +- `compute_id` (Number) +- `compute_name` (String) +- `created_time` (Number) +- `deleted_time` (Number) +- `destruction_time` (Number) +- `devicename` (String) +- `disk_id` (Number) +- `disk_path` (String) +- `guid` (Number) +- `id` (String) The ID of this resource. +- `image_id` (Number) +- `images` (List of String) +- `iqn` (String) +- `login` (String) +- `milestones` (Number) +- `order` (Number) +- `params` (String) +- `parent_id` (Number) +- `passwd` (String) +- `pci_slot` (Number) +- `purge_attempts` (Number) +- `purge_time` (Number) +- `reality_device_number` (Number) +- `reference_id` (String) +- `res_id` (String) +- `res_name` (String) +- `role` (String) +- `sep_type` (String) +- `size_used` (Number) +- `snapshots` (List of Object) (see [below for nested schema](#nestedatt--snapshots)) +- `status` (String) +- `tech_status` (String) +- `vmid` (Number) + + +### Nested Schema for `iotune` + +Optional: + +- `read_bytes_sec` (Number) +- `read_bytes_sec_max` (Number) +- `read_iops_sec` (Number) +- `read_iops_sec_max` (Number) +- `size_iops_sec` (Number) +- `total_bytes_sec` (Number) +- `total_bytes_sec_max` (Number) +- `total_iops_sec` (Number) +- `total_iops_sec_max` (Number) +- `write_bytes_sec` (Number) +- `write_bytes_sec_max` (Number) +- `write_iops_sec` (Number) +- `write_iops_sec_max` (Number) + ### Nested Schema for `timeouts` Optional: -- **create** (String) -- **default** (String) -- **delete** (String) -- **read** (String) -- **update** (String) +- `create` (String) +- `default` (String) +- `delete` (String) +- `read` (String) +- `update` (String) + + + +### Nested Schema for `snapshots` + +Read-Only: + +- `guid` (String) +- `label` (String) +- `res_id` (String) +- `snap_set_guid` (String) +- `snap_set_time` (Number) +- `timestamp` (Number) diff --git a/docs/resources/image.md b/docs/resources/image.md index a53623c..a4cfadd 100644 --- a/docs/resources/image.md +++ b/docs/resources/image.md @@ -1,6 +1,6 @@ --- # generated by https://github.com/hashicorp/terraform-plugin-docs -page_title: "decort_image Resource - terraform-provider-decort" +page_title: "decort_image Resource - decort" subcategory: "" description: |- @@ -17,67 +17,65 @@ description: |- ### Required -- **boot_type** (String) Boot type of image bios or uefi -- **drivers** (List of String) List of types of compute suitable for image. Example: [ "KVM_X86" ] -- **gid** (Number) grid (platform) ID where this template should be create in -- **image_type** (String) Image type linux, windows or other -- **name** (String) Name of the rescue disk -- **url** (String) URL where to download media from +- `boot_type` (String) Boot type of image bios or uefi +- `drivers` (List of String) +- `gid` (Number) grid (platform) ID where this template should be create in +- `name` (String) Name of the rescue disk +- `type` (String) Image type linux, windows or other +- `url` (String) URL where to download media from ### Optional -- **account_id** (Number) AccountId to make the image exclusive -- **architecture** (String) binary architecture of this image, one of X86_64 of PPC64_LE -- **bootable** (Boolean) Does this image boot OS -- **computeci_id** (Number) -- **enabled** (Boolean) -- **enabled_stacks** (List of String) -- **hot_resize** (Boolean) Does this machine supports hot resize -- **id** (String) The ID of this resource. -- **image_id** (Number) image id -- **password** (String) Optional password for the image -- **password_dl** (String) password for upload binary media -- **permanently** (Boolean) Whether to completely delete the image -- **pool_name** (String) pool for image create -- **reason** (String) -- **sep_id** (Number) storage endpoint provider ID -- **shared_with** (List of Number) -- **sync** (Boolean) Create image from a media identified by URL (in synchronous mode) -- **timeouts** (Block, Optional) (see [below for nested schema](#nestedblock--timeouts)) -- **username** (String) Optional username for the image -- **username_dl** (String) username for upload binary media +- `account_id` (Number) AccountId to make the image exclusive +- `architecture` (String) binary architecture of this image, one of X86_64 of PPC64_LE +- `hot_resize` (Boolean) Does this machine supports hot resize +- `image_id` (Number) image id +- `password` (String) Optional password for the image +- `password_dl` (String) password for upload binary media +- `permanently` (Boolean) whether to completely delete the image +- `pool_name` (String) pool for image create +- `sep_id` (Number) storage endpoint provider ID +- `timeouts` (Block, Optional) (see [below for nested schema](#nestedblock--timeouts)) +- `username` (String) Optional username for the image +- `username_dl` (String) username for upload binary media ### Read-Only -- **desc** (String) -- **guid** (Number) -- **history** (List of Object) (see [below for nested schema](#nestedatt--history)) -- **last_modified** (Number) -- **link_to** (Number) -- **meta** (List of String) meta -- **milestones** (Number) -- **provider_name** (String) -- **purge_attempts** (Number) -- **reference_id** (String) -- **res_id** (String) -- **res_name** (String) -- **rescuecd** (Boolean) -- **size** (Number) image size -- **status** (String) status -- **tech_status** (String) tech atatus -- **unc_path** (String) unc path -- **version** (String) version +- `acl` (String) +- `bootable` (Boolean) +- `ckey` (String) +- `compute_ci_id` (Number) +- `deleted_time` (String) +- `desc` (String) +- `enabled` (Boolean) +- `guid` (Number) +- `history` (List of Object) (see [below for nested schema](#nestedatt--history)) +- `id` (String) The ID of this resource. +- `image_name` (String) +- `last_modified` (Number) +- `link_to` (Number) +- `milestones` (Number) +- `provider_name` (String) +- `purge_attempts` (Number) +- `res_id` (String) +- `rescuecd` (Boolean) +- `shared_with` (List of Number) +- `size` (Number) +- `status` (String) +- `tech_status` (String) +- `unc_path` (String) +- `version` (String) ### Nested Schema for `timeouts` Optional: -- **create** (String) -- **default** (String) -- **delete** (String) -- **read** (String) -- **update** (String) +- `create` (String) +- `default` (String) +- `delete` (String) +- `read` (String) +- `update` (String) @@ -85,8 +83,8 @@ Optional: Read-Only: -- **guid** (String) -- **id** (Number) -- **timestamp** (Number) +- `guid` (String) +- `id` (Number) +- `timestamp` (Number) diff --git a/docs/resources/kubernetes.md b/docs/resources/kubernetes.md index 80c7863..624aa15 100644 --- a/docs/resources/kubernetes.md +++ b/docs/resources/kubernetes.md @@ -1,6 +1,6 @@ --- # generated by https://github.com/hashicorp/terraform-plugin-docs -page_title: "decort_k8s Resource - terraform-provider-decort" +page_title: "decort_k8s Resource - decort" subcategory: "" description: |- @@ -17,34 +17,34 @@ description: |- ### Required -- **k8sci_id** (Number) ID of the k8s catalog item to base this instance on. -- **name** (String) Name of the cluster. -- **rg_id** (Number) Resource group ID that this instance belongs to. -- **wg_name** (String) Name for first worker group created with cluster. +- `k8sci_id` (Number) ID of the k8s catalog item to base this instance on. +- `name` (String) Name of the cluster. +- `rg_id` (Number) Resource group ID that this instance belongs to. +- `wg_name` (String) Name for first worker group created with cluster. ### Optional -- **extnet_id** (Number) ID of the external network to connect workers to. If omitted network will be chosen by the platfom. -- **id** (String) The ID of this resource. -- **masters** (Block List, Max: 1) Master node(s) configuration. (see [below for nested schema](#nestedblock--masters)) -- **timeouts** (Block, Optional) (see [below for nested schema](#nestedblock--timeouts)) -- **workers** (Block List, Max: 1) Worker node(s) configuration. (see [below for nested schema](#nestedblock--workers)) +- `extnet_id` (Number) ID of the external network to connect workers to. If omitted network will be chosen by the platfom. +- `masters` (Block List, Max: 1) Master node(s) configuration. (see [below for nested schema](#nestedblock--masters)) +- `timeouts` (Block, Optional) (see [below for nested schema](#nestedblock--timeouts)) +- `workers` (Block List, Max: 1) Worker node(s) configuration. (see [below for nested schema](#nestedblock--workers)) ### Read-Only -- **default_wg_id** (Number) ID of default workers group for this instace. -- **kubeconfig** (String) Kubeconfig for cluster access. -- **lb_ip** (String) IP address of default load balancer. +- `default_wg_id` (Number) ID of default workers group for this instace. +- `id` (String) The ID of this resource. +- `kubeconfig` (String) Kubeconfig for cluster access. +- `lb_ip` (String) IP address of default load balancer. ### Nested Schema for `masters` Required: -- **cpu** (Number) Node CPU count. -- **disk** (Number) Node boot disk size in GB. -- **num** (Number) Number of nodes to create. -- **ram** (Number) Node RAM in MB. +- `cpu` (Number) Node CPU count. +- `disk` (Number) Node boot disk size in GB. +- `num` (Number) Number of nodes to create. +- `ram` (Number) Node RAM in MB. @@ -52,11 +52,11 @@ Required: Optional: -- **create** (String) -- **default** (String) -- **delete** (String) -- **read** (String) -- **update** (String) +- `create` (String) +- `default` (String) +- `delete` (String) +- `read` (String) +- `update` (String) @@ -64,9 +64,9 @@ Optional: Required: -- **cpu** (Number) Node CPU count. -- **disk** (Number) Node boot disk size in GB. -- **num** (Number) Number of nodes to create. -- **ram** (Number) Node RAM in MB. +- `cpu` (Number) Node CPU count. +- `disk` (Number) Node boot disk size in GB. +- `num` (Number) Number of nodes to create. +- `ram` (Number) Node RAM in MB. diff --git a/docs/resources/kubernetes_wg.md b/docs/resources/kubernetes_wg.md index d711efc..9fe6bf9 100644 --- a/docs/resources/kubernetes_wg.md +++ b/docs/resources/kubernetes_wg.md @@ -1,6 +1,6 @@ --- # generated by https://github.com/hashicorp/terraform-plugin-docs -page_title: "decort_k8s_wg Resource - terraform-provider-decort" +page_title: "decort_k8s_wg Resource - decort" subcategory: "" description: |- @@ -17,27 +17,30 @@ description: |- ### Required -- **k8s_id** (Number) ID of k8s instance. -- **name** (String) Name of the worker group. +- `k8s_id` (Number) ID of k8s instance. +- `name` (String) Name of the worker group. ### Optional -- **cpu** (Number) Worker node CPU count. -- **disk** (Number) Worker node boot disk size. If unspecified or 0, size is defined by OS image size. -- **id** (String) The ID of this resource. -- **num** (Number) Number of worker nodes to create. -- **ram** (Number) Worker node RAM in MB. -- **timeouts** (Block, Optional) (see [below for nested schema](#nestedblock--timeouts)) +- `cpu` (Number) Worker node CPU count. +- `disk` (Number) Worker node boot disk size. If unspecified or 0, size is defined by OS image size. +- `num` (Number) Number of worker nodes to create. +- `ram` (Number) Worker node RAM in MB. +- `timeouts` (Block, Optional) (see [below for nested schema](#nestedblock--timeouts)) + +### Read-Only + +- `id` (String) The ID of this resource. ### Nested Schema for `timeouts` Optional: -- **create** (String) -- **default** (String) -- **delete** (String) -- **read** (String) -- **update** (String) +- `create` (String) +- `default` (String) +- `delete` (String) +- `read` (String) +- `update` (String) diff --git a/docs/resources/kvmvm.md b/docs/resources/kvmvm.md index 2e00521..932c7f0 100644 --- a/docs/resources/kvmvm.md +++ b/docs/resources/kvmvm.md @@ -1,6 +1,6 @@ --- # generated by https://github.com/hashicorp/terraform-plugin-docs -page_title: "decort_kvmvm Resource - terraform-provider-decort" +page_title: "decort_kvmvm Resource - decort" subcategory: "" description: |- @@ -17,47 +17,49 @@ description: |- ### Required -- **boot_disk_size** (Number) This compute instance boot disk size in GB. Make sure it is large enough to accomodate selected OS image. -- **cpu** (Number) Number of CPUs to allocate to this compute instance. -- **driver** (String) Hardware architecture of this compute instance. -- **image_id** (Number) ID of the OS image to base this compute instance on. -- **name** (String) Name of this compute. Compute names are case sensitive and must be unique in the resource group. -- **ram** (Number) Amount of RAM in MB to allocate to this compute instance. -- **rg_id** (Number) ID of the resource group where this compute should be deployed. +- `boot_disk_size` (Number) This compute instance boot disk size in GB. Make sure it is large enough to accomodate selected OS image. +- `cpu` (Number) Number of CPUs to allocate to this compute instance. +- `driver` (String) Hardware architecture of this compute instance. +- `image_id` (Number) ID of the OS image to base this compute instance on. +- `name` (String) Name of this compute. Compute names are case sensitive and must be unique in the resource group. +- `ram` (Number) Amount of RAM in MB to allocate to this compute instance. +- `rg_id` (Number) ID of the resource group where this compute should be deployed. ### Optional -- **cloud_init** (String) Optional cloud_init parameters. Applied when creating new compute instance only, ignored in all other cases. -- **description** (String) Optional text description of this compute instance. -- **extra_disks** (Set of Number) Optional list of IDs of extra disks to attach to this compute. You may specify several extra disks. -- **id** (String) The ID of this resource. -- **network** (Block Set, Max: 8) Optional network connection(s) for this compute. You may specify several network blocks, one for each connection. (see [below for nested schema](#nestedblock--network)) -- **started** (Boolean) Is compute started. -- **timeouts** (Block, Optional) (see [below for nested schema](#nestedblock--timeouts)) +- `cloud_init` (String) Optional cloud_init parameters. Applied when creating new compute instance only, ignored in all other cases. +- `description` (String) Optional text description of this compute instance. +- `extra_disks` (Set of Number) Optional list of IDs of extra disks to attach to this compute. You may specify several extra disks. +- `network` (Block Set, Max: 8) Optional network connection(s) for this compute. You may specify several network blocks, one for each connection. (see [below for nested schema](#nestedblock--network)) +- `pool` (String) Pool to use if sepId is set, can be also empty if needed to be chosen by system. +- `sep_id` (Number) ID of SEP to create bootDisk on. Uses image's sepId if not set. +- `started` (Boolean) Is compute started. +- `timeouts` (Block, Optional) (see [below for nested schema](#nestedblock--timeouts)) ### Read-Only -- **account_id** (Number) ID of the account this compute instance belongs to. -- **account_name** (String) Name of the account this compute instance belongs to. -- **boot_disk_id** (Number) This compute instance boot disk ID. -- **os_users** (List of Object) Guest OS users provisioned on this compute instance. (see [below for nested schema](#nestedatt--os_users)) -- **rg_name** (String) Name of the resource group where this compute instance is located. +- `account_id` (Number) ID of the account this compute instance belongs to. +- `account_name` (String) Name of the account this compute instance belongs to. +- `boot_disk_id` (Number) This compute instance boot disk ID. +- `id` (String) The ID of this resource. +- `os_users` (List of Object) Guest OS users provisioned on this compute instance. (see [below for nested schema](#nestedatt--os_users)) +- `rg_name` (String) Name of the resource group where this compute instance is located. ### Nested Schema for `network` Required: -- **net_id** (Number) ID of the network for this connection. -- **net_type** (String) Type of the network for this connection, either EXTNET or VINS. +- `net_id` (Number) ID of the network for this connection. +- `net_type` (String) Type of the network for this connection, either EXTNET or VINS. Optional: -- **ip_address** (String) Optional IP address to assign to this connection. This IP should belong to the selected network and free for use. +- `ip_address` (String) Optional IP address to assign to this connection. This IP should belong to the selected network and free for use. Read-Only: -- **mac** (String) MAC address associated with this connection. MAC address is assigned automatically. +- `mac` (String) MAC address associated with this connection. MAC address is assigned automatically. @@ -65,11 +67,11 @@ Read-Only: Optional: -- **create** (String) -- **default** (String) -- **delete** (String) -- **read** (String) -- **update** (String) +- `create` (String) +- `default` (String) +- `delete` (String) +- `read` (String) +- `update` (String) @@ -77,9 +79,9 @@ Optional: Read-Only: -- **guid** (String) -- **login** (String) -- **password** (String) -- **public_key** (String) +- `guid` (String) +- `login` (String) +- `password` (String) +- `public_key` (String) diff --git a/docs/resources/pcidevice.md b/docs/resources/pcidevice.md index a4e3f86..55db726 100644 --- a/docs/resources/pcidevice.md +++ b/docs/resources/pcidevice.md @@ -1,6 +1,6 @@ --- # generated by https://github.com/hashicorp/terraform-plugin-docs -page_title: "decort_pcidevice Resource - terraform-provider-decort" +page_title: "decort_pcidevice Resource - decort" subcategory: "" description: |- @@ -17,38 +17,38 @@ description: |- ### Required -- **hw_path** (String) PCI address of the device -- **name** (String) Name of Device -- **rg_id** (Number) Resource GROUP -- **stack_id** (Number) stackId +- `hw_path` (String) PCI address of the device +- `name` (String) Name of Device +- `rg_id` (Number) Resource GROUP +- `stack_id` (Number) stackId ### Optional -- **description** (String) description, just for information -- **device_id** (Number) -- **enable** (Boolean) Enable pci device -- **force** (Boolean) Force delete -- **id** (String) The ID of this resource. -- **timeouts** (Block, Optional) (see [below for nested schema](#nestedblock--timeouts)) +- `description` (String) description, just for information +- `device_id` (Number) +- `enable` (Boolean) Enable pci device +- `force` (Boolean) Force delete +- `timeouts` (Block, Optional) (see [below for nested schema](#nestedblock--timeouts)) ### Read-Only -- **ckey** (String) -- **compute_id** (Number) -- **guid** (Number) -- **meta** (List of String) -- **status** (String) -- **system_name** (String) +- `ckey` (String) +- `compute_id` (Number) +- `guid` (Number) +- `id` (String) The ID of this resource. +- `meta` (List of String) +- `status` (String) +- `system_name` (String) ### Nested Schema for `timeouts` Optional: -- **create** (String) -- **default** (String) -- **delete** (String) -- **read** (String) -- **update** (String) +- `create` (String) +- `default` (String) +- `delete` (String) +- `read` (String) +- `update` (String) diff --git a/docs/resources/pfw.md b/docs/resources/pfw.md index c09c5c5..c9e3223 100644 --- a/docs/resources/pfw.md +++ b/docs/resources/pfw.md @@ -1,6 +1,6 @@ --- # generated by https://github.com/hashicorp/terraform-plugin-docs -page_title: "decort_pfw Resource - terraform-provider-decort" +page_title: "decort_pfw Resource - decort" subcategory: "" description: |- @@ -17,30 +17,30 @@ description: |- ### Required -- **compute_id** (Number) ID of compute instance. -- **local_base_port** (Number) Internal base port number. -- **proto** (String) Network protocol, either 'tcp' or 'udp'. -- **public_port_start** (Number) External start port number for the rule. +- `compute_id` (Number) ID of compute instance. +- `local_base_port` (Number) Internal base port number. +- `proto` (String) Network protocol, either 'tcp' or 'udp'. +- `public_port_start` (Number) External start port number for the rule. ### Optional -- **id** (String) The ID of this resource. -- **public_port_end** (Number) End port number (inclusive) for the ranged rule. -- **timeouts** (Block, Optional) (see [below for nested schema](#nestedblock--timeouts)) +- `public_port_end` (Number) End port number (inclusive) for the ranged rule. +- `timeouts` (Block, Optional) (see [below for nested schema](#nestedblock--timeouts)) ### Read-Only -- **local_ip** (String) IP address of compute instance. +- `id` (String) The ID of this resource. +- `local_ip` (String) IP address of compute instance. ### Nested Schema for `timeouts` Optional: -- **create** (String) -- **default** (String) -- **delete** (String) -- **read** (String) -- **update** (String) +- `create` (String) +- `default` (String) +- `delete` (String) +- `read` (String) +- `update` (String) diff --git a/docs/resources/resgroup.md b/docs/resources/resgroup.md index 73e0cc4..45d18b6 100644 --- a/docs/resources/resgroup.md +++ b/docs/resources/resgroup.md @@ -1,6 +1,6 @@ --- # generated by https://github.com/hashicorp/terraform-plugin-docs -page_title: "decort_resgroup Resource - terraform-provider-decort" +page_title: "decort_resgroup Resource - decort" subcategory: "" description: |- @@ -17,36 +17,36 @@ description: |- ### Required -- **account_id** (Number) Unique ID of the account, which this resource group belongs to. -- **name** (String) Name of this resource group. Names are case sensitive and unique within the context of a account. +- `account_id` (Number) Unique ID of the account, which this resource group belongs to. +- `name` (String) Name of this resource group. Names are case sensitive and unique within the context of a account. ### Optional -- **def_net_type** (String) Type of the network, which this resource group will use as default for its computes - PRIVATE or PUBLIC or NONE. -- **description** (String) User-defined text description of this resource group. -- **ext_ip** (String) IP address on the external netowrk to request when def_net_type=PRIVATE and ext_net_id is not 0 -- **ext_net_id** (Number) ID of the external network for default ViNS. Pass 0 if def_net_type=PUBLIC or no external connection required for the defult ViNS when def_net_type=PRIVATE -- **id** (String) The ID of this resource. -- **ipcidr** (String) Address of the netowrk inside the private network segment (aka ViNS) if def_net_type=PRIVATE -- **quota** (Block List, Max: 1) Quota settings for this resource group. (see [below for nested schema](#nestedblock--quota)) -- **timeouts** (Block, Optional) (see [below for nested schema](#nestedblock--timeouts)) +- `def_net_type` (String) Type of the network, which this resource group will use as default for its computes - PRIVATE or PUBLIC or NONE. +- `description` (String) User-defined text description of this resource group. +- `ext_ip` (String) IP address on the external netowrk to request when def_net_type=PRIVATE and ext_net_id is not 0 +- `ext_net_id` (Number) ID of the external network for default ViNS. Pass 0 if def_net_type=PUBLIC or no external connection required for the defult ViNS when def_net_type=PRIVATE +- `ipcidr` (String) Address of the netowrk inside the private network segment (aka ViNS) if def_net_type=PRIVATE +- `quota` (Block List, Max: 1) Quota settings for this resource group. (see [below for nested schema](#nestedblock--quota)) +- `timeouts` (Block, Optional) (see [below for nested schema](#nestedblock--timeouts)) ### Read-Only -- **account_name** (String) Name of the account, which this resource group belongs to. -- **def_net_id** (Number) ID of the default network for this resource group (if any). +- `account_name` (String) Name of the account, which this resource group belongs to. +- `def_net_id` (Number) ID of the default network for this resource group (if any). +- `id` (String) The ID of this resource. ### Nested Schema for `quota` Optional: -- **cpu** (Number) Limit on the total number of CPUs in this resource group. -- **disk** (Number) Limit on the total volume of storage resources in this resource group, specified in GB. -- **ext_ips** (Number) Limit on the total number of external IP addresses this resource group can use. -- **ext_traffic** (Number) Limit on the total ingress network traffic for this resource group, specified in GB. -- **gpu_units** (Number) Limit on the total number of virtual GPUs this resource group can use. -- **ram** (Number) Limit on the total amount of RAM in this resource group, specified in MB. +- `cpu` (Number) Limit on the total number of CPUs in this resource group. +- `disk` (Number) Limit on the total volume of storage resources in this resource group, specified in GB. +- `ext_ips` (Number) Limit on the total number of external IP addresses this resource group can use. +- `ext_traffic` (Number) Limit on the total ingress network traffic for this resource group, specified in GB. +- `gpu_units` (Number) Limit on the total number of virtual GPUs this resource group can use. +- `ram` (Number) Limit on the total amount of RAM in this resource group, specified in MB. @@ -54,10 +54,10 @@ Optional: Optional: -- **create** (String) -- **default** (String) -- **delete** (String) -- **read** (String) -- **update** (String) +- `create` (String) +- `default` (String) +- `delete` (String) +- `read` (String) +- `update` (String) diff --git a/docs/resources/sep.md b/docs/resources/sep.md index 7180b28..d566232 100644 --- a/docs/resources/sep.md +++ b/docs/resources/sep.md @@ -1,6 +1,6 @@ --- # generated by https://github.com/hashicorp/terraform-plugin-docs -page_title: "decort_sep Resource - terraform-provider-decort" +page_title: "decort_sep Resource - decort" subcategory: "" description: |- @@ -17,42 +17,42 @@ description: |- ### Required -- **gid** (Number) grid (platform) ID -- **name** (String) SEP name -- **type** (String) type of storage +- `gid` (Number) grid (platform) ID +- `name` (String) SEP name +- `type` (String) type of storage ### Optional -- **clear_physically** (Boolean) clear disks and images physically -- **config** (String) sep config string -- **consumed_by** (List of Number) list of consumer nodes IDs -- **decommission** (Boolean) unlink everything that exists from SEP -- **desc** (String) sep description -- **enable** (Boolean) enable SEP after creation -- **field_edit** (Block List, Max: 1) (see [below for nested schema](#nestedblock--field_edit)) -- **id** (String) The ID of this resource. -- **provided_by** (List of Number) list of provider nodes IDs -- **sep_id** (Number) sep type des id -- **timeouts** (Block, Optional) (see [below for nested schema](#nestedblock--timeouts)) -- **upd_capacity_limit** (Boolean) Update SEP capacity limit +- `clear_physically` (Boolean) clear disks and images physically +- `config` (String) sep config string +- `consumed_by` (List of Number) list of consumer nodes IDs +- `decommission` (Boolean) unlink everything that exists from SEP +- `desc` (String) sep description +- `enable` (Boolean) enable SEP after creation +- `field_edit` (Block List, Max: 1) (see [below for nested schema](#nestedblock--field_edit)) +- `provided_by` (List of Number) list of provider nodes IDs +- `sep_id` (Number) sep type des id +- `timeouts` (Block, Optional) (see [below for nested schema](#nestedblock--timeouts)) +- `upd_capacity_limit` (Boolean) Update SEP capacity limit ### Read-Only -- **ckey** (String) -- **guid** (Number) -- **meta** (List of String) -- **milestones** (Number) -- **obj_status** (String) -- **tech_status** (String) +- `ckey` (String) +- `guid` (Number) +- `id` (String) The ID of this resource. +- `meta` (List of String) +- `milestones` (Number) +- `obj_status` (String) +- `tech_status` (String) ### Nested Schema for `field_edit` Required: -- **field_name** (String) -- **field_type** (String) -- **field_value** (String) +- `field_name` (String) +- `field_type` (String) +- `field_value` (String) @@ -60,10 +60,10 @@ Required: Optional: -- **create** (String) -- **default** (String) -- **delete** (String) -- **read** (String) -- **update** (String) +- `create` (String) +- `default` (String) +- `delete` (String) +- `read` (String) +- `update` (String) diff --git a/docs/resources/sep_config.md b/docs/resources/sep_config.md index 32ec3ca..0bbbad7 100644 --- a/docs/resources/sep_config.md +++ b/docs/resources/sep_config.md @@ -1,6 +1,6 @@ --- # generated by https://github.com/hashicorp/terraform-plugin-docs -page_title: "decort_sep_config Resource - terraform-provider-decort" +page_title: "decort_sep_config Resource - decort" subcategory: "" description: |- @@ -17,23 +17,26 @@ description: |- ### Required -- **sep_id** (Number) +- `sep_id` (Number) ### Optional -- **config** (String) -- **field_edit** (Block List, Max: 1) (see [below for nested schema](#nestedblock--field_edit)) -- **id** (String) The ID of this resource. -- **timeouts** (Block, Optional) (see [below for nested schema](#nestedblock--timeouts)) +- `config` (String) +- `field_edit` (Block List, Max: 1) (see [below for nested schema](#nestedblock--field_edit)) +- `timeouts` (Block, Optional) (see [below for nested schema](#nestedblock--timeouts)) + +### Read-Only + +- `id` (String) The ID of this resource. ### Nested Schema for `field_edit` Required: -- **field_name** (String) -- **field_type** (String) -- **field_value** (String) +- `field_name` (String) +- `field_type` (String) +- `field_value` (String) @@ -41,10 +44,10 @@ Required: Optional: -- **create** (String) -- **default** (String) -- **delete** (String) -- **read** (String) -- **update** (String) +- `create` (String) +- `default` (String) +- `delete` (String) +- `read` (String) +- `update` (String) diff --git a/docs/resources/snapshot.md b/docs/resources/snapshot.md index f8a426c..8c4797f 100644 --- a/docs/resources/snapshot.md +++ b/docs/resources/snapshot.md @@ -1,6 +1,6 @@ --- # generated by https://github.com/hashicorp/terraform-plugin-docs -page_title: "decort_snapshot Resource - terraform-provider-decort" +page_title: "decort_snapshot Resource - decort" subcategory: "" description: |- @@ -17,30 +17,30 @@ description: |- ### Required -- **compute_id** (Number) ID of the compute instance to create snapshot for. -- **label** (String) text label for snapshot. Must be unique among this compute snapshots. +- `compute_id` (Number) ID of the compute instance to create snapshot for. +- `label` (String) text label for snapshot. Must be unique among this compute snapshots. ### Optional -- **id** (String) The ID of this resource. -- **rollback** (Boolean) is rollback the snapshot -- **timeouts** (Block, Optional) (see [below for nested schema](#nestedblock--timeouts)) +- `rollback` (Boolean) is rollback the snapshot +- `timeouts` (Block, Optional) (see [below for nested schema](#nestedblock--timeouts)) ### Read-Only -- **disks** (List of Number) -- **guid** (String) guid of the snapshot -- **timestamp** (Number) timestamp +- `disks` (List of Number) +- `guid` (String) guid of the snapshot +- `id` (String) The ID of this resource. +- `timestamp` (Number) timestamp ### Nested Schema for `timeouts` Optional: -- **create** (String) -- **default** (String) -- **delete** (String) -- **read** (String) -- **update** (String) +- `create` (String) +- `default` (String) +- `delete` (String) +- `read` (String) +- `update` (String) diff --git a/docs/resources/vins.md b/docs/resources/vins.md index 8f794b8..e1a568d 100644 --- a/docs/resources/vins.md +++ b/docs/resources/vins.md @@ -1,6 +1,6 @@ --- # generated by https://github.com/hashicorp/terraform-plugin-docs -page_title: "decort_vins Resource - terraform-provider-decort" +page_title: "decort_vins Resource - decort" subcategory: "" description: |- @@ -17,32 +17,32 @@ description: |- ### Required -- **account_id** (Number) ID of the account, which this ViNS belongs to. For ViNS created at account level, resource group ID is 0. -- **ext_net_id** (Number) ID of the external network this ViNS is connected to. Pass 0 if no external connection required. -- **name** (String) Name of the ViNS. Names are case sensitive and unique within the context of an account or resource group. +- `account_id` (Number) ID of the account, which this ViNS belongs to. For ViNS created at account level, resource group ID is 0. +- `ext_net_id` (Number) ID of the external network this ViNS is connected to. Pass 0 if no external connection required. +- `name` (String) Name of the ViNS. Names are case sensitive and unique within the context of an account or resource group. ### Optional -- **description** (String) Optional user-defined text description of this ViNS. -- **id** (String) The ID of this resource. -- **ipcidr** (String) Network address to use by this ViNS. This parameter is only valid when creating new ViNS. -- **rg_id** (Number) ID of the resource group, where this ViNS belongs to. Non-zero for ViNS created at resource group level, 0 otherwise. -- **timeouts** (Block, Optional) (see [below for nested schema](#nestedblock--timeouts)) +- `description` (String) Optional user-defined text description of this ViNS. +- `ipcidr` (String) Network address to use by this ViNS. This parameter is only valid when creating new ViNS. +- `rg_id` (Number) ID of the resource group, where this ViNS belongs to. Non-zero for ViNS created at resource group level, 0 otherwise. +- `timeouts` (Block, Optional) (see [below for nested schema](#nestedblock--timeouts)) ### Read-Only -- **account_name** (String) Name of the account, which this ViNS belongs to. -- **ext_ip_addr** (String) IP address of the external connection (valid for ViNS connected to external network, ignored otherwise). +- `account_name` (String) Name of the account, which this ViNS belongs to. +- `ext_ip_addr` (String) IP address of the external connection (valid for ViNS connected to external network, ignored otherwise). +- `id` (String) The ID of this resource. ### Nested Schema for `timeouts` Optional: -- **create** (String) -- **default** (String) -- **delete** (String) -- **read** (String) -- **update** (String) +- `create` (String) +- `default` (String) +- `delete` (String) +- `read` (String) +- `update` (String) diff --git a/docs/resources/virtual_image.md b/docs/resources/virtual_image.md index 1604064..1492684 100644 --- a/docs/resources/virtual_image.md +++ b/docs/resources/virtual_image.md @@ -1,6 +1,6 @@ --- # generated by https://github.com/hashicorp/terraform-plugin-docs -page_title: "decort_virtual_image Resource - terraform-provider-decort" +page_title: "decort_virtual_image Resource - decort" subcategory: "" description: |- @@ -17,67 +17,67 @@ description: |- ### Required -- **name** (String) name of the virtual image to create -- **target_id** (Number) ID of real image to link this virtual image to upon creation +- `name` (String) name of the virtual image to create +- `target_id` (Number) ID of real image to link this virtual image to upon creation ### Optional -- **account_id** (Number) AccountId to make the image exclusive -- **architecture** (String) binary architecture of this image, one of X86_64 of PPC64_LE -- **bootable** (Boolean) Does this image boot OS -- **computeci_id** (Number) -- **enabled** (Boolean) -- **enabled_stacks** (List of String) -- **hot_resize** (Boolean) Does this machine supports hot resize -- **id** (String) The ID of this resource. -- **link_to** (Number) -- **password** (String) Optional password for the image -- **password_dl** (String) password for upload binary media -- **permanently** (Boolean) Whether to completely delete the image -- **pool_name** (String) pool for image create -- **reason** (String) -- **sep_id** (Number) storage endpoint provider ID -- **shared_with** (List of Number) -- **timeouts** (Block, Optional) (see [below for nested schema](#nestedblock--timeouts)) -- **username** (String) Optional username for the image -- **username_dl** (String) username for upload binary media +- `account_id` (Number) AccountId to make the image exclusive +- `architecture` (String) binary architecture of this image, one of X86_64 of PPC64_LE +- `bootable` (Boolean) Does this image boot OS +- `computeci_id` (Number) +- `enabled` (Boolean) +- `enabled_stacks` (List of String) +- `hot_resize` (Boolean) Does this machine supports hot resize +- `link_to` (Number) +- `password` (String) Optional password for the image +- `password_dl` (String) password for upload binary media +- `permanently` (Boolean) Whether to completely delete the image +- `pool_name` (String) pool for image create +- `reason` (String) +- `sep_id` (Number) storage endpoint provider ID +- `shared_with` (List of Number) +- `timeouts` (Block, Optional) (see [below for nested schema](#nestedblock--timeouts)) +- `username` (String) Optional username for the image +- `username_dl` (String) username for upload binary media ### Read-Only -- **boot_type** (String) Boot type of image bios or uefi -- **desc** (String) -- **drivers** (List of String) List of types of compute suitable for image. Example: [ "KVM_X86" ] -- **gid** (Number) grid (platform) ID where this template should be create in -- **guid** (Number) -- **history** (List of Object) (see [below for nested schema](#nestedatt--history)) -- **image_id** (Number) image id -- **image_type** (String) Image type linux, windows or other -- **last_modified** (Number) -- **meta** (List of String) meta -- **milestones** (Number) -- **provider_name** (String) -- **purge_attempts** (Number) -- **reference_id** (String) -- **res_id** (String) -- **res_name** (String) -- **rescuecd** (Boolean) -- **size** (Number) image size -- **status** (String) status -- **tech_status** (String) tech atatus -- **unc_path** (String) unc path -- **url** (String) URL where to download media from -- **version** (String) version +- `boot_type` (String) Boot type of image bios or uefi +- `desc` (String) +- `drivers` (List of String) List of types of compute suitable for image. Example: [ "KVM_X86" ] +- `gid` (Number) grid (platform) ID where this template should be create in +- `guid` (Number) +- `history` (List of Object) (see [below for nested schema](#nestedatt--history)) +- `id` (String) The ID of this resource. +- `image_id` (Number) image id +- `image_type` (String) Image type linux, windows or other +- `last_modified` (Number) +- `meta` (List of String) meta +- `milestones` (Number) +- `provider_name` (String) +- `purge_attempts` (Number) +- `reference_id` (String) +- `res_id` (String) +- `res_name` (String) +- `rescuecd` (Boolean) +- `size` (Number) image size +- `status` (String) status +- `tech_status` (String) tech atatus +- `unc_path` (String) unc path +- `url` (String) URL where to download media from +- `version` (String) version ### Nested Schema for `timeouts` Optional: -- **create** (String) -- **default** (String) -- **delete** (String) -- **read** (String) -- **update** (String) +- `create` (String) +- `default` (String) +- `delete` (String) +- `read` (String) +- `update` (String) @@ -85,8 +85,8 @@ Optional: Read-Only: -- **guid** (String) -- **id** (Number) -- **timestamp** (Number) +- `guid` (String) +- `id` (Number) +- `timestamp` (Number)