This commit is contained in:
KasimBaybikov
2023-05-04 10:08:25 +03:00
parent 9bad8a6947
commit 8ca233dd32
288 changed files with 6645 additions and 11464 deletions

View File

@@ -1,56 +0,0 @@
/*
Copyright (c) 2019-2022 Digital Energy Cloud Solutions LLC. All Rights Reserved.
Authors:
Petr Krutov, <petr.krutov@digitalenergy.online>
Stanislav Solovev, <spsolovev@digitalenergy.online>
Kasim Baybikov, <kmbaybikov@basistech.ru>
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://repository.basistech.ru/BASIS/terraform-provider-decort
Please see README.md to learn where to place source code so that it
builds seamlessly.
Documentation: https://repository.basistech.ru/BASIS/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"

View File

@@ -48,7 +48,7 @@ func dataSourceAccountRead(ctx context.Context, d *schema.ResourceData, m interf
}
flattenAccount(d, *acc)
d.SetId(strconv.Itoa(acc.ID))
d.SetId(strconv.Itoa(int(acc.ID)))
return nil
}
@@ -385,6 +385,14 @@ func dataSourceAccountSchemaMake() map[string]*schema.Schema {
Type: schema.TypeInt,
Computed: true,
},
"cpu_allocation_parameter": {
Type: schema.TypeString,
Computed: true,
},
"cpu_allocation_ratio": {
Type: schema.TypeFloat,
Computed: true,
},
}
return res
}

View File

@@ -38,10 +38,11 @@ import (
"github.com/google/uuid"
"github.com/hashicorp/terraform-plugin-sdk/v2/diag"
"github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema"
"repository.basistech.ru/BASIS/decort-golang-sdk/pkg/cloudapi/account"
"repository.basistech.ru/BASIS/terraform-provider-decort/internal/constants"
)
func flattenAccountAuditsList(aal AccountAuditsList) []map[string]interface{} {
func flattenAccountAuditsList(aal account.ListAudits) []map[string]interface{} {
res := make([]map[string]interface{}, 0)
for _, aa := range aal {
temp := map[string]interface{}{

View File

@@ -38,33 +38,34 @@ import (
"github.com/google/uuid"
"github.com/hashicorp/terraform-plugin-sdk/v2/diag"
"github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema"
"repository.basistech.ru/BASIS/decort-golang-sdk/pkg/cloudapi/account"
"repository.basistech.ru/BASIS/terraform-provider-decort/internal/constants"
)
func flattenAccountComputesList(acl AccountComputesList) []map[string]interface{} {
func flattenAccountComputesList(acl account.ListComputes) []map[string]interface{} {
res := make([]map[string]interface{}, 0)
for _, acc := range acl {
temp := map[string]interface{}{
"account_id": acc.AccountId,
"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_id": acc.ComputeID,
"compute_name": acc.ComputeName,
"ram": acc.RAM,
"registered": acc.Registered,
"rg_id": acc.RgId,
"rg_name": acc.RgName,
"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,
"vins_connected": acc.VINSConnected,
}
res = append(res, temp)
}

View File

@@ -54,7 +54,7 @@ func dataSourceAccountConsumedUnitsRead(ctx context.Context, d *schema.ResourceD
d.Set("cu_i", accountConsumedUnits.CUI)
d.Set("cu_m", accountConsumedUnits.CUM)
d.Set("cu_np", accountConsumedUnits.CUNP)
d.Set("gpu_units", accountConsumedUnits.GpuUnits)
d.Set("gpu_units", accountConsumedUnits.GPUUnits)
return nil
}

View File

@@ -37,17 +37,18 @@ import (
"github.com/google/uuid"
"github.com/hashicorp/terraform-plugin-sdk/v2/diag"
"github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema"
"repository.basistech.ru/BASIS/decort-golang-sdk/pkg/cloudapi/account"
"repository.basistech.ru/BASIS/terraform-provider-decort/internal/constants"
)
func flattenAccountDisksList(adl AccountDisksList) []map[string]interface{} {
func flattenAccountDisksList(adl account.ListDisks) []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": ad.Pool,
"sep_id": ad.SepId,
"sep_id": ad.SEPID,
"shareable": ad.Shareable,
"size_max": ad.SizeMax,
"type": ad.Type,

View File

@@ -38,14 +38,15 @@ import (
"github.com/google/uuid"
"github.com/hashicorp/terraform-plugin-sdk/v2/diag"
"github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema"
"repository.basistech.ru/BASIS/decort-golang-sdk/pkg/cloudapi/account"
"repository.basistech.ru/BASIS/terraform-provider-decort/internal/constants"
)
func flattenAccountFlipGroupsList(afgl AccountFlipGroupsList) []map[string]interface{} {
func flattenAccountFlipGroupsList(afgl account.ListFLIPGroups) []map[string]interface{} {
res := make([]map[string]interface{}, 0)
for _, afg := range afgl {
temp := map[string]interface{}{
"account_id": afg.AccountId,
"account_id": afg.AccountID,
"client_type": afg.ClientType,
"conn_type": afg.ConnType,
"created_by": afg.CreatedBy,
@@ -53,7 +54,7 @@ func flattenAccountFlipGroupsList(afgl AccountFlipGroupsList) []map[string]inter
"default_gw": afg.DefaultGW,
"deleted_by": afg.DeletedBy,
"deleted_time": afg.DeletedTime,
"desc": afg.Desc,
"desc": afg.Description,
"gid": afg.GID,
"guid": afg.GUID,
"fg_id": afg.ID,

View File

@@ -38,14 +38,15 @@ import (
"github.com/google/uuid"
"github.com/hashicorp/terraform-plugin-sdk/v2/diag"
"github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema"
"repository.basistech.ru/BASIS/decort-golang-sdk/pkg/cloudapi/account"
"repository.basistech.ru/BASIS/terraform-provider-decort/internal/constants"
)
func flattenAccountList(al AccountCloudApiList) []map[string]interface{} {
func flattenAccountList(al account.ListAccounts) []map[string]interface{} {
res := make([]map[string]interface{}, 0)
for _, acc := range al {
temp := map[string]interface{}{
"acl": flattenRgAcl(acc.Acl),
"acl": flattenRgAcl(acc.ACL),
"created_time": acc.CreatedTime,
"deleted_time": acc.DeletedTime,
"account_id": acc.ID,
@@ -58,12 +59,12 @@ func flattenAccountList(al AccountCloudApiList) []map[string]interface{} {
return res
}
func flattenRgAcl(rgAcls []AccountAclRecord) []map[string]interface{} {
func flattenRgAcl(rgAcls []account.RecordACL) []map[string]interface{} {
res := make([]map[string]interface{}, 0)
for _, rgAcl := range rgAcls {
temp := map[string]interface{}{
"explicit": rgAcl.IsExplicit,
"guid": rgAcl.Guid,
"guid": rgAcl.GUID,
"right": rgAcl.Rights,
"status": rgAcl.Status,
"type": rgAcl.Type,

View File

@@ -54,7 +54,7 @@ func dataSourceAccountReservedUnitsRead(ctx context.Context, d *schema.ResourceD
d.Set("cu_i", accountReservedUnits.CUI)
d.Set("cu_m", accountReservedUnits.CUM)
d.Set("cu_np", accountReservedUnits.CUNP)
d.Set("gpu_units", accountReservedUnits.GpuUnits)
d.Set("gpu_units", accountReservedUnits.GPUUnits)
return nil
}

View File

@@ -38,10 +38,11 @@ import (
"github.com/google/uuid"
"github.com/hashicorp/terraform-plugin-sdk/v2/diag"
"github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema"
"repository.basistech.ru/BASIS/decort-golang-sdk/pkg/cloudapi/account"
"repository.basistech.ru/BASIS/terraform-provider-decort/internal/constants"
)
func flattenAccountRGList(argl AccountRGList) []map[string]interface{} {
func flattenAccountRGList(argl account.ListRG) []map[string]interface{} {
res := make([]map[string]interface{}, 0)
for _, arg := range argl {
temp := map[string]interface{}{
@@ -57,7 +58,7 @@ func flattenAccountRGList(argl AccountRGList) []map[string]interface{} {
"status": arg.Status,
"updated_by": arg.UpdatedBy,
"updated_time": arg.UpdatedTime,
"vinses": arg.Vinses,
"vinses": arg.VINSes,
}
res = append(res, temp)
}
@@ -65,7 +66,7 @@ func flattenAccountRGList(argl AccountRGList) []map[string]interface{} {
}
func flattenAccRGComputes(argc AccountRGComputes) []map[string]interface{} {
func flattenAccRGComputes(argc account.RGComputes) []map[string]interface{} {
res := make([]map[string]interface{}, 0)
temp := map[string]interface{}{
"started": argc.Started,
@@ -75,13 +76,13 @@ func flattenAccRGComputes(argc AccountRGComputes) []map[string]interface{} {
return res
}
func flattenAccResourceHack(r ResourceHack) []map[string]interface{} {
func flattenAccResourceHack(r account.LimitsRG) []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,
"disksize": r.DiskSize,
"extips": r.ExtIPs,
"exttraffic": r.ExtTraffic,
"gpu": r.GPU,
"ram": r.RAM,
//"seps": flattenAccountSeps(r.SEPs),
@@ -90,13 +91,13 @@ func flattenAccResourceHack(r ResourceHack) []map[string]interface{} {
return res
}
func flattenAccResourceRg(r Resource) []map[string]interface{} {
func flattenAccResourceRg(r account.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,
"disksize": r.DiskSize,
"extips": r.ExtIPs,
"exttraffic": r.ExtTraffic,
"gpu": r.GPU,
"ram": r.RAM,
}
@@ -104,7 +105,7 @@ func flattenAccResourceRg(r Resource) []map[string]interface{} {
return res
}
func flattenAccRGResources(argr AccountRGResources) []map[string]interface{} {
func flattenAccRGResources(argr account.RGResources) []map[string]interface{} {
res := make([]map[string]interface{}, 0)
temp := map[string]interface{}{
"consumed": flattenAccResourceRg(argr.Consumed),

View File

@@ -38,16 +38,17 @@ import (
"github.com/google/uuid"
"github.com/hashicorp/terraform-plugin-sdk/v2/diag"
"github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema"
"repository.basistech.ru/BASIS/decort-golang-sdk/pkg/cloudapi/account"
"repository.basistech.ru/BASIS/terraform-provider-decort/internal/constants"
)
func flattenAccountTemplatesList(atl AccountTemplatesList) []map[string]interface{} {
func flattenAccountTemplatesList(atl account.ListTemplates) []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,
"account_id": at.AccountID,
"desc": at.Description,
"template_id": at.ID,
"template_name": at.Name,
"public": at.Public,

View File

@@ -38,14 +38,15 @@ import (
"github.com/google/uuid"
"github.com/hashicorp/terraform-plugin-sdk/v2/diag"
"github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema"
"repository.basistech.ru/BASIS/decort-golang-sdk/pkg/cloudapi/account"
"repository.basistech.ru/BASIS/terraform-provider-decort/internal/constants"
)
func flattenAccountVinsList(avl AccountVinsList) []map[string]interface{} {
func flattenAccountVinsList(avl account.ListVINS) []map[string]interface{} {
res := make([]map[string]interface{}, 0)
for _, av := range avl {
temp := map[string]interface{}{
"account_id": av.AccountId,
"account_id": av.AccountID,
"account_name": av.AccountName,
"computes": av.Computes,
"created_by": av.CreatedBy,
@@ -56,9 +57,9 @@ func flattenAccountVinsList(avl AccountVinsList) []map[string]interface{} {
"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,
"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,

View File

@@ -2,20 +2,19 @@ package account
import (
"github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema"
"repository.basistech.ru/BASIS/terraform-provider-decort/internal/flattens"
"repository.basistech.ru/BASIS/decort-golang-sdk/pkg/cloudapi/account"
)
func flattenAccount(d *schema.ResourceData, acc AccountWithResources) error {
func flattenAccount(d *schema.ResourceData, acc account.RecordAccount) error {
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("acl", flattenAccAcl(acc.ACL))
d.Set("company", acc.Company)
d.Set("companyurl", acc.CompanyUrl)
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("deactivation_time", acc.DeactivationTime)
d.Set("deleted_by", acc.DeletedBy)
d.Set("deleted_time", acc.DeletedTime)
d.Set("displayname", acc.DisplayName)
@@ -24,25 +23,26 @@ func flattenAccount(d *schema.ResourceData, acc AccountWithResources) error {
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("vins", acc.VINS)
d.Set("vinses", acc.VINSes)
d.Set("computes", flattenAccComputes(acc.Computes))
d.Set("machines", flattenAccMachines(acc.Machines))
d.Set("cpu_allocation_parameter", acc.CPUAllocationParameter)
d.Set("cpu_allocation_ratio", acc.CPUAllocationRatio)
if username, ok := d.GetOk("username"); ok {
d.Set("username", username)
} else {
d.Set("username", acc.Acl[0].UgroupID)
d.Set("username", acc.ACL[0].UgroupID)
}
return nil
}
func flattenAccComputes(acs Computes) []map[string]interface{} {
func flattenAccComputes(acs account.Computes) []map[string]interface{} {
res := make([]map[string]interface{}, 0)
temp := map[string]interface{}{
"started": acs.Started,
@@ -52,7 +52,7 @@ func flattenAccComputes(acs Computes) []map[string]interface{} {
return res
}
func flattenAccMachines(ams Machines) []map[string]interface{} {
func flattenAccMachines(ams account.Machines) []map[string]interface{} {
res := make([]map[string]interface{}, 0)
temp := map[string]interface{}{
"running": ams.Running,
@@ -62,13 +62,13 @@ func flattenAccMachines(ams Machines) []map[string]interface{} {
return res
}
func flattenAccAcl(acls []AccountAclRecord) []map[string]interface{} {
func flattenAccAcl(acls []account.RecordACL) []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,
"guid": acls.GUID,
"right": acls.Rights,
"status": acls.Status,
"type": acls.Type,
@@ -79,7 +79,7 @@ func flattenAccAcl(acls []AccountAclRecord) []map[string]interface{} {
return res
}
func flattenRgResourceLimits(rl ResourceLimits) []map[string]interface{} {
func flattenRgResourceLimits(rl account.ResourceLimits) []map[string]interface{} {
res := make([]map[string]interface{}, 0)
temp := map[string]interface{}{
"cu_c": rl.CUC,
@@ -87,7 +87,7 @@ func flattenRgResourceLimits(rl ResourceLimits) []map[string]interface{} {
"cu_i": rl.CUI,
"cu_m": rl.CUM,
"cu_np": rl.CUNP,
"gpu_units": rl.GpuUnits,
"gpu_units": rl.GPUUnits,
}
res = append(res, temp)
@@ -95,7 +95,7 @@ func flattenRgResourceLimits(rl ResourceLimits) []map[string]interface{} {
}
func flattenAccResources(r Resources) []map[string]interface{} {
func flattenAccResources(r account.Resources) []map[string]interface{} {
res := make([]map[string]interface{}, 0)
temp := map[string]interface{}{
"current": flattenAccResource(r.Current),
@@ -105,7 +105,7 @@ func flattenAccResources(r Resources) []map[string]interface{} {
return res
}
func flattenAccountSeps(seps map[string]map[string]ResourceSep) []map[string]interface{} {
func flattenAccountSeps(seps map[string]map[string]account.DiskUsage) []map[string]interface{} {
res := make([]map[string]interface{}, 0)
for sepKey, sepVal := range seps {
for dataKey, dataVal := range sepVal {
@@ -121,13 +121,13 @@ func flattenAccountSeps(seps map[string]map[string]ResourceSep) []map[string]int
return res
}
func flattenAccResource(r Resource) []map[string]interface{} {
func flattenAccResource(r account.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,
"disksize": r.DiskSize,
"extips": r.ExtIPs,
"exttraffic": r.ExtTraffic,
"gpu": r.GPU,
"ram": r.RAM,
"seps": flattenAccountSeps(r.SEPs),

View File

@@ -1,277 +0,0 @@
/*
Copyright (c) 2019-2022 Digital Energy Cloud Solutions LLC. All Rights Reserved.
Authors:
Petr Krutov, <petr.krutov@digitalenergy.online>
Stanislav Solovev, <spsolovev@digitalenergy.online>
Kasim Baybikov, <kmbaybikov@basistech.ru>
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://repository.basistech.ru/BASIS/terraform-provider-decort
Please see README.md to learn where to place source code so that it
builds seamlessly.
Documentation: https://repository.basistech.ru/BASIS/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 ResourceSep struct {
DiskSize float64 `json:"disksize"`
DiskSizeMax int `json:"disksizemax"`
}
type Resource struct {
CPU int `json:"cpu"`
Disksize float64 `json:"disksize"`
Extips int `json:"extips"`
Exttraffic int `json:"exttraffic"`
GPU int `json:"gpu"`
RAM int `json:"ram"`
SEPs map[string]map[string]ResourceSep `json:"seps"`
}
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"`
Shareable bool `json:"shareable"`
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 ResourceHack struct {
CPU int `json:"cpu"`
Disksize float64 `json:"disksize"`
Extips int `json:"extips"`
Exttraffic int `json:"exttraffic"`
GPU int `json:"gpu"`
RAM int `json:"ram"`
}
type AccountRGResources struct {
Consumed Resource `json:"Consumed"`
Limits ResourceHack `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

View File

@@ -34,13 +34,13 @@ 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"
log "github.com/sirupsen/logrus"
"repository.basistech.ru/BASIS/decort-golang-sdk/pkg/cloudapi/account"
"repository.basistech.ru/BASIS/terraform-provider-decort/internal/constants"
"repository.basistech.ru/BASIS/terraform-provider-decort/internal/controller"
"repository.basistech.ru/BASIS/terraform-provider-decort/internal/status"
@@ -50,99 +50,103 @@ func resourceAccountCreate(ctx context.Context, d *schema.ResourceData, m interf
log.Debugf("resourceAccountCreate")
c := m.(*controller.ControllerCfg)
urlValues := &url.Values{}
req := account.CreateRequest{}
urlValues.Add("name", d.Get("account_name").(string))
urlValues.Add("username", d.Get("username").(string))
req.Name = d.Get("account_name").(string)
req.Username = d.Get("username").(string)
if emailaddress, ok := d.GetOk("emailaddress"); ok {
urlValues.Add("emailaddress", emailaddress.(string))
req.EmailAddress = emailaddress.(string)
}
if sendAccessEmails, ok := d.GetOk("send_access_emails"); ok {
urlValues.Add("sendAccessEmails", strconv.FormatBool(sendAccessEmails.(bool)))
req.SendAccessEmails = 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))
req.MaxMemoryCapacity = -1
} else {
urlValues.Add("maxMemoryCapacity", strconv.Itoa(maxMemCap))
req.MaxMemoryCapacity = int64(maxMemCap)
}
}
if resLimitConv["cu_d"] != nil {
maxDiskCap := int(resLimitConv["cu_d"].(float64))
if maxDiskCap == 0 {
urlValues.Add("maxVDiskCapacity", strconv.Itoa(-1))
req.MaxVDiskCapacity = -1
} else {
urlValues.Add("maxVDiskCapacity", strconv.Itoa(maxDiskCap))
req.MaxVDiskCapacity = int64(maxDiskCap)
}
}
if resLimitConv["cu_c"] != nil {
maxCPUCap := int(resLimitConv["cu_c"].(float64))
if maxCPUCap == 0 {
urlValues.Add("maxCPUCapacity", strconv.Itoa(-1))
req.MaxCPUCapacity = -1
} else {
urlValues.Add("maxCPUCapacity", strconv.Itoa(maxCPUCap))
req.MaxCPUCapacity = int64(maxCPUCap)
}
}
if resLimitConv["cu_i"] != nil {
maxNumPublicIP := int(resLimitConv["cu_i"].(float64))
if maxNumPublicIP == 0 {
urlValues.Add("maxNumPublicIP", strconv.Itoa(-1))
req.MaxNumPublicIP = -1
} else {
urlValues.Add("maxNumPublicIP", strconv.Itoa(maxNumPublicIP))
req.MaxNumPublicIP = int64(maxNumPublicIP)
}
}
if resLimitConv["cu_np"] != nil {
maxNP := int(resLimitConv["cu_np"].(float64))
if maxNP == 0 {
urlValues.Add("maxNetworkPeerTransfer", strconv.Itoa(-1))
req.MaxNetworkPeerTransfer = -1
} else {
urlValues.Add("maxNetworkPeerTransfer", strconv.Itoa(maxNP))
req.MaxNetworkPeerTransfer = int64(maxNP)
}
}
if resLimitConv["gpu_units"] != nil {
gpuUnits := int(resLimitConv["gpu_units"].(float64))
if gpuUnits == 0 {
urlValues.Add("gpu_units", strconv.Itoa(-1))
req.GPUUnits = -1
} else {
urlValues.Add("gpu_units", strconv.Itoa(gpuUnits))
req.GPUUnits = int64(gpuUnits)
}
}
}
accountId, err := c.DecortAPICall(ctx, "POST", accountCreateAPI, urlValues)
accountId, err := c.CloudAPI().Account().Create(ctx, req)
if err != nil {
return diag.FromErr(err)
}
accIdParsed, _ := strconv.Atoi(accountId)
d.SetId(accountId)
d.Set("account_id", accIdParsed)
urlValues = &url.Values{}
d.SetId(strconv.FormatUint(accountId, 10))
d.Set("account_id", accountId)
if enable, ok := d.GetOk("enable"); ok {
api := accountDisableAPI
reqSwitch := account.DisableEnableRequest{
AccountID: accountId,
}
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)
}
_, err := c.CloudAPI().Account().Enable(ctx, reqSwitch)
if err != nil {
return diag.FromErr(err)
urlValues = &url.Values{}
} else {
_, err := c.CloudAPI().Account().Disable(ctx, reqSwitch)
if err != nil {
return diag.FromErr(err)
}
}
}
}
if users, ok := d.GetOk("users"); ok {
@@ -151,15 +155,16 @@ func resourceAccountCreate(ctx context.Context, d *schema.ResourceData, m interf
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)
req := account.AddUserRequest{
AccountID: accountId,
UserID: userConv["user_id"].(string),
AccessType: strings.ToUpper(userConv["access_type"].(string)),
}
_, err := c.CloudAPI().Account().AddUser(ctx, req)
if err != nil {
return diag.FromErr(err)
}
urlValues = &url.Values{}
}
}
}
@@ -187,10 +192,13 @@ func resourceAccountRead(ctx context.Context, d *schema.ResourceData, m interfac
case status.Destroying:
return diag.Errorf("The account is in progress with status: %s", acc.Status)
case status.Deleted:
urlValues := &url.Values{}
urlValues.Add("accountId", d.Id())
id, _ := strconv.ParseUint(d.Id(), 10, 64)
_, err := c.DecortAPICall(ctx, "POST", accountRestoreAPI, urlValues)
req := account.RestoreRequest{
AccountID: id,
}
_, err := c.CloudAPI().Account().Restore(ctx, req)
if err != nil {
return diag.FromErr(err)
}
@@ -216,41 +224,40 @@ 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(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)
_, err := utilityAccountCheckPresence(ctx, d, m)
if err != nil {
return diag.FromErr(err)
}
req := account.DeleteRequest{
AccountID: uint64(d.Get("account_id").(int)),
Permanently: d.Get("permanently").(bool),
}
_, err = c.CloudAPI().Account().Delete(ctx, req)
if err != nil {
return diag.FromErr(err)
}
d.SetId("")
return nil
}
func resourceAccountUpdate(ctx context.Context, d *schema.ResourceData, m interface{}) diag.Diagnostics {
log.Debugf("resourceAccountEdit")
log.Debugf("resourceAccountUpdate")
c := m.(*controller.ControllerCfg)
urlValues := &url.Values{}
acc, err := utilityAccountCheckPresence(ctx, d, m)
if err != nil {
d.SetId("")
return diag.FromErr(err)
}
accountId, _ := strconv.ParseUint(d.Id(), 10, 64)
hasChanged := false
switch acc.Status {
@@ -260,10 +267,12 @@ func resourceAccountUpdate(ctx context.Context, d *schema.ResourceData, m interf
case status.Destroying:
return diag.Errorf("The account is in progress with status: %s", acc.Status)
case status.Deleted:
urlVal := &url.Values{}
urlVal.Add("accountId", d.Id())
_, err := c.DecortAPICall(ctx, "POST", accountRestoreAPI, urlVal)
req := account.RestoreRequest{
AccountID: accountId,
}
_, err := c.CloudAPI().Account().Restore(ctx, req)
if err != nil {
return diag.FromErr(err)
}
@@ -283,31 +292,39 @@ func resourceAccountUpdate(ctx context.Context, d *schema.ResourceData, m interf
}
if d.HasChange("enable") {
api := accountDisableAPI
reqSwitch := account.DisableEnableRequest{
AccountID: accountId,
}
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)
}
_, err := c.CloudAPI().Account().Enable(ctx, reqSwitch)
if err != nil {
return diag.FromErr(err)
urlValues = &url.Values{}
} else {
_, err := c.CloudAPI().Account().Disable(ctx, reqSwitch)
if err != nil {
return diag.FromErr(err)
}
}
}
}
req := account.UpdateRequest{
AccountID: accountId,
}
updated := false
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{}
req.Name = d.Get("account_name").(string)
updated = true
}
if d.HasChange("resource_limits") {
resLimit := d.Get("resource_limits").([]interface{})[0]
resLimitConv := resLimit.(map[string]interface{})
@@ -315,85 +332,83 @@ func resourceAccountUpdate(ctx context.Context, d *schema.ResourceData, m interf
if resLimitConv["cu_m"] != nil {
maxMemCap := int(resLimitConv["cu_m"].(float64))
if maxMemCap == 0 {
urlValues.Add("maxMemoryCapacity", strconv.Itoa(-1))
req.MaxMemoryCapacity = -1
} else {
urlValues.Add("maxMemoryCapacity", strconv.Itoa(maxMemCap))
req.MaxMemoryCapacity = int64(maxMemCap)
}
updated = true
}
if resLimitConv["cu_d"] != nil {
maxDiskCap := int(resLimitConv["cu_d"].(float64))
if maxDiskCap == 0 {
urlValues.Add("maxVDiskCapacity", strconv.Itoa(-1))
req.MaxVDiskCapacity = -1
} else {
urlValues.Add("maxVDiskCapacity", strconv.Itoa(maxDiskCap))
req.MaxVDiskCapacity = int64(maxDiskCap)
}
updated = true
}
if resLimitConv["cu_c"] != nil {
maxCPUCap := int(resLimitConv["cu_c"].(float64))
if maxCPUCap == 0 {
urlValues.Add("maxCPUCapacity", strconv.Itoa(-1))
req.MaxCPUCapacity = -1
} else {
urlValues.Add("maxCPUCapacity", strconv.Itoa(maxCPUCap))
req.MaxCPUCapacity = int64(maxCPUCap)
}
updated = true
}
if resLimitConv["cu_i"] != nil {
maxNumPublicIP := int(resLimitConv["cu_i"].(float64))
if maxNumPublicIP == 0 {
urlValues.Add("maxNumPublicIP", strconv.Itoa(-1))
req.MaxNumPublicIP = -1
} else {
urlValues.Add("maxNumPublicIP", strconv.Itoa(maxNumPublicIP))
req.MaxNumPublicIP = int64(maxNumPublicIP)
}
updated = true
}
if resLimitConv["cu_np"] != nil {
maxNP := int(resLimitConv["cu_np"].(float64))
if maxNP == 0 {
urlValues.Add("maxNetworkPeerTransfer", strconv.Itoa(-1))
req.MaxNetworkPeerTransfer = -1
} else {
urlValues.Add("maxNetworkPeerTransfer", strconv.Itoa(maxNP))
req.MaxNetworkPeerTransfer = int64(maxNP)
}
updated = true
}
if resLimitConv["gpu_units"] != nil {
gpuUnits := int(resLimitConv["gpu_units"].(float64))
if gpuUnits == 0 {
urlValues.Add("gpu_units", strconv.Itoa(-1))
req.GPUUnits = -1
} else {
urlValues.Add("gpu_units", strconv.Itoa(gpuUnits))
req.GPUUnits = int64(gpuUnits)
}
updated = true
}
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)
req.SendAccessEmails = d.Get("send_access_emails").(bool)
updated = true
}
if updated {
_, err := c.CloudAPI().Account().Update(ctx, req)
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)
if acc.Status == "DELETED" {
req := account.RestoreRequest{
AccountID: accountId,
}
_, err := c.CloudAPI().Account().Restore(ctx, req)
if err != nil {
return diag.FromErr(err)
}
}
urlValues = &url.Values{}
}
}
@@ -402,9 +417,9 @@ func resourceAccountUpdate(ctx context.Context, d *schema.ResourceData, m interf
addedUsers := make([]interface{}, 0)
updatedUsers := make([]interface{}, 0)
old, new := d.GetChange("users")
old, new_ := d.GetChange("users")
oldConv := old.([]interface{})
newConv := new.([]interface{})
newConv := new_.([]interface{})
for _, el := range oldConv {
if !isContainsUser(newConv, el) {
deletedUsers = append(deletedUsers, el)
@@ -412,7 +427,15 @@ func resourceAccountUpdate(ctx context.Context, d *schema.ResourceData, m interf
}
for _, el := range newConv {
if !isContainsUser(oldConv, el) {
addedUsers = append(addedUsers, el)
duplicate := false
for _, user := range acc.ACL {
if user.UgroupID == el.(map[string]interface{})["user_id"].(string) {
duplicate = true
}
}
if !duplicate {
addedUsers = append(addedUsers, el)
}
} else {
if isChangedUser(oldConv, el) {
updatedUsers = append(updatedUsers, el)
@@ -423,45 +446,50 @@ func resourceAccountUpdate(ctx context.Context, d *schema.ResourceData, m interf
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)
req := account.DeleteUserRequest{
AccountID: accountId,
UserID: userConv["user_id"].(string),
RecursiveDelete: userConv["recursive_delete"].(bool),
}
_, err := c.CloudAPI().Account().DeleteUser(ctx, req)
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)
req := account.AddUserRequest{
AccountID: accountId,
UserID: userConv["user_id"].(string),
AccessType: strings.ToUpper(userConv["access_type"].(string)),
}
_, err := c.CloudAPI().Account().AddUser(ctx, req)
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)
req := account.UpdateUserRequest{
AccountID: accountId,
UserID: userConv["user_id"].(string),
AccessType: strings.ToUpper(userConv["access_type"].(string)),
}
_, err := c.CloudAPI().Account().UpdateUser(ctx, req)
if err != nil {
return diag.FromErr(err)
}
urlValues = &url.Values{}
}
}
@@ -514,7 +542,6 @@ func resourceAccountSchemaMake() map[string]*schema.Schema {
"send_access_emails": {
Type: schema.TypeBool,
Optional: true,
Default: true,
Description: "if true send emails when a user is granted access to resources",
},
"users": {
@@ -613,13 +640,13 @@ func resourceAccountSchemaMake() map[string]*schema.Schema {
Type: schema.TypeString,
Computed: true,
},
"meta": {
Type: schema.TypeList,
Computed: true,
Elem: &schema.Schema{
Type: schema.TypeString,
},
},
// "meta": {
// Type: schema.TypeList,
// Computed: true,
// Elem: &schema.Schema{
// Type: schema.TypeString,
// },
// },
"acl": {
Type: schema.TypeList,
Computed: true,
@@ -704,6 +731,14 @@ func resourceAccountSchemaMake() map[string]*schema.Schema {
Type: schema.TypeInt,
Computed: true,
},
"cpu_allocation_parameter": {
Type: schema.TypeString,
Computed: true,
},
"cpu_allocation_ratio": {
Type: schema.TypeFloat,
Computed: true,
},
}
}

View File

@@ -34,34 +34,32 @@ package account
import (
"context"
"encoding/json"
"net/url"
"strconv"
log "github.com/sirupsen/logrus"
"repository.basistech.ru/BASIS/decort-golang-sdk/pkg/cloudapi/account"
"repository.basistech.ru/BASIS/terraform-provider-decort/internal/controller"
"github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema"
)
func utilityAccountCheckPresence(ctx context.Context, d *schema.ResourceData, m interface{}) (*AccountWithResources, error) {
account := &AccountWithResources{}
func utilityAccountCheckPresence(ctx context.Context, d *schema.ResourceData, m interface{}) (*account.RecordAccount, error) {
c := m.(*controller.ControllerCfg)
urlValues := &url.Values{}
var id uint64
if (strconv.Itoa(d.Get("account_id").(int))) != "0" {
urlValues.Add("accountId", strconv.Itoa(d.Get("account_id").(int)))
id = uint64(d.Get("account_id").(int))
} else {
urlValues.Add("accountId", d.Id())
idParsed, _ := strconv.Atoi(d.Id())
id = uint64(idParsed)
}
req := account.GetRequest{
AccountID: 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)
account, err := c.CloudAPI().Account().Get(ctx, req)
if err != nil {
return nil, err
}

View File

@@ -34,30 +34,26 @@ package account
import (
"context"
"encoding/json"
"net/url"
"strconv"
log "github.com/sirupsen/logrus"
"repository.basistech.ru/BASIS/decort-golang-sdk/pkg/cloudapi/account"
"repository.basistech.ru/BASIS/terraform-provider-decort/internal/controller"
"github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema"
)
func utilityAccountAuditsListCheckPresence(ctx context.Context, d *schema.ResourceData, m interface{}) (AccountAuditsList, error) {
accountAuditsList := AccountAuditsList{}
func utilityAccountAuditsListCheckPresence(ctx context.Context, d *schema.ResourceData, m interface{}) (account.ListAudits, error) {
c := m.(*controller.ControllerCfg)
urlValues := &url.Values{}
var id uint64
urlValues.Add("accountId", strconv.Itoa(d.Get("account_id").(int)))
id = uint64(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
req := account.AuditsRequest{
AccountID: id,
}
err = json.Unmarshal([]byte(accountAuditsListRaw), &accountAuditsList)
log.Debugf("utilityAccountAuditsListCheckPresence: load account list")
accountAuditsList, err := c.CloudAPI().Account().Audits(ctx, req)
if err != nil {
return nil, err
}

View File

@@ -34,30 +34,26 @@ package account
import (
"context"
"encoding/json"
"net/url"
"strconv"
log "github.com/sirupsen/logrus"
"repository.basistech.ru/BASIS/decort-golang-sdk/pkg/cloudapi/account"
"repository.basistech.ru/BASIS/terraform-provider-decort/internal/controller"
"github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema"
)
func utilityAccountComputesListCheckPresence(ctx context.Context, d *schema.ResourceData, m interface{}) (AccountComputesList, error) {
accountComputesList := AccountComputesList{}
func utilityAccountComputesListCheckPresence(ctx context.Context, d *schema.ResourceData, m interface{}) (account.ListComputes, error) {
c := m.(*controller.ControllerCfg)
urlValues := &url.Values{}
var id uint64
urlValues.Add("accountId", strconv.Itoa(d.Get("account_id").(int)))
id = uint64(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
req := account.ListComputesRequest{
AccountID: id,
}
err = json.Unmarshal([]byte(accountComputesListRaw), &accountComputesList)
log.Debugf("utilityAccountComputesListCheckPresence: load account list")
accountComputesList, err := c.CloudAPI().Account().ListComputes(ctx, req)
if err != nil {
return nil, err
}

View File

@@ -34,30 +34,26 @@ package account
import (
"context"
"encoding/json"
"net/url"
"strconv"
log "github.com/sirupsen/logrus"
"repository.basistech.ru/BASIS/decort-golang-sdk/pkg/cloudapi/account"
"repository.basistech.ru/BASIS/terraform-provider-decort/internal/controller"
"github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema"
)
func utilityAccountConsumedUnitsCheckPresence(ctx context.Context, d *schema.ResourceData, m interface{}) (*ResourceLimits, error) {
accountConsumedUnits := &ResourceLimits{}
func utilityAccountConsumedUnitsCheckPresence(ctx context.Context, d *schema.ResourceData, m interface{}) (*account.ResourceLimits, error) {
c := m.(*controller.ControllerCfg)
urlValues := &url.Values{}
var id uint64
urlValues.Add("accountId", strconv.Itoa(d.Get("account_id").(int)))
id = uint64(d.Get("account_id").(int))
log.Debugf("utilityAccountConsumedUnitsCheckPresence: load account list")
accountConsumedUnitsRaw, err := c.DecortAPICall(ctx, "POST", accountGetConsumedUnitsAPI, urlValues)
if err != nil {
return nil, err
req := account.GetConsumedAccountUnitsRequest{
AccountID: id,
}
err = json.Unmarshal([]byte(accountConsumedUnitsRaw), accountConsumedUnits)
log.Debugf("utilityAccountConsumedUnitsCheckPresence: load account list")
accountConsumedUnits, err := c.CloudAPI().Account().GetConsumedAccountUnits(ctx, req)
if err != nil {
return nil, err
}

View File

@@ -34,11 +34,10 @@ package account
import (
"context"
"net/url"
"strconv"
"strings"
log "github.com/sirupsen/logrus"
"repository.basistech.ru/BASIS/decort-golang-sdk/pkg/cloudapi/account"
"repository.basistech.ru/BASIS/terraform-provider-decort/internal/controller"
"github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema"
@@ -46,17 +45,19 @@ import (
func utilityAccountConsumedUnitsByTypeCheckPresence(ctx context.Context, d *schema.ResourceData, m interface{}) (float64, error) {
c := m.(*controller.ControllerCfg)
urlValues := &url.Values{}
var id uint64
var cuType string
urlValues.Add("accountId", strconv.Itoa(d.Get("account_id").(int)))
urlValues.Add("cutype", strings.ToUpper(d.Get("cu_type").(string)))
id = uint64(d.Get("account_id").(int))
cuType = strings.ToUpper(d.Get("cu_type").(string))
req := account.GetConsumedCloudUnitsByTypeRequest{
AccountID: id,
CUType: cuType,
}
log.Debugf("utilityAccountConsumedUnitsByTypeCheckPresence")
resultRaw, err := c.DecortAPICall(ctx, "POST", accountGetConsumedUnitsByTypeAPI, urlValues)
if err != nil {
return 0, err
}
result, err := strconv.ParseFloat(resultRaw, 64)
result, err := c.CloudAPI().Account().GetConsumedCloudUnitsByType(ctx, req)
if err != nil {
return 0, err
}

View File

@@ -34,38 +34,37 @@ package account
import (
"context"
"encoding/json"
"net/url"
"strconv"
log "github.com/sirupsen/logrus"
"repository.basistech.ru/BASIS/decort-golang-sdk/pkg/cloudapi/account"
"repository.basistech.ru/BASIS/terraform-provider-decort/internal/controller"
"github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema"
)
func utilityAccountDeletedListCheckPresence(ctx context.Context, d *schema.ResourceData, m interface{}) (AccountCloudApiList, error) {
accountDeletedList := AccountCloudApiList{}
func utilityAccountDeletedListCheckPresence(ctx context.Context, d *schema.ResourceData, m interface{}) (account.ListAccounts, error) {
c := m.(*controller.ControllerCfg)
urlValues := &url.Values{}
var (
pageVal uint64 = 0
sizeVal uint64 = 0
)
if page, ok := d.GetOk("page"); ok {
urlValues.Add("page", strconv.Itoa(page.(int)))
pageVal = uint64(page.(int))
}
if size, ok := d.GetOk("size"); ok {
urlValues.Add("size", strconv.Itoa(size.(int)))
sizeVal = uint64(size.(int))
}
req := account.ListDeletedRequest{
Page: pageVal,
Size: sizeVal,
}
log.Debugf("utilityAccountDeletedListCheckPresence: load")
accountDeletedListRaw, err := c.DecortAPICall(ctx, "POST", accountListDeletedAPI, urlValues)
accountDeletedList, err := c.CloudAPI().Account().ListDeleted(ctx, req)
if err != nil {
return nil, err
}
err = json.Unmarshal([]byte(accountDeletedListRaw), &accountDeletedList)
if err != nil {
return nil, err
}
return accountDeletedList, nil
}

View File

@@ -34,30 +34,24 @@ package account
import (
"context"
"encoding/json"
"net/url"
"strconv"
log "github.com/sirupsen/logrus"
"repository.basistech.ru/BASIS/decort-golang-sdk/pkg/cloudapi/account"
"repository.basistech.ru/BASIS/terraform-provider-decort/internal/controller"
"github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema"
)
func utilityAccountDisksListCheckPresence(ctx context.Context, d *schema.ResourceData, m interface{}) (AccountDisksList, error) {
accountDisksList := AccountDisksList{}
func utilityAccountDisksListCheckPresence(ctx context.Context, d *schema.ResourceData, m interface{}) (account.ListDisks, error) {
c := m.(*controller.ControllerCfg)
urlValues := &url.Values{}
var id uint64
urlValues.Add("accountId", strconv.Itoa(d.Get("account_id").(int)))
id = uint64(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
req := account.ListDisksRequest{
AccountID: id,
}
err = json.Unmarshal([]byte(accountDisksListRaw), &accountDisksList)
accountDisksList, err := c.CloudAPI().Account().ListDisks(ctx, req)
if err != nil {
return nil, err
}

View File

@@ -34,30 +34,26 @@ package account
import (
"context"
"encoding/json"
"net/url"
"strconv"
log "github.com/sirupsen/logrus"
"repository.basistech.ru/BASIS/decort-golang-sdk/pkg/cloudapi/account"
"repository.basistech.ru/BASIS/terraform-provider-decort/internal/controller"
"github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema"
)
func utilityAccountFlipGroupsListCheckPresence(ctx context.Context, d *schema.ResourceData, m interface{}) (AccountFlipGroupsList, error) {
accountFlipGroupsList := AccountFlipGroupsList{}
func utilityAccountFlipGroupsListCheckPresence(ctx context.Context, d *schema.ResourceData, m interface{}) (account.ListFLIPGroups, error) {
c := m.(*controller.ControllerCfg)
urlValues := &url.Values{}
var id uint64
urlValues.Add("accountId", strconv.Itoa(d.Get("account_id").(int)))
id = uint64(d.Get("account_id").(int))
log.Debugf("utilityAccountFlipGroupsListCheckPresence")
accountFlipGroupsListRaw, err := c.DecortAPICall(ctx, "POST", accountListFlipGroupsAPI, urlValues)
if err != nil {
return nil, err
req := account.ListFLIPGroupsRequest{
AccountID: id,
}
err = json.Unmarshal([]byte(accountFlipGroupsListRaw), &accountFlipGroupsList)
log.Debugf("utilityAccountFlipGroupsListCheckPresence")
accountFlipGroupsList, err := c.CloudAPI().Account().ListFLIPGroups(ctx, req)
if err != nil {
return nil, err
}

View File

@@ -34,66 +34,38 @@ package account
import (
"context"
"encoding/json"
"net/url"
"strconv"
log "github.com/sirupsen/logrus"
"repository.basistech.ru/BASIS/decort-golang-sdk/pkg/cloudapi/account"
"repository.basistech.ru/BASIS/terraform-provider-decort/internal/controller"
"github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema"
)
func utilityAccountListCheckPresence(ctx context.Context, d *schema.ResourceData, m interface{}) (AccountCloudApiList, error) {
accountList := AccountCloudApiList{}
func utilityAccountListCheckPresence(ctx context.Context, d *schema.ResourceData, m interface{}) (account.ListAccounts, error) {
c := m.(*controller.ControllerCfg)
urlValues := &url.Values{}
var (
pageVal uint64 = 0
sizeVal uint64 = 0
)
if page, ok := d.GetOk("page"); ok {
urlValues.Add("page", strconv.Itoa(page.(int)))
pageVal = uint64(page.(int))
}
if size, ok := d.GetOk("size"); ok {
urlValues.Add("size", strconv.Itoa(size.(int)))
sizeVal = uint64(size.(int))
}
req := account.ListRequest{
Page: pageVal,
Size: sizeVal,
}
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)
accountList, err := c.CloudAPI().Account().List(ctx, req)
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)
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
}
*/

View File

@@ -34,30 +34,26 @@ package account
import (
"context"
"encoding/json"
"net/url"
"strconv"
log "github.com/sirupsen/logrus"
"repository.basistech.ru/BASIS/decort-golang-sdk/pkg/cloudapi/account"
"repository.basistech.ru/BASIS/terraform-provider-decort/internal/controller"
"github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema"
)
func utilityAccountReservedUnitsCheckPresence(ctx context.Context, d *schema.ResourceData, m interface{}) (*ResourceLimits, error) {
accountReservedUnits := &ResourceLimits{}
func utilityAccountReservedUnitsCheckPresence(ctx context.Context, d *schema.ResourceData, m interface{}) (*account.ResourceLimits, error) {
c := m.(*controller.ControllerCfg)
urlValues := &url.Values{}
var id uint64
urlValues.Add("accountId", strconv.Itoa(d.Get("account_id").(int)))
id = uint64(d.Get("account_id").(int))
log.Debugf("utilityAccountReservedUnitsCheckPresence: load units")
accountReservedUnitsRaw, err := c.DecortAPICall(ctx, "POST", accountGetReservedUnitsAPI, urlValues)
if err != nil {
return nil, err
req := account.GetReservedAccountUnitsRequest{
AccountID: id,
}
err = json.Unmarshal([]byte(accountReservedUnitsRaw), accountReservedUnits)
log.Debugf("utilityAccountReservedUnitsCheckPresence: load units")
accountReservedUnits, err := c.CloudAPI().Account().GetReservedAccountUnits(ctx, req)
if err != nil {
return nil, err
}

View File

@@ -34,30 +34,26 @@ package account
import (
"context"
"encoding/json"
"net/url"
"strconv"
log "github.com/sirupsen/logrus"
"repository.basistech.ru/BASIS/decort-golang-sdk/pkg/cloudapi/account"
"repository.basistech.ru/BASIS/terraform-provider-decort/internal/controller"
"github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema"
)
func utilityAccountRGListCheckPresence(ctx context.Context, d *schema.ResourceData, m interface{}) (AccountRGList, error) {
accountRGList := AccountRGList{}
func utilityAccountRGListCheckPresence(ctx context.Context, d *schema.ResourceData, m interface{}) (account.ListRG, error) {
c := m.(*controller.ControllerCfg)
urlValues := &url.Values{}
var id uint64
urlValues.Add("accountId", strconv.Itoa(d.Get("account_id").(int)))
id = uint64(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
req := account.ListRGRequest{
AccountID: id,
}
err = json.Unmarshal([]byte(accountRGListRaw), &accountRGList)
log.Debugf("utilityAccountRGListCheckPresence: load account list")
accountRGList, err := c.CloudAPI().Account().ListRG(ctx, req)
if err != nil {
return nil, err
}

View File

@@ -34,30 +34,26 @@ package account
import (
"context"
"encoding/json"
"net/url"
"strconv"
log "github.com/sirupsen/logrus"
"repository.basistech.ru/BASIS/decort-golang-sdk/pkg/cloudapi/account"
"repository.basistech.ru/BASIS/terraform-provider-decort/internal/controller"
"github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema"
)
func utilityAccountTemplatesListCheckPresence(ctx context.Context, d *schema.ResourceData, m interface{}) (AccountTemplatesList, error) {
accountTemplatesList := AccountTemplatesList{}
func utilityAccountTemplatesListCheckPresence(ctx context.Context, d *schema.ResourceData, m interface{}) (account.ListTemplates, error) {
c := m.(*controller.ControllerCfg)
urlValues := &url.Values{}
var id uint64
urlValues.Add("accountId", strconv.Itoa(d.Get("account_id").(int)))
id = uint64(d.Get("account_id").(int))
log.Debugf("utilityAccountTemplatesListCheckPresence: load")
accountTemplatesListRaw, err := c.DecortAPICall(ctx, "POST", accountListTemplatesAPI, urlValues)
if err != nil {
return nil, err
req := account.ListTemplatesRequest{
AccountID: id,
}
err = json.Unmarshal([]byte(accountTemplatesListRaw), &accountTemplatesList)
log.Debugf("utilityAccountTemplatesListCheckPresence: load")
accountTemplatesList, err := c.CloudAPI().Account().ListTemplates(ctx, req)
if err != nil {
return nil, err
}

View File

@@ -34,30 +34,26 @@ package account
import (
"context"
"encoding/json"
"net/url"
"strconv"
log "github.com/sirupsen/logrus"
"repository.basistech.ru/BASIS/decort-golang-sdk/pkg/cloudapi/account"
"repository.basistech.ru/BASIS/terraform-provider-decort/internal/controller"
"github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema"
)
func utilityAccountVinsListCheckPresence(ctx context.Context, d *schema.ResourceData, m interface{}) (AccountVinsList, error) {
accountVinsList := AccountVinsList{}
func utilityAccountVinsListCheckPresence(ctx context.Context, d *schema.ResourceData, m interface{}) (account.ListVINS, error) {
c := m.(*controller.ControllerCfg)
urlValues := &url.Values{}
var id uint64
urlValues.Add("accountId", strconv.Itoa(d.Get("account_id").(int)))
id = uint64(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
req := account.ListVINSRequest{
AccountID: id,
}
err = json.Unmarshal([]byte(accountVinsListRaw), &accountVinsList)
log.Debugf("utilityAccountVinsListCheckPresence: load account list")
accountVinsList, err := c.CloudAPI().Account().ListVINS(ctx, req)
if err != nil {
return nil, err
}

View File

@@ -1,60 +0,0 @@
/*
Copyright (c) 2019-2022 Digital Energy Cloud Solutions LLC. All Rights Reserved.
Authors:
Petr Krutov, <petr.krutov@digitalenergy.online>
Stanislav Solovev, <spsolovev@digitalenergy.online>
Kasim Baybikov, <kmbaybikov@basistech.ru>
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://repository.basistech.ru/BASIS/terraform-provider-decort
Please see README.md to learn where to place source code so that it
builds seamlessly.
Documentation: https://repository.basistech.ru/BASIS/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"

View File

@@ -47,7 +47,7 @@ func dataSourceBasicServiceRead(ctx context.Context, d *schema.ResourceData, m i
return diag.FromErr(err)
}
d.SetId(strconv.Itoa(bs.ID))
d.SetId(strconv.FormatUint(bs.ID, 10))
flattenService(d, bs)
@@ -77,6 +77,14 @@ func dataSourceBasicServiceSchemaMake() map[string]*schema.Schema {
Computed: true,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"account_id": {
Type: schema.TypeInt,
Computed: true,
},
"architecture": {
Type: schema.TypeString,
Computed: true,
},
"compgroup_id": {
Type: schema.TypeInt,
Computed: true,
@@ -93,10 +101,26 @@ func dataSourceBasicServiceSchemaMake() map[string]*schema.Schema {
Type: schema.TypeInt,
Computed: true,
},
"rg_id": {
Type: schema.TypeInt,
Computed: true,
},
"stack_id": {
Type: schema.TypeInt,
Computed: true,
},
"name": {
Type: schema.TypeString,
Computed: true,
},
"status": {
Type: schema.TypeString,
Computed: true,
},
"tech_status": {
Type: schema.TypeString,
Computed: true,
},
},
},
},
@@ -132,8 +156,33 @@ func dataSourceBasicServiceSchemaMake() map[string]*schema.Schema {
"groups": {
Type: schema.TypeList,
Computed: true,
Elem: &schema.Schema{
Type: schema.TypeInt,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"computes": {
Type: schema.TypeInt,
Computed: true,
},
"consistency": {
Type: schema.TypeBool,
Computed: true,
},
"id": {
Type: schema.TypeInt,
Computed: true,
},
"name": {
Type: schema.TypeString,
Computed: true,
},
"status": {
Type: schema.TypeString,
Computed: true,
},
"tech_status": {
Type: schema.TypeString,
Computed: true,
},
},
},
},
"groups_name": {

View File

@@ -38,6 +38,7 @@ import (
"github.com/google/uuid"
"github.com/hashicorp/terraform-plugin-sdk/v2/diag"
"github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema"
"repository.basistech.ru/BASIS/decort-golang-sdk/pkg/cloudapi/bservice"
"repository.basistech.ru/BASIS/terraform-provider-decort/internal/constants"
)
@@ -49,7 +50,7 @@ func dataSourceBasicServiceGroupRead(ctx context.Context, d *schema.ResourceData
id := uuid.New()
d.SetId(id.String())
d.Set("account_id", bsg.AccountId)
d.Set("account_id", bsg.AccountID)
d.Set("account_name", bsg.AccountName)
d.Set("computes", flattenBSGroupComputes(bsg.Computes))
d.Set("consistency", bsg.Consistency)
@@ -60,10 +61,10 @@ func dataSourceBasicServiceGroupRead(ctx context.Context, d *schema.ResourceData
d.Set("deleted_time", bsg.DeletedTime)
d.Set("disk", bsg.Disk)
d.Set("driver", bsg.Driver)
d.Set("extnets", bsg.Extnets)
d.Set("extnets", bsg.ExtNets)
d.Set("gid", bsg.GID)
d.Set("guid", bsg.GUID)
d.Set("image_id", bsg.ImageId)
d.Set("image_id", bsg.ImageID)
d.Set("milestones", bsg.Milestones)
d.Set("compgroup_name", bsg.Name)
d.Set("parents", bsg.Parents)
@@ -71,18 +72,18 @@ func dataSourceBasicServiceGroupRead(ctx context.Context, d *schema.ResourceData
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("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)
d.Set("vinses", bsg.VINSes)
return nil
}
func flattenBSGroupOSUsers(bsgosus BasicServiceGroupOSUsers) []map[string]interface{} {
func flattenBSGroupOSUsers(bsgosus bservice.ListOSUsers) []map[string]interface{} {
res := make([]map[string]interface{}, 0)
for _, bsgosu := range bsgosus {
temp := map[string]interface{}{
@@ -95,12 +96,12 @@ func flattenBSGroupOSUsers(bsgosus BasicServiceGroupOSUsers) []map[string]interf
return res
}
func flattenBSGroupComputes(bsgcs BasicServiceGroupComputes) []map[string]interface{} {
func flattenBSGroupComputes(bsgcs bservice.ListGroupComputes) []map[string]interface{} {
res := make([]map[string]interface{}, 0)
for _, bsgc := range bsgcs {
temp := map[string]interface{}{
"id": bsgc.ID,
"ip_addresses": bsgc.IPAdresses,
"ip_addresses": bsgc.IPAddresses,
"name": bsgc.Name,
"os_users": flattenBSGroupOSUsers(bsgc.OSUsers),
}

View File

@@ -38,14 +38,15 @@ import (
"github.com/google/uuid"
"github.com/hashicorp/terraform-plugin-sdk/v2/diag"
"github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema"
"repository.basistech.ru/BASIS/decort-golang-sdk/pkg/cloudapi/bservice"
"repository.basistech.ru/BASIS/terraform-provider-decort/internal/constants"
)
func flattenBasicServiceList(bsl BasicServiceList) []map[string]interface{} {
func flattenBasicServiceList(bsl bservice.ListBasicServices) []map[string]interface{} {
res := make([]map[string]interface{}, 0)
for _, bs := range bsl {
temp := map[string]interface{}{
"account_id": bs.AccountId,
"account_id": bs.AccountID,
"account_name": bs.AccountName,
"base_domain": bs.BaseDomain,
"created_by": bs.CreatedBy,
@@ -57,7 +58,7 @@ func flattenBasicServiceList(bsl BasicServiceList) []map[string]interface{} {
"guid": bs.GUID,
"service_id": bs.ID,
"service_name": bs.Name,
"parent_srv_id": bs.ParentSrvId,
"parent_srv_id": bs.ParentSrvID,
"parent_srv_type": bs.ParentSrvType,
"rg_id": bs.RGID,
"rg_name": bs.RGName,

View File

@@ -1,9 +1,62 @@
package bservice
import "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema"
import (
"github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema"
"repository.basistech.ru/BASIS/decort-golang-sdk/pkg/cloudapi/bservice"
)
func flattenService(d *schema.ResourceData, bs *BasicServiceExtend) {
d.Set("account_id", bs.AccountId)
func flattenResourceBasicServiceGroup(d *schema.ResourceData, bsg *bservice.RecordGroup) {
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)
}
func flattenGroups(groups bservice.ListGroups) []map[string]interface{} {
res := make([]map[string]interface{}, 0)
for _, group := range groups {
temp := map[string]interface{}{
"computes": group.Computes,
"consistency": group.Consistency,
"id": group.ID,
"name": group.Name,
"status": group.Status,
"tech_status": group.TechStatus,
}
res = append(res, temp)
}
return res
}
func flattenService(d *schema.ResourceData, bs *bservice.RecordBasicService) {
d.Set("account_id", bs.AccountID)
d.Set("account_name", bs.AccountName)
d.Set("base_domain", bs.BaseDomain)
d.Set("computes", flattenBasicServiceComputes(bs.Computes))
@@ -14,15 +67,14 @@ func flattenService(d *schema.ResourceData, bs *BasicServiceExtend) {
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("groups", flattenGroups(bs.Groups))
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_id", bs.ParentSrvID)
d.Set("parent_srv_type", bs.ParentSrvType)
d.Set("ram_total", bs.RamTotal)
d.Set("ram_total", bs.RAMTotal)
d.Set("rg_id", bs.RGID)
d.Set("rg_name", bs.RGName)
d.Set("snapshots", flattenBasicServiceSnapshots(bs.Snapshots))
@@ -35,15 +87,21 @@ func flattenService(d *schema.ResourceData, bs *BasicServiceExtend) {
d.Set("user_managed", bs.UserManaged)
}
func flattenBasicServiceComputes(bscs BasicServiceComputes) []map[string]interface{} {
func flattenBasicServiceComputes(bscs bservice.ListComputes) []map[string]interface{} {
res := make([]map[string]interface{}, 0)
for _, bsc := range bscs {
temp := map[string]interface{}{
"compgroup_id": bsc.CompGroupId,
"account_id": bsc.AccountID,
"architecture": bsc.Architecture,
"compgroup_id": bsc.CompGroupID,
"compgroup_name": bsc.CompGroupName,
"compgroup_role": bsc.CompGroupRole,
"id": bsc.ID,
"name": bsc.Name,
"rg_id": bsc.RGID,
"stack_id": bsc.StackID,
"status": bsc.Status,
"tech_status": bsc.TechStatus,
}
res = append(res, temp)
}
@@ -51,7 +109,7 @@ func flattenBasicServiceComputes(bscs BasicServiceComputes) []map[string]interfa
return res
}
func flattenBasicServiceSnapshots(bsrvss BasicServiceSnapshots) []map[string]interface{} {
func flattenBasicServiceSnapshots(bsrvss bservice.ListSnapshots) []map[string]interface{} {
res := make([]map[string]interface{}, 0)
for _, bsrvs := range bsrvss {
temp := map[string]interface{}{

View File

@@ -1,145 +0,0 @@
/*
Copyright (c) 2019-2022 Digital Energy Cloud Solutions LLC. All Rights Reserved.
Authors:
Petr Krutov, <petr.krutov@digitalenergy.online>
Stanislav Solovev, <spsolovev@digitalenergy.online>
Kasim Baybikov, <kmbaybikov@basistech.ru>
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://repository.basistech.ru/BASIS/terraform-provider-decort
Please see README.md to learn where to place source code so that it
builds seamlessly.
Documentation: https://repository.basistech.ru/BASIS/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"`
}

View File

@@ -34,12 +34,12 @@ package bservice
import (
"context"
"net/url"
"strconv"
"github.com/hashicorp/terraform-plugin-sdk/v2/diag"
"github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema"
log "github.com/sirupsen/logrus"
"repository.basistech.ru/BASIS/decort-golang-sdk/pkg/cloudapi/bservice"
"repository.basistech.ru/BASIS/terraform-provider-decort/internal/constants"
"repository.basistech.ru/BASIS/terraform-provider-decort/internal/controller"
"repository.basistech.ru/BASIS/terraform-provider-decort/internal/status"
@@ -47,9 +47,8 @@ import (
func resourceBasicServiceCreate(ctx context.Context, d *schema.ResourceData, m interface{}) diag.Diagnostics {
log.Debugf("resourceBasicServiceCreate")
c := m.(*controller.ControllerCfg)
urlValues := &url.Values{}
req := bservice.CreateRequest{}
haveRGID, err := existRGID(ctx, d, m)
if err != nil {
@@ -60,32 +59,25 @@ func resourceBasicServiceCreate(ctx context.Context, d *schema.ResourceData, m i
return diag.Errorf("resourceBasicServiceCreate: can't create basic service because RGID %d is not allowed or does not exist", d.Get("rg_id").(int))
}
urlValues.Add("name", d.Get("service_name").(string))
urlValues.Add("rgId", strconv.Itoa(d.Get("rg_id").(int)))
req.Name = d.Get("service_name").(string)
req.RGID = uint64(d.Get("rg_id").(int))
if sshKey, ok := d.GetOk("ssh_key"); ok {
urlValues.Add("sshKey", sshKey.(string))
req.SSHKey = sshKey.(string)
}
if sshUser, ok := d.GetOk("ssh_user"); ok {
urlValues.Add("sshUser", sshUser.(string))
req.SSHUser = sshUser.(string)
}
serviceId, err := c.DecortAPICall(ctx, "POST", bserviceCreateAPI, urlValues)
serviceId, err := c.CloudAPI().BService().Create(ctx, req)
if err != nil {
return diag.FromErr(err)
}
serviceIdParsed, _ := strconv.Atoi(serviceId)
d.SetId(strconv.FormatUint(serviceId, 10))
d.Set("service_id", serviceId)
d.SetId(serviceId)
d.Set("service_id", serviceIdParsed)
diagnostics := resourceBasicServiceRead(ctx, d, m)
if diagnostics != nil {
return diagnostics
}
return nil
return resourceBasicServiceRead(ctx, d, m)
}
func resourceBasicServiceRead(ctx context.Context, d *schema.ResourceData, m interface{}) diag.Diagnostics {
@@ -112,10 +104,20 @@ func resourceBasicServiceRead(ctx context.Context, d *schema.ResourceData, m int
case status.Disabling:
log.Debugf("The basic service is in status: %s, troubles can occur with the update.", bs.Status)
case status.Deleted:
urlVal := &url.Values{}
urlVal.Add("serviceId", d.Id())
id, _ := strconv.ParseUint(d.Id(), 10, 64)
restoreReq := bservice.RestoreRequest{
ServiceID: id,
}
enableReq := bservice.EnableRequest{
ServiceID: id,
}
_, err := c.DecortAPICall(ctx, "POST", bserviceRestoreAPI, urlVal)
_, err := c.CloudAPI().BService().Restore(ctx, restoreReq)
if err != nil {
return diag.FromErr(err)
}
_, err = c.CloudAPI().BService().Enable(ctx, enableReq)
if err != nil {
return diag.FromErr(err)
}
@@ -146,31 +148,30 @@ 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(ctx, d, m)
if bs == nil {
if err != nil {
return diag.FromErr(err)
}
return nil
}
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 = c.DecortAPICall(ctx, "POST", bserviceDeleteAPI, urlValues)
_, err := utilityBasicServiceCheckPresence(ctx, d, m)
if err != nil {
return diag.FromErr(err)
}
req := bservice.DeleteRequest{
ServiceID: uint64(d.Get("service_id").(int)),
Permanently: d.Get("permanently").(bool),
}
_, err = c.CloudAPI().BService().Delete(ctx, req)
if err != nil {
return diag.FromErr(err)
}
d.SetId("")
return nil
}
func resourceBasicServiceUpdate(ctx context.Context, d *schema.ResourceData, m interface{}) diag.Diagnostics {
log.Debugf("resourceBasicServiceEdit")
log.Debugf("resourceBasicServiceUpdate")
c := m.(*controller.ControllerCfg)
haveRGID, err := existRGID(ctx, d, m)
@@ -201,10 +202,20 @@ func resourceBasicServiceUpdate(ctx context.Context, d *schema.ResourceData, m i
case status.Disabling:
log.Debugf("The basic service is in status: %s, troubles can occur with the update.", bs.Status)
case status.Deleted:
urlVal := &url.Values{}
urlVal.Add("serviceId", d.Id())
id, _ := strconv.ParseUint(d.Id(), 10, 64)
restoreReq := bservice.RestoreRequest{
ServiceID: id,
}
enableReq := bservice.EnableRequest{
ServiceID: id,
}
_, err := c.DecortAPICall(ctx, "POST", bserviceRestoreAPI, urlVal)
_, err := c.CloudAPI().BService().Restore(ctx, restoreReq)
if err != nil {
return diag.FromErr(err)
}
_, err = c.CloudAPI().BService().Enable(ctx, enableReq)
if err != nil {
return diag.FromErr(err)
}
@@ -228,50 +239,63 @@ func resourceBasicServiceUpdate(ctx context.Context, d *schema.ResourceData, m i
}
}
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)))
req := bservice.EnableRequest{
ServiceID: uint64(d.Get("service_id").(int)),
}
_, err := c.DecortAPICall(ctx, "POST", api, urlValues)
if err != nil {
return diag.FromErr(err)
}
_, err := c.CloudAPI().BService().Enable(ctx, req)
if err != nil {
return diag.FromErr(err)
}
} else {
req := bservice.DisableRequest{
ServiceID: uint64(d.Get("service_id").(int)),
}
urlValues = &url.Values{}
_, err := c.CloudAPI().BService().Disable(ctx, req)
if err != nil {
return diag.FromErr(err)
}
}
}
if d.HasChange("restore") {
restore := d.Get("restore").(bool)
if restore {
urlValues.Add("serviceId", strconv.Itoa(d.Get("service_id").(int)))
_, err := c.DecortAPICall(ctx, "POST", bserviceRestoreAPI, urlValues)
req := bservice.RestoreRequest{
ServiceID: uint64(d.Get("service_id").(int)),
}
_, err := c.CloudAPI().BService().Restore(ctx, req)
if err != nil {
return diag.FromErr(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)))
req := bservice.StartRequest{
ServiceID: uint64(d.Get("service_id").(int)),
}
_, err := c.DecortAPICall(ctx, "POST", api, urlValues)
if err != nil {
return diag.FromErr(err)
}
_, err := c.CloudAPI().BService().Start(ctx, req)
if err != nil {
return diag.FromErr(err)
}
} else {
req := bservice.StopRequest{
ServiceID: uint64(d.Get("service_id").(int)),
}
urlValues = &url.Values{}
_, err := c.CloudAPI().BService().Stop(ctx, req)
if err != nil {
return diag.FromErr(err)
}
}
}
if d.HasChange("snapshots") {
@@ -300,42 +324,45 @@ func resourceBasicServiceUpdate(ctx context.Context, d *schema.ResourceData, m i
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(ctx, "POST", bserviceSnapshotDeleteAPI, urlValues)
req := bservice.SnapshotDeleteRequest{
ServiceID: uint64(d.Get("service_id").(int)),
Label: snapshotConv["label"].(string),
}
_, err := c.CloudAPI().BService().SnapshotDelete(ctx, req)
if err != nil {
return diag.FromErr(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(ctx, "POST", bserviceSnapshotCreateAPI, urlValues)
req := bservice.SnapshotCreateRequest{
ServiceID: uint64(d.Get("service_id").(int)),
Label: snapshotConv["label"].(string),
}
_, err := c.CloudAPI().BService().SnapshotCreate(ctx, req)
if err != nil {
return diag.FromErr(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(ctx, "POST", bserviceSnapshotRollbackAPI, urlValues)
req := bservice.SnapshotRollbackRequest{
ServiceID: uint64(d.Get("service_id").(int)),
Label: snapshotConv["label"].(string),
}
_, err := c.CloudAPI().BService().SnapshotRollback(ctx, req)
if err != nil {
return diag.FromErr(err)
}
urlValues = &url.Values{}
}
}
@@ -402,7 +429,7 @@ func resourceBasicServiceSchemaMake() map[string]*schema.Schema {
Type: schema.TypeBool,
Optional: true,
Default: false,
Description: "if set to False, Basic service will be deleted to recycle bin. Otherwise destroyed immediately",
Description: "Enable service. Enabling a service technically means setting model status of all computes and service itself to ENABLED. It does not start computes.",
},
"restore": {
Type: schema.TypeBool,
@@ -438,6 +465,14 @@ func resourceBasicServiceSchemaMake() map[string]*schema.Schema {
Computed: true,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"account_id": {
Type: schema.TypeInt,
Computed: true,
},
"architecture": {
Type: schema.TypeString,
Computed: true,
},
"compgroup_id": {
Type: schema.TypeInt,
Computed: true,
@@ -454,14 +489,29 @@ func resourceBasicServiceSchemaMake() map[string]*schema.Schema {
Type: schema.TypeInt,
Computed: true,
},
"rg_id": {
Type: schema.TypeInt,
Computed: true,
},
"stack_id": {
Type: schema.TypeInt,
Computed: true,
},
"name": {
Type: schema.TypeString,
Computed: true,
},
"status": {
Type: schema.TypeString,
Computed: true,
},
"tech_status": {
Type: schema.TypeString,
Computed: true,
},
},
},
},
"cpu_total": {
Type: schema.TypeInt,
Computed: true,
@@ -493,15 +543,33 @@ func resourceBasicServiceSchemaMake() map[string]*schema.Schema {
"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,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"computes": {
Type: schema.TypeInt,
Computed: true,
},
"consistency": {
Type: schema.TypeBool,
Computed: true,
},
"id": {
Type: schema.TypeInt,
Computed: true,
},
"name": {
Type: schema.TypeString,
Computed: true,
},
"status": {
Type: schema.TypeString,
Computed: true,
},
"tech_status": {
Type: schema.TypeString,
Computed: true,
},
},
},
},
"guid": {

View File

@@ -34,14 +34,13 @@ package bservice
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/hashicorp/terraform-plugin-sdk/v2/helper/validation"
log "github.com/sirupsen/logrus"
"repository.basistech.ru/BASIS/decort-golang-sdk/pkg/cloudapi/bservice"
"repository.basistech.ru/BASIS/terraform-provider-decort/internal/constants"
"repository.basistech.ru/BASIS/terraform-provider-decort/internal/controller"
)
@@ -50,111 +49,63 @@ func resourceBasicServiceGroupCreate(ctx context.Context, d *schema.ResourceData
log.Debugf("resourceBasicServiceGroupCreate")
c := m.(*controller.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)))
req := bservice.GroupAddRequest{
ServiceID: uint64(d.Get("service_id").(int)),
Name: d.Get("compgroup_name").(string),
Count: uint64(d.Get("comp_count").(int)),
CPU: uint64(d.Get("cpu").(int)),
RAM: uint64(d.Get("ram").(int)),
Disk: uint64(d.Get("disk").(int)),
ImageID: uint64(d.Get("image_id").(int)),
Driver: d.Get("driver").(string),
}
if role, ok := d.GetOk("role"); ok {
urlValues.Add("role", role.(string))
req.Role = role.(string)
}
if timeoutStart, ok := d.GetOk("timeout_start"); ok {
urlValues.Add("timeoutStart", strconv.Itoa(timeoutStart.(int)))
req.TimeoutStart = uint64(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
res := []uint64{}
for _, vins := range vinses.([]interface{}) {
res = append(res, uint64(vins.(int)))
}
temp = "[" + temp + "]"
urlValues.Add("vinses", temp)
req.VINSes = res
}
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
res := []uint64{}
for _, enet := range extnets.([]interface{}) {
res = append(res, uint64(enet.(int)))
}
temp = "[" + temp + "]"
urlValues.Add("extnets", temp)
req.ExtNets = res
}
compgroupId, err := c.DecortAPICall(ctx, "POST", bserviceGroupAddAPI, urlValues)
compgroupId, err := c.CloudAPI().BService().GroupAdd(ctx, req)
if err != nil {
return diag.FromErr(err)
}
d.SetId(compgroupId)
d.SetId(strconv.FormatUint(compgroupId, 10))
d.Set("compgroup_id", compgroupId)
diagnostics := resourceBasicServiceGroupRead(ctx, d, m)
if diagnostics != nil {
return diagnostics
}
return nil
return resourceBasicServiceGroupRead(ctx, d, m)
}
func resourceBasicServiceGroupRead(ctx context.Context, d *schema.ResourceData, m interface{}) diag.Diagnostics {
log.Debugf("resourceBasicServiceGroupRead")
bsg, err := utilityBasicServiceGroupCheckPresence(ctx, d, m)
if bsg == nil {
if err != nil {
d.SetId("")
return diag.FromErr(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)
flattenResourceBasicServiceGroup(d, bsg)
return nil
}
@@ -163,19 +114,17 @@ func resourceBasicServiceGroupDelete(ctx context.Context, d *schema.ResourceData
log.Debugf("resourceBasicServiceGroupDelete")
bsg, err := utilityBasicServiceGroupCheckPresence(ctx, d, m)
if bsg == nil {
if err != nil {
return diag.FromErr(err)
}
return nil
if err != nil {
return diag.FromErr(err)
}
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)))
req := bservice.GroupRemoveRequest{
ServiceID: bsg.ServiceID,
CompGroupID: bsg.ID,
}
_, err = c.DecortAPICall(ctx, "POST", bserviceGroupRemoveAPI, urlValues)
_, err = c.CloudAPI().BService().GroupRemove(ctx, req)
if err != nil {
return diag.FromErr(err)
}
@@ -184,113 +133,106 @@ func resourceBasicServiceGroupDelete(ctx context.Context, d *schema.ResourceData
return nil
}
func resourceBasicServiceGroupEdit(ctx context.Context, d *schema.ResourceData, m interface{}) diag.Diagnostics {
func resourceBasicServiceGroupUpdate(ctx context.Context, d *schema.ResourceData, m interface{}) diag.Diagnostics {
log.Debugf("resourceBasicServiceGroupEdit")
c := m.(*controller.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(ctx, "POST", bserviceGroupResizeAPI, urlValues)
req := bservice.GroupResizeRequest{
ServiceID: uint64(d.Get("service_id").(int)),
CompGroupID: uint64(d.Get("compgroup_id").(int)),
Count: int64(d.Get("comp_count").(int)),
Mode: d.Get("mode").(string),
}
_, err := c.CloudAPI().BService().GroupResize(ctx, req)
if err != nil {
return diag.FromErr(err)
}
urlValues = &url.Values{}
}
if d.HasChange("start") {
api := bserviceGroupStopAPI
start := d.Get("start").(bool)
if start {
api = bserviceGroupStartAPI
req := bservice.GroupStartRequest{
ServiceID: uint64(d.Get("service_id").(int)),
CompGroupID: uint64(d.Get("compgroup_id").(int)),
}
_, err := c.CloudAPI().BService().GroupStart(ctx, req)
if err != nil {
return diag.FromErr(err)
}
} 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)))
req := bservice.GroupStopRequest{
ServiceID: uint64(d.Get("service_id").(int)),
CompGroupID: uint64(d.Get("compgroup_id").(int)),
Force: d.Get("force_stop").(bool),
}
_, err := c.DecortAPICall(ctx, "POST", api, urlValues)
if err != nil {
return diag.FromErr(err)
_, err := c.CloudAPI().BService().GroupStop(ctx, req)
if err != nil {
return diag.FromErr(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)))
req := bservice.GroupUpdateRequest{
ServiceID: uint64(d.Get("service_id").(int)),
CompGroupID: uint64(d.Get("compgroup_id").(int)),
Name: d.Get("compgroup_name").(string),
Role: d.Get("role").(string),
CPU: uint64(d.Get("cpu").(int)),
RAM: uint64(d.Get("ram").(int)),
Disk: uint64(d.Get("disk").(int)),
Force: 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(ctx, "POST", bserviceGroupUpdateAPI, urlValues)
_, err := c.CloudAPI().BService().GroupUpdate(ctx, req)
if err != nil {
return diag.FromErr(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(ctx, "POST", bserviceGroupUpdateExtnetAPI, urlValues)
res := []uint64{}
for _, enet := range extnets {
res = append(res, uint64(enet.(int)))
}
req := bservice.GroupUpdateExtNetRequest{
ServiceID: uint64(d.Get("service_id").(int)),
CompGroupID: uint64(d.Get("compgroup_id").(int)),
ExtNets: res,
}
_, err := c.CloudAPI().BService().GroupUpdateExtNet(ctx, req)
if err != nil {
return diag.FromErr(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(ctx, "POST", bserviceGroupUpdateVinsAPI, urlValues)
res := []uint64{}
for _, vins := range vinses {
res = append(res, uint64(vins.(int)))
}
req := bservice.GroupUpdateVINSRequest{
ServiceID: uint64(d.Get("service_id").(int)),
CompGroupID: uint64(d.Get("compgroup_id").(int)),
VINSes: res,
}
_, err := c.CloudAPI().BService().GroupUpdateVINS(ctx, req)
if err != nil {
return diag.FromErr(err)
}
urlValues = &url.Values{}
}
if d.HasChange("parents") {
@@ -315,31 +257,33 @@ func resourceBasicServiceGroupEdit(ctx context.Context, d *schema.ResourceData,
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))
req := bservice.GroupParentRemoveRequest{
ServiceID: uint64(d.Get("service_id").(int)),
CompGroupID: uint64(d.Get("compgroup_id").(int)),
ParentID: uint64(parentConv),
}
_, err := c.DecortAPICall(ctx, "POST", bserviceGroupParentRemoveAPI, urlValues)
_, err := c.CloudAPI().BService().GroupParentRemove(ctx, req)
if err != nil {
return diag.FromErr(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(ctx, "POST", bserviceGroupParentAddAPI, urlValues)
req := bservice.GroupParentAddRequest{
ServiceID: uint64(d.Get("service_id").(int)),
CompGroupID: uint64(d.Get("compgroup_id").(int)),
ParentID: uint64(parentConv),
}
_, err := c.CloudAPI().BService().GroupParentAdd(ctx, req)
if err != nil {
return diag.FromErr(err)
}
urlValues = &url.Values{}
}
}
}
@@ -348,16 +292,16 @@ func resourceBasicServiceGroupEdit(ctx context.Context, d *schema.ResourceData,
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)))
req := bservice.GroupComputeRemoveRequest{
ServiceID: uint64(d.Get("service_id").(int)),
CompGroupID: uint64(d.Get("compgroup_id").(int)),
ComputeID: uint64(rc.(int)),
}
_, err := c.DecortAPICall(ctx, "POST", bserviceGroupComputeRemoveAPI, urlValues)
_, err := c.CloudAPI().BService().GroupComputeRemove(ctx, req)
if err != nil {
return diag.FromErr(err)
}
urlValues = &url.Values{}
}
}
}
@@ -613,7 +557,7 @@ func ResourceBasicServiceGroup() *schema.Resource {
CreateContext: resourceBasicServiceGroupCreate,
ReadContext: resourceBasicServiceGroupRead,
UpdateContext: resourceBasicServiceGroupEdit,
UpdateContext: resourceBasicServiceGroupUpdate,
DeleteContext: resourceBasicServiceGroupDelete,
Importer: &schema.ResourceImporter{

View File

@@ -2,41 +2,23 @@ package bservice
import (
"context"
"encoding/json"
"net/url"
"github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema"
"repository.basistech.ru/BASIS/decort-golang-sdk/pkg/cloudapi/rg"
"repository.basistech.ru/BASIS/terraform-provider-decort/internal/controller"
)
func existRGID(ctx context.Context, d *schema.ResourceData, m interface{}) (bool, error) {
c := m.(*controller.ControllerCfg)
urlValues := &url.Values{}
rgList := []struct {
ID int `json:"id"`
}{}
req := rg.ListRequest{}
rgListAPI := "/restmachine/cloudapi/rg/list"
rgListRaw, err := c.DecortAPICall(ctx, "POST", rgListAPI, urlValues)
rgList, err := c.CloudAPI().RG().List(ctx, req)
if err != nil {
return false, err
}
err = json.Unmarshal([]byte(rgListRaw), &rgList)
if err != nil {
return false, err
}
rgId := uint64(d.Get("rg_id").(int))
haveRG := false
rgId := d.Get("rg_id").(int)
for _, rg := range rgList {
if rg.ID == rgId {
haveRG = true
break
}
}
return haveRG, nil
return len(rgList.FilterByID(rgId)) != 0, nil
}

View File

@@ -34,41 +34,33 @@ package bservice
import (
"context"
"encoding/json"
"net/url"
"strconv"
log "github.com/sirupsen/logrus"
"repository.basistech.ru/BASIS/decort-golang-sdk/pkg/cloudapi/bservice"
"repository.basistech.ru/BASIS/terraform-provider-decort/internal/controller"
"github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema"
)
func utilityBasicServiceDeletedListCheckPresence(ctx context.Context, d *schema.ResourceData, m interface{}) (BasicServiceList, error) {
basicServiceDeletedList := BasicServiceList{}
func utilityBasicServiceDeletedListCheckPresence(ctx context.Context, d *schema.ResourceData, m interface{}) (bservice.ListBasicServices, error) {
c := m.(*controller.ControllerCfg)
urlValues := &url.Values{}
req := bservice.ListRequest{}
if accountId, ok := d.GetOk("account_id"); ok {
urlValues.Add("accountId", strconv.Itoa(accountId.(int)))
req.AccountID = uint64(accountId.(int))
}
if rgId, ok := d.GetOk("rg_id"); ok {
urlValues.Add("rgId", strconv.Itoa(rgId.(int)))
req.RGID = uint64(rgId.(int))
}
if page, ok := d.GetOk("page"); ok {
urlValues.Add("page", strconv.Itoa(page.(int)))
req.Page = uint64(page.(int))
}
if size, ok := d.GetOk("size"); ok {
urlValues.Add("size", strconv.Itoa(size.(int)))
req.Size = uint64(size.(int))
}
log.Debugf("utilityBasicServiceDeletedListCheckPresence")
basicServiceDeletedListRaw, err := c.DecortAPICall(ctx, "POST", bserviceListDeletedAPI, urlValues)
if err != nil {
return nil, err
}
err = json.Unmarshal([]byte(basicServiceDeletedListRaw), &basicServiceDeletedList)
basicServiceDeletedList, err := c.CloudAPI().BService().ListDeleted(ctx, req)
if err != nil {
return nil, err
}

View File

@@ -34,34 +34,31 @@ package bservice
import (
"context"
"encoding/json"
"net/url"
"strconv"
log "github.com/sirupsen/logrus"
"repository.basistech.ru/BASIS/decort-golang-sdk/pkg/cloudapi/bservice"
"repository.basistech.ru/BASIS/terraform-provider-decort/internal/controller"
"github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema"
)
func utilityBasicServiceCheckPresence(ctx context.Context, d *schema.ResourceData, m interface{}) (*BasicServiceExtend, error) {
bservice := &BasicServiceExtend{}
func utilityBasicServiceCheckPresence(ctx context.Context, d *schema.ResourceData, m interface{}) (*bservice.RecordBasicService, error) {
c := m.(*controller.ControllerCfg)
urlValues := &url.Values{}
var id uint64
if (strconv.Itoa(d.Get("service_id").(int))) != "0" {
urlValues.Add("serviceId", strconv.Itoa(d.Get("service_id").(int)))
id = uint64(d.Get("service_id").(int))
} else {
urlValues.Add("serviceId", d.Id())
id, _ = strconv.ParseUint(d.Id(), 10, 64)
}
req := bservice.GetRequest{
ServiceID: id,
}
log.Debugf("utilityBasicServiceCheckPresence")
bserviceRaw, err := c.DecortAPICall(ctx, "POST", bserviceGetAPI, urlValues)
if err != nil {
return nil, err
}
err = json.Unmarshal([]byte(bserviceRaw), &bservice)
bservice, err := c.CloudAPI().BService().Get(ctx, req)
if err != nil {
return nil, err
}

View File

@@ -34,35 +34,31 @@ package bservice
import (
"context"
"encoding/json"
"net/url"
"strconv"
log "github.com/sirupsen/logrus"
"repository.basistech.ru/BASIS/decort-golang-sdk/pkg/cloudapi/bservice"
"repository.basistech.ru/BASIS/terraform-provider-decort/internal/controller"
"github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema"
)
func utilityBasicServiceGroupCheckPresence(ctx context.Context, d *schema.ResourceData, m interface{}) (*BasicServiceGroup, error) {
bserviceGroup := &BasicServiceGroup{}
func utilityBasicServiceGroupCheckPresence(ctx context.Context, d *schema.ResourceData, m interface{}) (*bservice.RecordGroup, error) {
c := m.(*controller.ControllerCfg)
urlValues := &url.Values{}
urlValues.Add("serviceId", strconv.Itoa(d.Get("service_id").(int)))
req := bservice.GroupGetRequest{
ServiceID: uint64(d.Get("service_id").(int)),
}
if (strconv.Itoa(d.Get("compgroup_id").(int))) != "0" {
urlValues.Add("compgroupId", strconv.Itoa(d.Get("compgroup_id").(int)))
req.CompGroupID = uint64(d.Get("compgroup_id").(int))
} else {
urlValues.Add("compgroupId", d.Id())
comGroupID, _ := strconv.ParseUint(d.Id(), 10, 64)
req.CompGroupID = comGroupID
}
log.Debugf("utilityBasicServiceGroupCheckPresence")
bserviceGroupRaw, err := c.DecortAPICall(ctx, "POST", bserviceGroupGetAPI, urlValues)
if err != nil {
return nil, err
}
err = json.Unmarshal([]byte(bserviceGroupRaw), &bserviceGroup)
bserviceGroup, err := c.CloudAPI().BService().GroupGet(ctx, req)
if err != nil {
return nil, err
}

View File

@@ -34,41 +34,33 @@ package bservice
import (
"context"
"encoding/json"
"net/url"
"strconv"
log "github.com/sirupsen/logrus"
"repository.basistech.ru/BASIS/decort-golang-sdk/pkg/cloudapi/bservice"
"repository.basistech.ru/BASIS/terraform-provider-decort/internal/controller"
"github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema"
)
func utilityBasicServiceListCheckPresence(ctx context.Context, d *schema.ResourceData, m interface{}) (BasicServiceList, error) {
basicServiceList := BasicServiceList{}
func utilityBasicServiceListCheckPresence(ctx context.Context, d *schema.ResourceData, m interface{}) (bservice.ListBasicServices, error) {
c := m.(*controller.ControllerCfg)
urlValues := &url.Values{}
req := bservice.ListRequest{}
if accountId, ok := d.GetOk("account_id"); ok {
urlValues.Add("accountId", strconv.Itoa(accountId.(int)))
req.AccountID = uint64(accountId.(int))
}
if rgId, ok := d.GetOk("rg_id"); ok {
urlValues.Add("rgId", strconv.Itoa(rgId.(int)))
req.RGID = uint64(rgId.(int))
}
if page, ok := d.GetOk("page"); ok {
urlValues.Add("page", strconv.Itoa(page.(int)))
req.Page = uint64(page.(int))
}
if size, ok := d.GetOk("size"); ok {
urlValues.Add("size", strconv.Itoa(size.(int)))
req.Size = uint64(size.(int))
}
log.Debugf("utilityBasicServiceListCheckPresence")
basicServiceListRaw, err := c.DecortAPICall(ctx, "POST", bserviceListAPI, urlValues)
if err != nil {
return nil, err
}
err = json.Unmarshal([]byte(basicServiceListRaw), &basicServiceList)
basicServiceList, err := c.CloudAPI().BService().List(ctx, req)
if err != nil {
return nil, err
}

View File

@@ -34,32 +34,28 @@ package bservice
import (
"context"
"encoding/json"
"net/url"
"strconv"
log "github.com/sirupsen/logrus"
"repository.basistech.ru/BASIS/decort-golang-sdk/pkg/cloudapi/bservice"
"repository.basistech.ru/BASIS/terraform-provider-decort/internal/controller"
"github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema"
)
func utilityBasicServiceSnapshotListCheckPresence(ctx context.Context, d *schema.ResourceData, m interface{}) (BasicServiceSnapshots, error) {
basicServiceSnapshotList := BasicServiceSnapshots{}
func utilityBasicServiceSnapshotListCheckPresence(ctx context.Context, d *schema.ResourceData, m interface{}) (bservice.ListSnapshots, error) {
c := m.(*controller.ControllerCfg)
urlValues := &url.Values{}
var id uint64
if serviceId, ok := d.GetOk("service_id"); ok {
urlValues.Add("serviceId", strconv.Itoa(serviceId.(int)))
id = uint64(serviceId.(int))
}
req := bservice.SnapshotListRequest{
ServiceID: id,
}
log.Debugf("utilityBasicServiceSnapshotListCheckPresence")
basicServiceSnapshotListRaw, err := c.DecortAPICall(ctx, "POST", bserviceSnapshotListAPI, urlValues)
if err != nil {
return nil, err
}
err = json.Unmarshal([]byte(basicServiceSnapshotListRaw), &basicServiceSnapshotList)
basicServiceSnapshotList, err := c.CloudAPI().BService().SnapshotList(ctx, req)
if err != nil {
return nil, err
}

View File

@@ -1,52 +0,0 @@
/*
Copyright (c) 2019-2022 Digital Energy Cloud Solutions LLC. All Rights Reserved.
Authors:
Petr Krutov, <petr.krutov@digitalenergy.online>
Stanislav Solovev, <spsolovev@digitalenergy.online>
Kasim Baybikov, <kmbaybikov@basistech.ru>
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://repository.basistech.ru/BASIS/terraform-provider-decort
Please see README.md to learn where to place source code so that it
builds seamlessly.
Documentation: https://repository.basistech.ru/BASIS/terraform-provider-decort/wiki
*/
package disks
const (
disksCreateAPI = "/restmachine/cloudapi/disks/create"
disksGetAPI = "/restmachine/cloudapi/disks/get"
disksListAPI = "/restmachine/cloudapi/disks/list"
disksResizeAPI = "/restmachine/cloudapi/disks/resize2"
disksRenameAPI = "/restmachine/cloudapi/disks/rename"
disksDeleteAPI = "/restmachine/cloudapi/disks/delete"
disksIOLimitAPI = "/restmachine/cloudapi/disks/limitIO"
disksRestoreAPI = "/restmachine/cloudapi/disks/restore"
disksListTypesAPI = "/restmachine/cloudapi/disks/listTypes"
disksListDeletedAPI = "/restmachine/cloudapi/disks/listDeleted"
disksListUnattachedAPI = "/restmachine/cloudapi/disks/listUnattached"
disksSnapshotDeleteAPI = "/restmachine/cloudapi/disks/snapshotDelete"
disksSnapshotRollbackAPI = "/restmachine/cloudapi/disks/snapshotRollback"
disksShareAPI = "/restmachine/cloudapi/disks/share"
disksUnshareAPI = "/restmachine/cloudapi/disks/unshare"
)

View File

@@ -34,7 +34,6 @@ package disks
import (
"context"
"encoding/json"
// "net/url"
@@ -54,53 +53,7 @@ func dataSourceDiskRead(ctx context.Context, d *schema.ResourceData, m interface
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("computes", flattenDiskComputes(disk.Computes))
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("present_to", disk.PresentTo)
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("shareable", disk.Shareable)
d.Set("size_max", disk.SizeMax)
d.Set("size_used", disk.SizeUsed)
d.Set("snapshots", flattenDiskSnapshotList(disk.Snapshots))
d.Set("status", disk.Status)
d.Set("tech_status", disk.TechStatus)
d.Set("type", disk.Type)
d.Set("vmid", disk.VMID)
flattenDisk(d, disk)
return nil
}
@@ -126,11 +79,11 @@ func dataSourceDiskSchemaMake() map[string]*schema.Schema {
Type: schema.TypeString,
Computed: true,
},
"boot_partition": {
Type: schema.TypeInt,
Computed: true,
Description: "Number of disk partitions",
},
// "boot_partition": {
// Type: schema.TypeInt,
// Computed: true,
// Description: "Number of disk partitions",
// },
"computes": {
Type: schema.TypeList,
Computed: true,
@@ -172,21 +125,21 @@ func dataSourceDiskSchemaMake() map[string]*schema.Schema {
Computed: true,
Description: "Name of the device",
},
"disk_path": {
Type: schema.TypeString,
Computed: true,
Description: "Disk path",
},
// "disk_path": {
// Type: schema.TypeString,
// Computed: true,
// Description: "Disk path",
// },
"gid": {
Type: schema.TypeInt,
Computed: true,
Description: "ID of the grid (platform)",
},
"guid": {
Type: schema.TypeInt,
Computed: true,
Description: "Disk ID on the storage side",
},
// "guid": {
// Type: schema.TypeInt,
// Computed: true,
// Description: "Disk ID on the storage side",
// },
"image_id": {
Type: schema.TypeInt,
Computed: true,
@@ -273,21 +226,21 @@ func dataSourceDiskSchemaMake() map[string]*schema.Schema {
},
},
},
"iqn": {
Type: schema.TypeString,
Computed: true,
Description: "Disk IQN",
},
"login": {
Type: schema.TypeString,
Computed: true,
Description: "Login to access the disk",
},
"milestones": {
Type: schema.TypeInt,
Computed: true,
Description: "Milestones",
},
// "iqn": {
// Type: schema.TypeString,
// Computed: true,
// Description: "Disk IQN",
// },
// "login": {
// Type: schema.TypeString,
// Computed: true,
// Description: "Login to access the disk",
// },
// "milestones": {
// Type: schema.TypeInt,
// Computed: true,
// Description: "Milestones",
// },
"disk_name": {
Type: schema.TypeString,
Computed: true,
@@ -308,11 +261,11 @@ func dataSourceDiskSchemaMake() map[string]*schema.Schema {
Computed: true,
Description: "ID of the parent disk",
},
"passwd": {
Type: schema.TypeString,
Computed: true,
Description: "Password to access the disk",
},
// "passwd": {
// Type: schema.TypeString,
// Computed: true,
// Description: "Password to access the disk",
// },
"pci_slot": {
Type: schema.TypeInt,
Computed: true,
@@ -330,26 +283,26 @@ func dataSourceDiskSchemaMake() map[string]*schema.Schema {
Type: schema.TypeInt,
},
},
"purge_attempts": {
Type: schema.TypeInt,
Computed: true,
Description: "Number of deletion attempts",
},
// "purge_attempts": {
// Type: schema.TypeInt,
// Computed: true,
// Description: "Number of deletion attempts",
// },
"purge_time": {
Type: schema.TypeInt,
Computed: true,
Description: "Time of the last deletion attempt",
},
"reality_device_number": {
Type: schema.TypeInt,
Computed: true,
Description: "Reality device number",
},
"reference_id": {
Type: schema.TypeString,
Computed: true,
Description: "ID of the reference to the disk",
},
// "reality_device_number": {
// Type: schema.TypeInt,
// Computed: true,
// Description: "Reality device number",
// },
// "reference_id": {
// Type: schema.TypeString,
// Computed: true,
// Description: "ID of the reference to the disk",
// },
"res_id": {
Type: schema.TypeString,
Computed: true,

View File

@@ -42,7 +42,7 @@ import (
)
func dataSourceDiskListRead(ctx context.Context, d *schema.ResourceData, m interface{}) diag.Diagnostics {
diskList, err := utilityDiskListCheckPresence(ctx, d, m, disksListAPI)
diskList, err := utilityDiskListCheckPresence(ctx, d, m)
if err != nil {
return diag.FromErr(err)
}
@@ -95,11 +95,11 @@ func dataSourceDiskListSchemaMake() map[string]*schema.Schema {
Type: schema.TypeString,
Computed: true,
},
"boot_partition": {
Type: schema.TypeInt,
Computed: true,
Description: "Number of disk partitions",
},
// "boot_partition": {
// Type: schema.TypeInt,
// Computed: true,
// Description: "Number of disk partitions",
// },
"computes": {
Type: schema.TypeList,
Computed: true,
@@ -141,21 +141,21 @@ func dataSourceDiskListSchemaMake() map[string]*schema.Schema {
Computed: true,
Description: "Name of the device",
},
"disk_path": {
Type: schema.TypeString,
Computed: true,
Description: "Disk path",
},
// "disk_path": {
// Type: schema.TypeString,
// Computed: true,
// Description: "Disk path",
// },
"gid": {
Type: schema.TypeInt,
Computed: true,
Description: "ID of the grid (platform)",
},
"guid": {
Type: schema.TypeInt,
Computed: true,
Description: "Disk ID on the storage side",
},
// "guid": {
// Type: schema.TypeInt,
// Computed: true,
// Description: "Disk ID on the storage side",
// },
"disk_id": {
Type: schema.TypeInt,
Computed: true,
@@ -247,16 +247,16 @@ func dataSourceDiskListSchemaMake() map[string]*schema.Schema {
},
},
},
"iqn": {
Type: schema.TypeString,
Computed: true,
Description: "Disk IQN",
},
"login": {
Type: schema.TypeString,
Computed: true,
Description: "Login to access the disk",
},
// "iqn": {
// Type: schema.TypeString,
// Computed: true,
// Description: "Disk IQN",
// },
// "login": {
// Type: schema.TypeString,
// Computed: true,
// Description: "Login to access the disk",
// },
"machine_id": {
Type: schema.TypeInt,
Computed: true,
@@ -267,11 +267,11 @@ func dataSourceDiskListSchemaMake() map[string]*schema.Schema {
Computed: true,
Description: "Machine name",
},
"milestones": {
Type: schema.TypeInt,
Computed: true,
Description: "Milestones",
},
// "milestones": {
// Type: schema.TypeInt,
// Computed: true,
// Description: "Milestones",
// },
"disk_name": {
Type: schema.TypeString,
Computed: true,
@@ -292,11 +292,11 @@ func dataSourceDiskListSchemaMake() map[string]*schema.Schema {
Computed: true,
Description: "ID of the parent disk",
},
"passwd": {
Type: schema.TypeString,
Computed: true,
Description: "Password to access the disk",
},
// "passwd": {
// Type: schema.TypeString,
// Computed: true,
// Description: "Password to access the disk",
// },
"pci_slot": {
Type: schema.TypeInt,
Computed: true,
@@ -314,26 +314,26 @@ func dataSourceDiskListSchemaMake() map[string]*schema.Schema {
Type: schema.TypeInt,
},
},
"purge_attempts": {
Type: schema.TypeInt,
Computed: true,
Description: "Number of deletion attempts",
},
// "purge_attempts": {
// Type: schema.TypeInt,
// Computed: true,
// Description: "Number of deletion attempts",
// },
"purge_time": {
Type: schema.TypeInt,
Computed: true,
Description: "Time of the last deletion attempt",
},
"reality_device_number": {
Type: schema.TypeInt,
Computed: true,
Description: "Reality device number",
},
"reference_id": {
Type: schema.TypeString,
Computed: true,
Description: "ID of the reference to the disk",
},
// "reality_device_number": {
// Type: schema.TypeInt,
// Computed: true,
// Description: "Reality device number",
// },
// "reference_id": {
// Type: schema.TypeString,
// Computed: true,
// Description: "ID of the reference to the disk",
// },
"res_id": {
Type: schema.TypeString,
Computed: true,

View File

@@ -41,24 +41,26 @@ import (
"repository.basistech.ru/BASIS/terraform-provider-decort/internal/constants"
)
func flattenDiskListTypesDetailed(tld TypesDetailedList) []map[string]interface{} {
func flattenDiskListTypesDetailed(tld []interface{}) []map[string]interface{} {
res := make([]map[string]interface{}, 0)
for _, typeListDetailed := range tld {
toMap := typeListDetailed.(map[string]interface{})
temp := map[string]interface{}{
"pools": flattenListTypesDetailedPools(typeListDetailed.Pools),
"sep_id": typeListDetailed.SepID,
"pools": flattenListTypesDetailedPools(toMap["pools"].([]interface{})),
"sep_id": toMap["sepId"].(float64),
}
res = append(res, temp)
}
return res
}
func flattenListTypesDetailedPools(pools PoolList) []interface{} {
func flattenListTypesDetailedPools(pools []interface{}) []interface{} {
res := make([]interface{}, 0)
for _, pool := range pools {
toMap := pool.(map[string]interface{})
temp := map[string]interface{}{
"name": pool.Name,
"types": pool.Types,
"name": toMap["name"].(string),
"types": toMap["types"].([]interface{}),
}
res = append(res, temp)
}

View File

@@ -34,92 +34,13 @@ package disks
import (
"context"
"encoding/json"
"net/url"
"strconv"
"github.com/google/uuid"
"github.com/hashicorp/terraform-plugin-sdk/v2/diag"
"github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema"
"repository.basistech.ru/BASIS/terraform-provider-decort/internal/constants"
"repository.basistech.ru/BASIS/terraform-provider-decort/internal/controller"
"repository.basistech.ru/BASIS/terraform-provider-decort/internal/flattens"
log "github.com/sirupsen/logrus"
)
func utilityDiskListUnattachedCheckPresence(ctx context.Context, d *schema.ResourceData, m interface{}) (UnattachedList, error) {
unattachedList := UnattachedList{}
c := m.(*controller.ControllerCfg)
urlValues := &url.Values{}
if accountId, ok := d.GetOk("accountId"); ok {
urlValues.Add("accountId", strconv.Itoa(accountId.(int)))
}
log.Debugf("utilityDiskListUnattachedCheckPresence: load disk Unattached list")
unattachedListRaw, err := c.DecortAPICall(ctx, "POST", disksListUnattachedAPI, urlValues)
if err != nil {
return nil, err
}
err = json.Unmarshal([]byte(unattachedListRaw), &unattachedList)
if err != nil {
return nil, err
}
return unattachedList, nil
}
func flattenDiskListUnattached(ul UnattachedList) []map[string]interface{} {
res := make([]map[string]interface{}, 0)
for _, unattachedDisk := range ul {
unattachedDiskAcl, _ := json.Marshal(unattachedDisk.Acl)
tmp := map[string]interface{}{
"_ckey": unattachedDisk.Ckey,
"_meta": flattens.FlattenMeta(unattachedDisk.Meta),
"account_id": unattachedDisk.AccountID,
"account_name": unattachedDisk.AccountName,
"acl": string(unattachedDiskAcl),
"boot_partition": unattachedDisk.BootPartition,
"created_time": unattachedDisk.CreatedTime,
"deleted_time": unattachedDisk.DeletedTime,
"desc": unattachedDisk.Desc,
"destruction_time": unattachedDisk.DestructionTime,
"disk_path": unattachedDisk.DiskPath,
"gid": unattachedDisk.GridID,
"guid": unattachedDisk.GUID,
"disk_id": unattachedDisk.ID,
"image_id": unattachedDisk.ImageID,
"images": unattachedDisk.Images,
"iotune": flattenIOTune(unattachedDisk.IOTune),
"iqn": unattachedDisk.IQN,
"login": unattachedDisk.Login,
"milestones": unattachedDisk.Milestones,
"disk_name": unattachedDisk.Name,
"order": unattachedDisk.Order,
"params": unattachedDisk.Params,
"parent_id": unattachedDisk.ParentID,
"passwd": unattachedDisk.Passwd,
"pci_slot": unattachedDisk.PciSlot,
"pool": unattachedDisk.Pool,
"purge_attempts": unattachedDisk.PurgeAttempts,
"purge_time": unattachedDisk.PurgeTime,
"reality_device_number": unattachedDisk.RealityDeviceNumber,
"reference_id": unattachedDisk.ReferenceID,
"res_id": unattachedDisk.ResID,
"res_name": unattachedDisk.ResName,
"role": unattachedDisk.Role,
"sep_id": unattachedDisk.SepID,
"size_max": unattachedDisk.SizeMax,
"size_used": unattachedDisk.SizeUsed,
"snapshots": flattenDiskSnapshotList(unattachedDisk.Snapshots),
"status": unattachedDisk.Status,
"tech_status": unattachedDisk.TechStatus,
"type": unattachedDisk.Type,
"vmid": unattachedDisk.VMID,
}
res = append(res, tmp)
}
return res
}
func dataSourceDiskListUnattachedRead(ctx context.Context, d *schema.ResourceData, m interface{}) diag.Diagnostics {
diskListUnattached, err := utilityDiskListUnattachedCheckPresence(ctx, d, m)
if err != nil {

View File

@@ -38,21 +38,19 @@ import (
"github.com/google/uuid"
"github.com/hashicorp/terraform-plugin-sdk/v2/diag"
"github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema"
"repository.basistech.ru/BASIS/decort-golang-sdk/pkg/cloudapi/disks"
"repository.basistech.ru/BASIS/terraform-provider-decort/internal/constants"
)
func dataSourceDiskSnapshotRead(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
if err != nil {
return diag.FromErr(err)
}
snapshots := disk.Snapshots
snapshot := Snapshot{}
var snapshot disks.ItemSnapshot
label := d.Get("label").(string)
for _, sn := range snapshots {
for _, sn := range disk.Snapshots {
if label == sn.Label {
snapshot = sn
break
@@ -64,11 +62,9 @@ func dataSourceDiskSnapshotRead(ctx context.Context, d *schema.ResourceData, m i
id := uuid.New()
d.SetId(id.String())
d.Set("timestamp", snapshot.TimeStamp)
d.Set("guid", snapshot.Guid)
d.Set("res_id", snapshot.ResId)
d.Set("snap_set_guid", snapshot.SnapSetGuid)
d.Set("snap_set_time", snapshot.SnapSetTime)
flattenDiskSnapshot(d, snapshot)
return nil
}

View File

@@ -43,11 +43,8 @@ import (
func dataSourceDiskSnapshotListRead(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
if err != nil {
return diag.FromErr(err)
}
id := uuid.New()

View File

@@ -42,7 +42,7 @@ import (
)
func dataSourceDiskListDeletedRead(ctx context.Context, d *schema.ResourceData, m interface{}) diag.Diagnostics {
diskList, err := utilityDiskListCheckPresence(ctx, d, m, disksListDeletedAPI)
diskList, err := utilityDiskListCheckPresence(ctx, d, m)
if err != nil {
return diag.FromErr(err)
}

View File

@@ -4,43 +4,106 @@ import (
"encoding/json"
"github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema"
"repository.basistech.ru/BASIS/decort-golang-sdk/pkg/cloudapi/disks"
"repository.basistech.ru/BASIS/terraform-provider-decort/internal/flattens"
)
func flattenDisk(d *schema.ResourceData, disk Disk) {
diskAcl, _ := json.Marshal(disk.Acl)
func flattenDiskSnapshot(d *schema.ResourceData, snapshot disks.ItemSnapshot) {
d.Set("timestamp", snapshot.TimeStamp)
d.Set("guid", snapshot.GUID)
d.Set("res_id", snapshot.ResID)
d.Set("snap_set_guid", snapshot.SnapSetGUID)
d.Set("snap_set_time", snapshot.SnapSetTime)
}
func flattenDiskListUnattached(ul disks.ListDisksUnattached) []map[string]interface{} {
res := make([]map[string]interface{}, 0)
for _, unattachedDisk := range ul {
unattachedDiskAcl, _ := json.Marshal(unattachedDisk.ACL)
tmp := map[string]interface{}{
"_ckey": unattachedDisk.CKey,
"_meta": flattens.FlattenMeta(unattachedDisk.Meta),
"account_id": unattachedDisk.AccountID,
"account_name": unattachedDisk.AccountName,
"acl": string(unattachedDiskAcl),
"boot_partition": unattachedDisk.BootPartition,
"created_time": unattachedDisk.CreatedTime,
"deleted_time": unattachedDisk.DeletedTime,
"desc": unattachedDisk.Description,
"destruction_time": unattachedDisk.DestructionTime,
"disk_path": unattachedDisk.DiskPath,
"gid": unattachedDisk.GID,
"guid": unattachedDisk.GUID,
"disk_id": unattachedDisk.ID,
"image_id": unattachedDisk.ImageID,
"images": unattachedDisk.Images,
"iotune": flattenIOTune(unattachedDisk.IOTune),
"iqn": unattachedDisk.IQN,
"login": unattachedDisk.Login,
"milestones": unattachedDisk.Milestones,
"disk_name": unattachedDisk.Name,
"order": unattachedDisk.Order,
"params": unattachedDisk.Params,
"parent_id": unattachedDisk.ParentID,
"passwd": unattachedDisk.Password,
"pci_slot": unattachedDisk.PCISlot,
"pool": unattachedDisk.Pool,
"purge_attempts": unattachedDisk.PurgeAttempts,
"purge_time": unattachedDisk.PurgeTime,
"reality_device_number": unattachedDisk.RealityDeviceNumber,
"reference_id": unattachedDisk.ReferenceID,
"res_id": unattachedDisk.ResID,
"res_name": unattachedDisk.ResName,
"role": unattachedDisk.Role,
"sep_id": unattachedDisk.SEPID,
"size_max": unattachedDisk.SizeMax,
"size_used": unattachedDisk.SizeUsed,
"snapshots": flattenDiskSnapshotList(unattachedDisk.Snapshots),
"status": unattachedDisk.Status,
"tech_status": unattachedDisk.TechStatus,
"type": unattachedDisk.Type,
"vmid": unattachedDisk.VMID,
}
res = append(res, tmp)
}
return res
}
func flattenDisk(d *schema.ResourceData, disk *disks.RecordDisk) {
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("boot_partition", disk.BootPartition)
d.Set("computes", flattenDiskComputes(disk.Computes))
d.Set("created_time", disk.CreatedTime)
d.Set("deleted_time", disk.DeletedTime)
d.Set("desc", disk.Desc)
d.Set("desc", disk.Description)
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_path", disk.DiskPath)
d.Set("gid", disk.GID)
// 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("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("parent_id", disk.ParentID)
// d.Set("passwd", disk.Passwd)
d.Set("pci_slot", disk.PCISlot)
d.Set("pool", disk.Pool)
d.Set("present_to", disk.PresentTo)
d.Set("purge_attempts", disk.PurgeAttempts)
// 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("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)
@@ -56,14 +119,14 @@ func flattenDisk(d *schema.ResourceData, disk Disk) {
d.Set("vmid", disk.VMID)
}
func flattenDiskSnapshotList(sl SnapshotList) []interface{} {
func flattenDiskSnapshotList(sl disks.ListSnapshots) []interface{} {
res := make([]interface{}, 0)
for _, snapshot := range sl {
temp := map[string]interface{}{
"guid": snapshot.Guid,
"guid": snapshot.GUID,
"label": snapshot.Label,
"res_id": snapshot.ResId,
"snap_set_guid": snapshot.SnapSetGuid,
"res_id": snapshot.ResID,
"snap_set_guid": snapshot.SnapSetGUID,
"snap_set_time": snapshot.SnapSetTime,
"timestamp": snapshot.TimeStamp,
}
@@ -73,80 +136,70 @@ func flattenDiskSnapshotList(sl SnapshotList) []interface{} {
return res
}
func flattenDiskList(dl DisksList) []map[string]interface{} {
func flattenDiskList(dl disks.ListDisks) []map[string]interface{} {
res := make([]map[string]interface{}, 0)
for _, disk := range dl {
diskAcl, _ := json.Marshal(disk.Acl)
diskAcl, _ := json.Marshal(disk.ACL)
temp := map[string]interface{}{
"account_id": disk.AccountID,
"account_name": disk.AccountName,
"acl": string(diskAcl),
"computes": flattenDiskComputes(disk.Computes),
"boot_partition": disk.BootPartition,
"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,
"present_to": disk.PresentTo,
"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,
"shareable": disk.Shareable,
"size_max": disk.SizeMax,
"size_used": disk.SizeUsed,
"snapshots": flattenDiskSnapshotList(disk.Snapshots),
"status": disk.Status,
"tech_status": disk.TechStatus,
"type": disk.Type,
"vmid": disk.VMID,
"account_id": disk.AccountID,
"account_name": disk.AccountName,
"acl": string(diskAcl),
"computes": flattenDiskComputes(disk.Computes),
"created_time": disk.CreatedTime,
"deleted_time": disk.DeletedTime,
"desc": disk.Description,
"destruction_time": disk.DestructionTime,
"devicename": disk.DeviceName,
"gid": disk.GID,
"disk_id": disk.ID,
"image_id": disk.ImageID,
"images": disk.Images,
"iotune": flattenIOTune(disk.IOTune),
"machine_id": disk.MachineID,
"machine_name": disk.MachineName,
"disk_name": disk.Name,
"order": disk.Order,
"params": disk.Params,
"parent_id": disk.ParentID,
"pci_slot": disk.PCISlot,
"pool": disk.Pool,
"present_to": disk.PresentTo,
"purge_time": disk.PurgeTime,
"res_id": disk.ResID,
"res_name": disk.ResName,
"role": disk.Role,
"sep_id": disk.SepID,
"sep_type": disk.SepType,
"shareable": disk.Shareable,
"size_max": disk.SizeMax,
"size_used": disk.SizeUsed,
"snapshots": flattenDiskSnapshotList(disk.Snapshots),
"status": disk.Status,
"tech_status": disk.TechStatus,
"type": disk.Type,
"vmid": disk.VMID,
}
res = append(res, temp)
}
return res
}
func flattenIOTune(iot IOTune) []map[string]interface{} {
func flattenIOTune(iot disks.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,
"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,
"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,
"write_iops_sec": iot.WriteIOPSSec,
"write_iops_sec_max": iot.WriteIOPSSecMax,
}
res = append(res, temp)

View File

@@ -1,181 +0,0 @@
/*
Copyright (c) 2019-2022 Digital Energy Cloud Solutions LLC. All Rights Reserved.
Authors:
Petr Krutov, <petr.krutov@digitalenergy.online>
Stanislav Solovev, <spsolovev@digitalenergy.online>
Kasim Baybikov, <kmbaybikov@basistech.ru>
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://repository.basistech.ru/BASIS/terraform-provider-decort
Please see README.md to learn where to place source code so that it
builds seamlessly.
Documentation: https://repository.basistech.ru/BASIS/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"`
Computes map[string]string `json:"computes"`
CreatedTime uint64 `json:"creationTime"`
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"`
PresentTo []int `json:"presentTo"`
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"`
Shareable bool `json:"shareable"`
SepID int `json:"sepId"` // NOTE: absent from compute/get output
SizeMax int `json:"sizeMax"`
SizeUsed float64 `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"`
}
type Pool struct {
Name string `json:"name"`
Types []string `json:"types"`
}
type PoolList []Pool
type TypeDetailed struct {
Pools []Pool `json:"pools"`
SepID int `json:"sepId"`
}
type TypesDetailedList []TypeDetailed
type TypesList []string
type Unattached struct {
Ckey string `json:"_ckey"`
Meta []interface{} `json:"_meta"`
AccountID int `json:"accountId"`
AccountName string `json:"accountName"`
Acl map[string]interface{} `json:"acl"`
BootPartition int `json:"bootPartition"`
CreatedTime int `json:"createdTime"`
DeletedTime int `json:"deletedTime"`
Desc string `json:"desc"`
DestructionTime int `json:"destructionTime"`
DiskPath string `json:"diskPath"`
GridID int `json:"gid"`
GUID int `json:"guid"`
ID int `json:"id"`
ImageID int `json:"imageId"`
Images []int `json:"images"`
IOTune IOTune `json:"iotune"`
IQN string `json:"iqn"`
Login string `json:"login"`
Milestones int `json:"milestones"`
Name string `json:"name"`
Order int `json:"order"`
Params string `json:"params"`
ParentID int `json:"parentId"`
Passwd string `json:"passwd"`
PciSlot int `json:"pciSlot"`
Pool string `json:"pool"`
PurgeAttempts int `json:"purgeAttempts"`
PurgeTime int `json:"purgeTime"`
RealityDeviceNumber int `json:"realityDeviceNumber"`
ReferenceID string `json:"referenceId"`
ResID string `json:"resId"`
ResName string `json:"resName"`
Role string `json:"role"`
SepID int `json:"sepId"`
SizeMax int `json:"sizeMax"`
SizeUsed float64 `json:"sizeUsed"`
Snapshots []Snapshot `json:"snapshots"`
Status string `json:"status"`
TechStatus string `json:"techStatus"`
Type string `json:"type"`
VMID int `json:"vmid"`
}
type UnattachedList []Unattached
type Pair struct {
intPort int
extPortStart int
}

View File

@@ -2,76 +2,35 @@ package disks
import (
"context"
"encoding/json"
"net/url"
"github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema"
"repository.basistech.ru/BASIS/decort-golang-sdk/pkg/cloudapi/account"
"repository.basistech.ru/BASIS/decort-golang-sdk/pkg/cloudapi/locations"
"repository.basistech.ru/BASIS/terraform-provider-decort/internal/controller"
)
func existAccountID(ctx context.Context, d *schema.ResourceData, m interface{}) (bool, error) {
c := m.(*controller.ControllerCfg)
accountId := uint64(d.Get("account_id").(int))
req := account.ListRequest{}
urlValues := &url.Values{}
accountList := []struct {
ID int `json:"id"`
}{}
accountListAPI := "/restmachine/cloudapi/account/list"
accountListRaw, err := c.DecortAPICall(ctx, "POST", accountListAPI, urlValues)
accountList, err := c.CloudAPI().Account().List(ctx, req)
if err != nil {
return false, err
}
err = json.Unmarshal([]byte(accountListRaw), &accountList)
if err != nil {
return false, err
}
haveAccount := false
myAccount := d.Get("account_id").(int)
for _, account := range accountList {
if account.ID == myAccount {
haveAccount = true
break
}
}
return haveAccount, nil
return len(accountList.FilterByID(accountId)) != 0, nil
}
func existGID(ctx context.Context, d *schema.ResourceData, m interface{}) (bool, error) {
c := m.(*controller.ControllerCfg)
gid := uint64(d.Get("gid").(int))
req := locations.ListRequest{}
urlValues := &url.Values{}
locationList := []struct {
GID int `json:"gid"`
}{}
locationsListAPI := "/restmachine/cloudapi/locations/list"
locationListRaw, err := c.DecortAPICall(ctx, "POST", locationsListAPI, urlValues)
locationList, err := c.CloudAPI().Locations().List(ctx, req)
if err != nil {
return false, err
}
err = json.Unmarshal([]byte(locationListRaw), &locationList)
if err != nil {
return false, err
}
haveGID := false
gid := d.Get("gid").(int)
for _, location := range locationList {
if location.GID == gid {
haveGID = true
break
}
}
return haveGID, nil
return len(locationList.FilterByGID(gid)) != 0, nil
}

View File

@@ -35,11 +35,11 @@ package disks
import (
"context"
"fmt"
"net/url"
"strconv"
"strings"
log "github.com/sirupsen/logrus"
"repository.basistech.ru/BASIS/decort-golang-sdk/pkg/cloudapi/disks"
"repository.basistech.ru/BASIS/terraform-provider-decort/internal/constants"
"repository.basistech.ru/BASIS/terraform-provider-decort/internal/controller"
"repository.basistech.ru/BASIS/terraform-provider-decort/internal/dc"
@@ -52,7 +52,7 @@ import (
func resourceDiskCreate(ctx context.Context, d *schema.ResourceData, m interface{}) diag.Diagnostics {
c := m.(*controller.ControllerCfg)
urlValues := &url.Values{}
req := disks.CreateRequest{}
haveAccount, err := existAccountID(ctx, d, m)
if err != nil {
@@ -70,83 +70,78 @@ func resourceDiskCreate(ctx context.Context, d *schema.ResourceData, m interface
return diag.Errorf("resourceDiskCreate: can't create Disk because GID %d is not allowed or does not exist", d.Get("gid").(int))
}
urlValues.Add("accountId", strconv.Itoa(d.Get("account_id").(int)))
urlValues.Add("gid", strconv.Itoa(d.Get("gid").(int)))
urlValues.Add("name", d.Get("disk_name").(string))
urlValues.Add("size", strconv.Itoa(d.Get("size_max").(int)))
req.AccountID = uint64(d.Get("account_id").(int))
req.GID = uint64(d.Get("gid").(int))
req.Name = d.Get("disk_name").(string)
req.Size = uint64(d.Get("size_max").(int))
if typeRaw, ok := d.GetOk("type"); ok {
urlValues.Add("type", strings.ToUpper(typeRaw.(string)))
req.Type = strings.ToUpper(typeRaw.(string))
} else {
urlValues.Add("type", "D")
req.Type = "D"
}
if sepId, ok := d.GetOk("sep_id"); ok {
urlValues.Add("sep_id", strconv.Itoa(sepId.(int)))
req.SEPID = uint64(sepId.(int))
}
if poolName, ok := d.GetOk("pool"); ok {
urlValues.Add("pool", poolName.(string))
req.Pool = poolName.(string)
}
argVal, argSet := d.GetOk("desc")
if argSet {
urlValues.Add("description", argVal.(string))
req.Description = argVal.(string)
}
diskId, err := c.DecortAPICall(ctx, "POST", disksCreateAPI, urlValues)
diskId, err := c.CloudAPI().Disks().Create(ctx, req)
if err != nil {
return diag.FromErr(err)
}
urlValues = &url.Values{}
d.SetId(diskId)
d.SetId(strconv.FormatUint(diskId, 10))
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)))
req := disks.LimitIORequest{
DiskID: diskId,
IOPS: uint64(iotune["total_iops_sec"].(int)),
ReadBytesSec: uint64(iotune["read_bytes_sec"].(int)),
ReadBytesSecMax: uint64(iotune["read_bytes_sec_max"].(int)),
ReadIOPSSec: uint64(iotune["read_iops_sec"].(int)),
ReadIOPSSecMax: uint64(iotune["read_iops_sec_max"].(int)),
SizeIOPSSec: uint64(iotune["size_iops_sec"].(int)),
TotalBytesSec: uint64(iotune["total_bytes_sec"].(int)),
TotalBytesSecMax: uint64(iotune["total_bytes_sec_max"].(int)),
TotalIOPSSecMax: uint64(iotune["total_iops_sec_max"].(int)),
TotalIOPSSec: uint64(iotune["total_iops_sec"].(int)),
WriteBytesSec: uint64(iotune["write_bytes_sec"].(int)),
WriteBytesSecMax: uint64(iotune["write_bytes_sec_max"].(int)),
WriteIOPSSec: uint64(iotune["write_iops_sec"].(int)),
WriteIOPSSecMax: uint64(iotune["write_iops_sec_max"].(int)),
}
_, err := c.DecortAPICall(ctx, "POST", disksIOLimitAPI, urlValues)
_, err := c.CloudAPI().Disks().LimitIO(ctx, req)
if err != nil {
return diag.FromErr(err)
}
urlValues = &url.Values{}
}
if shareable := d.Get("shareable"); shareable.(bool) == true {
urlValues.Add("diskId", diskId)
_, err := c.DecortAPICall(ctx, "POST", disksShareAPI, urlValues)
req := disks.ShareRequest{
DiskID: diskId,
}
_, err := c.CloudAPI().Disks().Share(ctx, req)
if err != nil {
return diag.FromErr(err)
}
urlValues = &url.Values{}
}
dgn := resourceDiskRead(ctx, d, m)
if dgn != nil {
return dgn
}
return nil
return resourceDiskRead(ctx, d, m)
}
func resourceDiskRead(ctx context.Context, d *schema.ResourceData, m interface{}) diag.Diagnostics {
urlValues := &url.Values{}
c := m.(*controller.ControllerCfg)
warnings := dc.Warnings{}
@@ -161,13 +156,21 @@ func resourceDiskRead(ctx context.Context, d *schema.ResourceData, m interface{}
switch disk.Status {
case status.Destroyed, status.Purged:
d.Set("disk_id", 0)
d.SetId("")
return resourceDiskCreate(ctx, d, m)
case status.Deleted:
hasChangeState = true
urlValues.Add("diskId", d.Id())
urlValues.Add("reason", d.Get("reason").(string))
req := disks.RestoreRequest{
DiskID: disk.ID,
}
_, err := c.DecortAPICall(ctx, "POST", disksRestoreAPI, urlValues)
if reason, ok := d.GetOk("reason"); ok {
req.Reason = reason.(string)
} else {
req.Reason = "Terraform automatic restore"
}
_, err := c.CloudAPI().Disks().Restore(ctx, req)
if err != nil {
warnings.Add(err)
}
@@ -188,7 +191,7 @@ func resourceDiskRead(ctx context.Context, d *schema.ResourceData, m interface{}
}
}
flattenDisk(d, *disk)
flattenDisk(d, disk)
return warnings.Get()
}
@@ -196,7 +199,6 @@ func resourceDiskRead(ctx context.Context, d *schema.ResourceData, m interface{}
func resourceDiskUpdate(ctx context.Context, d *schema.ResourceData, m interface{}) diag.Diagnostics {
c := m.(*controller.ControllerCfg)
warnings := dc.Warnings{}
urlValues := &url.Values{}
haveAccount, err := existAccountID(ctx, d, m)
if err != nil {
@@ -224,13 +226,21 @@ func resourceDiskUpdate(ctx context.Context, d *schema.ResourceData, m interface
switch disk.Status {
case status.Destroyed, status.Purged:
d.Set("disk_id", 0)
d.SetId("")
return resourceDiskCreate(ctx, d, m)
case status.Deleted:
hasChangeState = true
urlValues.Add("diskId", d.Id())
urlValues.Add("reason", d.Get("reason").(string))
req := disks.RestoreRequest{
DiskID: disk.ID,
}
_, err := c.DecortAPICall(ctx, "POST", disksRestoreAPI, urlValues)
if reason, ok := d.GetOk("reason"); ok {
req.Reason = reason.(string)
} else {
req.Reason = "Terraform automatic restore"
}
_, err := c.CloudAPI().Disks().Restore(ctx, req)
if err != nil {
warnings.Add(err)
}
@@ -256,68 +266,75 @@ func resourceDiskUpdate(ctx context.Context, d *schema.ResourceData, m interface
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", strconv.Itoa(newSize.(int)))
_, err := c.DecortAPICall(ctx, "POST", disksResizeAPI, urlValues)
req := disks.ResizeRequest{
DiskID: disk.ID,
Size: uint64(newSize.(int)),
}
_, err := c.CloudAPI().Disks().Resize(ctx, req)
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)
req := disks.RenameRequest{
DiskID: disk.ID,
Name: d.Get("disk_name").(string),
}
_, err := c.CloudAPI().Disks().Rename(ctx, req)
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)))
req := disks.LimitIORequest{
DiskID: disk.ID,
IOPS: uint64(iotune["total_iops_sec"].(int)),
ReadBytesSec: uint64(iotune["read_bytes_sec"].(int)),
ReadBytesSecMax: uint64(iotune["read_bytes_sec_max"].(int)),
ReadIOPSSec: uint64(iotune["read_iops_sec"].(int)),
ReadIOPSSecMax: uint64(iotune["read_iops_sec_max"].(int)),
SizeIOPSSec: uint64(iotune["size_iops_sec"].(int)),
TotalBytesSec: uint64(iotune["total_bytes_sec"].(int)),
TotalBytesSecMax: uint64(iotune["total_bytes_sec_max"].(int)),
TotalIOPSSecMax: uint64(iotune["total_iops_sec_max"].(int)),
TotalIOPSSec: uint64(iotune["total_iops_sec"].(int)),
WriteBytesSec: uint64(iotune["write_bytes_sec"].(int)),
WriteBytesSecMax: uint64(iotune["write_bytes_sec_max"].(int)),
WriteIOPSSec: uint64(iotune["write_iops_sec"].(int)),
WriteIOPSSecMax: uint64(iotune["write_iops_sec_max"].(int)),
}
_, err := c.DecortAPICall(ctx, "POST", disksIOLimitAPI, urlValues)
_, err := c.CloudAPI().Disks().LimitIO(ctx, req)
if err != nil {
return diag.FromErr(err)
}
urlValues = &url.Values{}
}
if d.HasChange("shareable") {
oldShare, newShare := d.GetChange("shareable")
urlValues = &url.Values{}
urlValues.Add("diskId", d.Id())
if oldShare.(bool) == false && newShare.(bool) == true {
_, err := c.DecortAPICall(ctx, "POST", disksShareAPI, urlValues)
req := disks.ShareRequest{DiskID: disk.ID}
_, err := c.CloudAPI().Disks().Share(ctx, req)
if err != nil {
return diag.FromErr(err)
}
}
if oldShare.(bool) == true && newShare.(bool) == false {
_, err := c.DecortAPICall(ctx, "POST", disksUnshareAPI, urlValues)
req := disks.UnshareRequest{DiskID: disk.ID}
_, err := c.CloudAPI().Disks().Unshare(ctx, req)
if err != nil {
return diag.FromErr(err)
}
@@ -336,17 +353,22 @@ func resourceDiskDelete(ctx context.Context, d *schema.ResourceData, m interface
if disk.Status == status.Destroyed || disk.Status == status.Purged {
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))
req := disks.DeleteRequest{
DiskID: disk.ID,
Detach: d.Get("detach").(bool),
Permanently: d.Get("permanently").(bool),
Reason: d.Get("reason").(string),
}
c := m.(*controller.ControllerCfg)
_, err = c.DecortAPICall(ctx, "POST", disksDeleteAPI, params)
_, err = c.CloudAPI().Disks().Delete(ctx, req)
if err != nil {
return diag.FromErr(err)
}
d.SetId("")
return nil
}
@@ -531,11 +553,11 @@ func resourceDiskSchemaMake() map[string]*schema.Schema {
Type: schema.TypeString,
Computed: true,
},
"boot_partition": {
Type: schema.TypeInt,
Computed: true,
Description: "Number of disk partitions",
},
// "boot_partition": {
// Type: schema.TypeInt,
// Computed: true,
// Description: "Number of disk partitions",
// },
"computes": {
Type: schema.TypeList,
Computed: true,
@@ -572,16 +594,16 @@ func resourceDiskSchemaMake() map[string]*schema.Schema {
Computed: true,
Description: "Name of the device",
},
"disk_path": {
Type: schema.TypeString,
Computed: true,
Description: "Disk path",
},
"guid": {
Type: schema.TypeInt,
Computed: true,
Description: "Disk ID on the storage side",
},
// "disk_path": {
// Type: schema.TypeString,
// Computed: true,
// Description: "Disk path",
// },
// "guid": {
// Type: schema.TypeInt,
// Computed: true,
// Description: "Disk ID on the storage side",
// },
"image_id": {
Type: schema.TypeInt,
Computed: true,
@@ -595,22 +617,21 @@ func resourceDiskSchemaMake() map[string]*schema.Schema {
},
Description: "IDs of images using the disk",
},
"iqn": {
Type: schema.TypeString,
Computed: true,
Description: "Disk IQN",
},
"login": {
Type: schema.TypeString,
Computed: true,
Description: "Login to access the disk",
},
"milestones": {
Type: schema.TypeInt,
Computed: true,
Description: "Milestones",
},
// "iqn": {
// Type: schema.TypeString,
// Computed: true,
// Description: "Disk IQN",
// },
// "login": {
// Type: schema.TypeString,
// Computed: true,
// Description: "Login to access the disk",
// },
// "milestones": {
// Type: schema.TypeInt,
// Computed: true,
// Description: "Milestones",
// },
"order": {
Type: schema.TypeInt,
Computed: true,
@@ -626,36 +647,36 @@ func resourceDiskSchemaMake() map[string]*schema.Schema {
Computed: true,
Description: "ID of the parent disk",
},
"passwd": {
Type: schema.TypeString,
Computed: true,
Description: "Password to access the disk",
},
// "passwd": {
// Type: schema.TypeString,
// Computed: true,
// Description: "Password to access the disk",
// },
"pci_slot": {
Type: schema.TypeInt,
Computed: true,
Description: "ID of the pci slot to which the disk is connected",
},
"purge_attempts": {
Type: schema.TypeInt,
Computed: true,
Description: "Number of deletion attempts",
},
// "purge_attempts": {
// Type: schema.TypeInt,
// Computed: true,
// Description: "Number of deletion attempts",
// },
"purge_time": {
Type: schema.TypeInt,
Computed: true,
Description: "Time of the last deletion attempt",
},
"reality_device_number": {
Type: schema.TypeInt,
Computed: true,
Description: "Reality device number",
},
"reference_id": {
Type: schema.TypeString,
Computed: true,
Description: "ID of the reference to the disk",
},
// "reality_device_number": {
// Type: schema.TypeInt,
// Computed: true,
// Description: "Reality device number",
// },
// "reference_id": {
// Type: schema.TypeString,
// Computed: true,
// Description: "ID of the reference to the disk",
// },
"res_id": {
Type: schema.TypeString,
Computed: true,

View File

@@ -34,18 +34,16 @@ package disks
import (
"context"
"net/url"
"strconv"
"github.com/hashicorp/terraform-plugin-sdk/v2/diag"
"github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema"
log "github.com/sirupsen/logrus"
"repository.basistech.ru/BASIS/decort-golang-sdk/pkg/cloudapi/disks"
"repository.basistech.ru/BASIS/terraform-provider-decort/internal/constants"
"repository.basistech.ru/BASIS/terraform-provider-decort/internal/controller"
)
func resourceDiskSnapshotCreate(ctx context.Context, d *schema.ResourceData, m interface{}) diag.Diagnostics {
urlValues := &url.Values{}
c := m.(*controller.ControllerCfg)
disk, err := utilityDiskCheckPresence(ctx, d, m)
@@ -54,7 +52,7 @@ func resourceDiskSnapshotCreate(ctx context.Context, d *schema.ResourceData, m i
}
snapshots := disk.Snapshots
snapshot := Snapshot{}
snapshot := disks.ItemSnapshot{}
label := d.Get("label").(string)
for _, sn := range snapshots {
if label == sn.Label {
@@ -65,30 +63,31 @@ func resourceDiskSnapshotCreate(ctx context.Context, d *schema.ResourceData, m i
if label != snapshot.Label {
return diag.Errorf("Snapshot with label \"%v\" not found", label)
}
if rollback := d.Get("rollback").(bool); rollback {
urlValues.Add("diskId", strconv.Itoa(d.Get("disk_id").(int)))
urlValues.Add("label", label)
urlValues.Add("timestamp", strconv.Itoa(d.Get("timestamp").(int)))
req := disks.SnapshotRollbackRequest{
DiskID: disk.ID,
Label: label,
TimeStamp: uint64(d.Get("timestamp").(int)),
}
log.Debugf("resourceDiskCreate: Snapshot rollback with label", label)
_, err := c.DecortAPICall(ctx, "POST", disksSnapshotRollbackAPI, urlValues)
_, err := c.CloudAPI().Disks().SnapshotRollback(ctx, req)
if err != nil {
return diag.FromErr(err)
}
urlValues = &url.Values{}
}
return resourceDiskSnapshotRead(ctx, d, m)
}
func resourceDiskSnapshotRead(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
if err != nil {
return diag.FromErr(err)
}
snapshots := disk.Snapshots
snapshot := Snapshot{}
snapshot := disks.ItemSnapshot{}
label := d.Get("label").(string)
for _, sn := range snapshots {
if label == sn.Label {
@@ -100,27 +99,20 @@ func resourceDiskSnapshotRead(ctx context.Context, d *schema.ResourceData, m int
return diag.Errorf("Snapshot with label \"%v\" not found", label)
}
d.SetId(d.Get("label").(string))
d.Set("timestamp", snapshot.TimeStamp)
d.Set("guid", snapshot.Guid)
d.Set("res_id", snapshot.ResId)
d.Set("snap_set_guid", snapshot.SnapSetGuid)
d.Set("snap_set_time", snapshot.SnapSetTime)
flattenDiskSnapshot(d, snapshot)
return nil
}
func resourceDiskSnapshotUpdate(ctx context.Context, d *schema.ResourceData, m interface{}) diag.Diagnostics {
urlValues := &url.Values{}
c := m.(*controller.ControllerCfg)
disk, err := utilityDiskCheckPresence(ctx, d, m)
if disk == nil {
if err != nil {
return diag.FromErr(err)
}
return nil
if err != nil {
return diag.FromErr(err)
}
snapshots := disk.Snapshots
snapshot := Snapshot{}
snapshot := disks.ItemSnapshot{}
label := d.Get("label").(string)
for _, sn := range snapshots {
if label == sn.Label {
@@ -128,19 +120,23 @@ func resourceDiskSnapshotUpdate(ctx context.Context, d *schema.ResourceData, m i
break
}
}
if label != snapshot.Label {
return diag.Errorf("Snapshot with label \"%v\" not found", label)
}
if d.HasChange("rollback") && d.Get("rollback").(bool) == true {
urlValues.Add("diskId", strconv.Itoa(d.Get("disk_id").(int)))
urlValues.Add("label", label)
urlValues.Add("timestamp", strconv.Itoa(d.Get("timestamp").(int)))
req := disks.SnapshotRollbackRequest{
DiskID: disk.ID,
Label: label,
TimeStamp: uint64(d.Get("timestamp").(int)),
}
log.Debugf("resourceDiskUpdtae: Snapshot rollback with label", label)
_, err := c.DecortAPICall(ctx, "POST", disksSnapshotRollbackAPI, urlValues)
_, err := c.CloudAPI().Disks().SnapshotRollback(ctx, req)
if err != nil {
return diag.FromErr(err)
}
urlValues = &url.Values{}
}
return resourceDiskSnapshotRead(ctx, d, m)
@@ -150,22 +146,23 @@ func resourceDiskSnapshotDelete(ctx context.Context, d *schema.ResourceData, m i
c := m.(*controller.ControllerCfg)
disk, err := utilityDiskCheckPresence(ctx, d, m)
if disk == nil { //if disk not exits, can't call snapshotDelete
if err != nil {
d.SetId("")
if err != nil {
return diag.FromErr(err)
}
return nil
return diag.FromErr(err)
}
params := &url.Values{}
params.Add("diskId", strconv.Itoa(d.Get("disk_id").(int)))
params.Add("label", d.Get("label").(string))
req := disks.SnapshotDeleteRequest{
DiskID: disk.ID,
Label: d.Get("label").(string),
}
_, err = c.DecortAPICall(ctx, "POST", disksSnapshotDeleteAPI, params)
_, err = c.CloudAPI().Disks().SnapshotDelete(ctx, req)
if err != nil {
return diag.FromErr(err)
}
d.SetId("")
return nil
}

View File

@@ -34,39 +34,33 @@ package disks
import (
"context"
"encoding/json"
"net/url"
"strconv"
log "github.com/sirupsen/logrus"
"repository.basistech.ru/BASIS/decort-golang-sdk/pkg/cloudapi/disks"
"repository.basistech.ru/BASIS/terraform-provider-decort/internal/controller"
"github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema"
)
func utilityDiskCheckPresence(ctx context.Context, d *schema.ResourceData, m interface{}) (*Disk, error) {
func utilityDiskCheckPresence(ctx context.Context, d *schema.ResourceData, m interface{}) (*disks.RecordDisk, error) {
c := m.(*controller.ControllerCfg)
urlValues := &url.Values{}
disk := &Disk{}
req := disks.GetRequest{}
if d.Get("disk_id") != nil {
if d.Get("disk_id").(int) == 0 {
urlValues.Add("diskId", d.Id())
id, _ := strconv.ParseUint(d.Id(), 10, 64)
req.DiskID = id
} else {
urlValues.Add("diskId", strconv.Itoa(d.Get("disk_id").(int)))
req.DiskID = uint64(d.Get("disk_id").(int))
}
} else {
urlValues.Add("diskId", strconv.Itoa(d.Get("disk_id").(int)))
id, _ := strconv.ParseUint(d.Id(), 10, 64)
req.DiskID = id
}
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)
disk, err := c.CloudAPI().Disks().Get(ctx, req)
if err != nil {
return nil, err
}

View File

@@ -34,42 +34,34 @@ package disks
import (
"context"
"encoding/json"
"net/url"
"strconv"
"strings"
"repository.basistech.ru/BASIS/terraform-provider-decort/internal/controller"
log "github.com/sirupsen/logrus"
"repository.basistech.ru/BASIS/decort-golang-sdk/pkg/cloudapi/disks"
"repository.basistech.ru/BASIS/terraform-provider-decort/internal/controller"
"github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema"
)
func utilityDiskListCheckPresence(ctx context.Context, d *schema.ResourceData, m interface{}, api string) (DisksList, error) {
diskList := DisksList{}
func utilityDiskListCheckPresence(ctx context.Context, d *schema.ResourceData, m interface{}) (disks.ListDisks, error) {
c := m.(*controller.ControllerCfg)
urlValues := &url.Values{}
req := disks.ListRequest{}
if page, ok := d.GetOk("page"); ok {
urlValues.Add("page", strconv.Itoa(page.(int)))
req.Page = uint64(page.(int))
}
if size, ok := d.GetOk("size"); ok {
urlValues.Add("size", strconv.Itoa(size.(int)))
req.Size = uint64(size.(int))
}
if diskType, ok := d.GetOk("type"); ok {
urlValues.Add("type", strings.ToUpper(diskType.(string)))
req.Type = strings.ToUpper(diskType.(string))
}
if accountId, ok := d.GetOk("accountId"); ok {
urlValues.Add("accountId", strconv.Itoa(accountId.(int)))
req.AccountID = uint64(accountId.(int))
}
log.Debugf("utilityDiskListCheckPresence: load disk list")
diskListRaw, err := c.DecortAPICall(ctx, "POST", api, urlValues)
if err != nil {
return nil, err
}
err = json.Unmarshal([]byte(diskListRaw), &diskList)
diskList, err := c.CloudAPI().Disks().List(ctx, req)
if err != nil {
return nil, err
}

View File

@@ -0,0 +1,26 @@
package disks
import (
"context"
"github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema"
log "github.com/sirupsen/logrus"
"repository.basistech.ru/BASIS/decort-golang-sdk/pkg/cloudapi/disks"
"repository.basistech.ru/BASIS/terraform-provider-decort/internal/controller"
)
func utilityDiskListUnattachedCheckPresence(ctx context.Context, d *schema.ResourceData, m interface{}) (disks.ListDisksUnattached, error) {
c := m.(*controller.ControllerCfg)
req := disks.ListUnattachedRequest{}
if accountId, ok := d.GetOk("accountId"); ok {
req.AccountID = uint64(accountId.(int))
}
log.Debugf("utilityDiskListUnattachedCheckPresence: load disk Unattached list")
unattachedList, err := c.CloudAPI().Disks().ListUnattached(ctx, req)
if err != nil {
return nil, err
}
return unattachedList, nil
}

View File

@@ -34,26 +34,21 @@ package disks
import (
"context"
"encoding/json"
"net/url"
"github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema"
"repository.basistech.ru/BASIS/terraform-provider-decort/internal/controller"
log "github.com/sirupsen/logrus"
"repository.basistech.ru/BASIS/decort-golang-sdk/pkg/cloudapi/disks"
"repository.basistech.ru/BASIS/terraform-provider-decort/internal/controller"
)
func utilityDiskListTypesDetailedCheckPresence(ctx context.Context, d *schema.ResourceData, m interface{}) (TypesDetailedList, error) {
listTypesDetailed := TypesDetailedList{}
func utilityDiskListTypesDetailedCheckPresence(ctx context.Context, d *schema.ResourceData, m interface{}) ([]interface{}, error) {
c := m.(*controller.ControllerCfg)
urlValues := &url.Values{}
urlValues.Add("detailed", "true")
log.Debugf("utilityDiskListTypesDetailedCheckPresence: load disk list Types Detailed")
diskListRaw, err := c.DecortAPICall(ctx, "POST", disksListTypesAPI, urlValues)
if err != nil {
return nil, err
req := disks.ListTypesRequest{
Detailed: true,
}
err = json.Unmarshal([]byte(diskListRaw), &listTypesDetailed)
log.Debugf("utilityDiskListTypesDetailedCheckPresence: load disk list Types Detailed")
listTypesDetailed, err := c.CloudAPI().Disks().ListTypes(ctx, req)
if err != nil {
return nil, err
}

View File

@@ -34,26 +34,21 @@ package disks
import (
"context"
"encoding/json"
"net/url"
"github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema"
"repository.basistech.ru/BASIS/terraform-provider-decort/internal/controller"
log "github.com/sirupsen/logrus"
"repository.basistech.ru/BASIS/decort-golang-sdk/pkg/cloudapi/disks"
"repository.basistech.ru/BASIS/terraform-provider-decort/internal/controller"
)
func utilityDiskListTypesCheckPresence(ctx context.Context, d *schema.ResourceData, m interface{}) (TypesList, error) {
typesList := TypesList{}
func utilityDiskListTypesCheckPresence(ctx context.Context, d *schema.ResourceData, m interface{}) ([]interface{}, error) {
c := m.(*controller.ControllerCfg)
urlValues := &url.Values{}
urlValues.Add("detailed", "false")
log.Debugf("utilityDiskListTypesCheckPresence: load disk list Types Detailed")
diskListRaw, err := c.DecortAPICall(ctx, "POST", disksListTypesAPI, urlValues)
if err != nil {
return nil, err
req := disks.ListTypesRequest{
Detailed: false,
}
err = json.Unmarshal([]byte(diskListRaw), &typesList)
log.Debugf("utilityDiskListTypesCheckPresence: load disk list Types Detailed")
typesList, err := c.CloudAPI().Disks().ListTypes(ctx, req)
if err != nil {
return nil, err
}

View File

@@ -1,38 +0,0 @@
/*
Copyright (c) 2019-2022 Digital Energy Cloud Solutions LLC. All Rights Reserved.
Authors:
Petr Krutov, <petr.krutov@digitalenergy.online>
Stanislav Solovev, <spsolovev@digitalenergy.online>
Kasim Baybikov, <kmbaybikov@basistech.ru>
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://repository.basistech.ru/BASIS/terraform-provider-decort
Please see README.md to learn where to place source code so that it
builds seamlessly.
Documentation: https://repository.basistech.ru/BASIS/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"

View File

@@ -34,12 +34,11 @@ package extnet
import (
"context"
"strconv"
"github.com/google/uuid"
"github.com/hashicorp/terraform-plugin-sdk/v2/diag"
"github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema"
"repository.basistech.ru/BASIS/terraform-provider-decort/internal/constants"
"repository.basistech.ru/BASIS/terraform-provider-decort/internal/flattens"
)
func dataSourceExtnetRead(ctx context.Context, d *schema.ResourceData, m interface{}) diag.Diagnostics {
@@ -48,77 +47,12 @@ func dataSourceExtnetRead(ctx context.Context, d *schema.ResourceData, m interfa
return diag.FromErr(err)
}
id := uuid.New()
d.SetId(id.String())
d.Set("ckey", e.CKey)
d.Set("meta", flattens.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))
d.SetId(strconv.FormatUint(e.ID, 10))
flattenExtnet(d, e)
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": {
@@ -164,6 +98,10 @@ func dataSourceExtnetSchemaMake() map[string]*schema.Schema {
Type: schema.TypeInt,
Computed: true,
},
"e_burst": {
Type: schema.TypeInt,
Computed: true,
},
"guid": {
Type: schema.TypeString,
Computed: true,
@@ -193,8 +131,29 @@ func dataSourceExtnetSchemaMake() map[string]*schema.Schema {
"excluded": {
Type: schema.TypeList,
Computed: true,
Elem: &schema.Schema{
Type: schema.TypeString,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"client_type": {
Type: schema.TypeString,
Computed: true,
},
"mac": {
Type: schema.TypeString,
Computed: true,
},
"ip": {
Type: schema.TypeString,
Computed: true,
},
"type": {
Type: schema.TypeString,
Computed: true,
},
"vm_id": {
Type: schema.TypeInt,
Computed: true,
},
},
},
},
"free_ips": {

View File

@@ -41,37 +41,6 @@ import (
"repository.basistech.ru/BASIS/terraform-provider-decort/internal/constants"
)
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(ctx context.Context, d *schema.ResourceData, m interface{}) diag.Diagnostics {
extnetComputesList, err := utilityExtnetComputesListCheckPresence(ctx, d, m)
if err != nil {

View File

@@ -41,19 +41,6 @@ import (
"repository.basistech.ru/BASIS/terraform-provider-decort/internal/constants"
)
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(ctx context.Context, d *schema.ResourceData, m interface{}) diag.Diagnostics {
extnetList, err := utilityExtnetListCheckPresence(ctx, d, m)
if err != nil {

View File

@@ -0,0 +1,137 @@
package extnet
import (
"github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema"
"repository.basistech.ru/BASIS/decort-golang-sdk/pkg/cloudapi/extnet"
"repository.basistech.ru/BASIS/terraform-provider-decort/internal/flattens"
)
func flattenExtnet(d *schema.ResourceData, e *extnet.RecordExtNet) {
d.Set("ckey", e.CKey)
d.Set("meta", flattens.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.Description)
d.Set("dns", e.DNS)
d.Set("excluded", flattenExcluded(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))
}
func flattenExcluded(ex []extnet.Excluded) []map[string]interface{} {
res := make([]map[string]interface{}, 0)
for _, item := range ex {
temp := map[string]interface{}{
"client_type": item.ClientType,
"mac": item.MAC,
"ip": item.IP,
"type": item.Type,
"vm_id": item.VMID,
}
res = append(res, temp)
}
return res
}
func flattenExtnetReservations(ers extnet.ListReservations) []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.Description,
"ip": er.IP,
"mac": er.MAC,
"type": er.Type,
"vm_id": er.VMID,
}
res = append(res, temp)
}
return res
}
func flattenExtnetDefaultQos(edqos extnet.QOS) []map[string]interface{} {
res := make([]map[string]interface{}, 0)
temp := map[string]interface{}{
"e_rate": edqos.ERate,
"e_burst": edqos.EBurst,
"guid": edqos.GUID,
"in_burst": edqos.InBurst,
"in_rate": edqos.InRate,
}
res = append(res, temp)
return res
}
func flattenExtnetVNFS(evnfs extnet.VNFs) []map[string]interface{} {
res := make([]map[string]interface{}, 0)
temp := map[string]interface{}{
"dhcp": evnfs.DHCP,
}
res = append(res, temp)
return res
}
func flattenExtnetsComputes(ecs extnet.ListExtNetExtends) []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 extnet.ListExtNetComputes) []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 flattenExtnetList(el extnet.ListExtNets) []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
}

View File

@@ -1,112 +0,0 @@
/*
Copyright (c) 2019-2022 Digital Energy Cloud Solutions LLC. All Rights Reserved.
Authors:
Petr Krutov, <petr.krutov@digitalenergy.online>
Stanislav Solovev, <spsolovev@digitalenergy.online>
Kasim Baybikov, <kmbaybikov@basistech.ru>
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://repository.basistech.ru/BASIS/terraform-provider-decort
Please see README.md to learn where to place source code so that it
builds seamlessly.
Documentation: https://repository.basistech.ru/BASIS/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"`
}

View File

@@ -34,30 +34,22 @@ package extnet
import (
"context"
"encoding/json"
"net/url"
"strconv"
log "github.com/sirupsen/logrus"
"repository.basistech.ru/BASIS/decort-golang-sdk/pkg/cloudapi/extnet"
"repository.basistech.ru/BASIS/terraform-provider-decort/internal/controller"
"github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema"
)
func utilityExtnetCheckPresence(ctx context.Context, d *schema.ResourceData, m interface{}) (*ExtnetDetailed, error) {
extnet := &ExtnetDetailed{}
func utilityExtnetCheckPresence(ctx context.Context, d *schema.ResourceData, m interface{}) (*extnet.RecordExtNet, error) {
c := m.(*controller.ControllerCfg)
urlValues := &url.Values{}
urlValues.Add("net_id", strconv.Itoa(d.Get("net_id").(int)))
log.Debugf("utilityExtnetCheckPresence")
extnetRaw, err := c.DecortAPICall(ctx, "POST", extnetGetAPI, urlValues)
if err != nil {
return nil, err
req := extnet.GetRequest{
NetID: uint64(d.Get("net_id").(int)),
}
err = json.Unmarshal([]byte(extnetRaw), &extnet)
log.Debugf("utilityExtnetCheckPresence")
extnet, err := c.CloudAPI().ExtNet().Get(ctx, req)
if err != nil {
return nil, err
}

View File

@@ -34,30 +34,22 @@ package extnet
import (
"context"
"encoding/json"
"net/url"
"strconv"
log "github.com/sirupsen/logrus"
"repository.basistech.ru/BASIS/decort-golang-sdk/pkg/cloudapi/extnet"
"repository.basistech.ru/BASIS/terraform-provider-decort/internal/controller"
"github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema"
)
func utilityExtnetComputesListCheckPresence(ctx context.Context, d *schema.ResourceData, m interface{}) (ExtnetComputesList, error) {
extnetComputesList := ExtnetComputesList{}
func utilityExtnetComputesListCheckPresence(ctx context.Context, d *schema.ResourceData, m interface{}) (extnet.ListExtNetComputes, error) {
c := m.(*controller.ControllerCfg)
urlValues := &url.Values{}
urlValues.Add("accountId", strconv.Itoa(d.Get("account_id").(int)))
log.Debugf("utilityExtnetComputesListCheckPresence")
extnetComputesListRaw, err := c.DecortAPICall(ctx, "POST", extnetListComputesAPI, urlValues)
if err != nil {
return nil, err
req := extnet.ListComputesRequest{
AccountID: uint64(d.Get("account_id").(int)),
}
err = json.Unmarshal([]byte(extnetComputesListRaw), &extnetComputesList)
log.Debugf("utilityExtnetComputesListCheckPresence")
extnetComputesList, err := c.CloudAPI().ExtNet().ListComputes(ctx, req)
if err != nil {
return nil, err
}

View File

@@ -34,7 +34,7 @@ package extnet
import (
"context"
"net/url"
"strconv"
log "github.com/sirupsen/logrus"
"repository.basistech.ru/BASIS/terraform-provider-decort/internal/controller"
@@ -42,13 +42,12 @@ import (
func utilityExtnetDefaultCheckPresence(ctx context.Context, m interface{}) (string, error) {
c := m.(*controller.ControllerCfg)
urlValues := &url.Values{}
log.Debugf("utilityExtnetDefaultCheckPresence")
res, err := c.DecortAPICall(ctx, "POST", extnetGetDefaultAPI, urlValues)
res, err := c.CloudAPI().ExtNet().GetDefault(ctx)
if err != nil {
return "", err
}
return res, nil
return strconv.FormatUint(res, 10), nil
}

View File

@@ -34,38 +34,30 @@ package extnet
import (
"context"
"encoding/json"
"net/url"
"strconv"
log "github.com/sirupsen/logrus"
"repository.basistech.ru/BASIS/decort-golang-sdk/pkg/cloudapi/extnet"
"repository.basistech.ru/BASIS/terraform-provider-decort/internal/controller"
"github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema"
)
func utilityExtnetListCheckPresence(ctx context.Context, d *schema.ResourceData, m interface{}) (ExtnetList, error) {
extnetList := ExtnetList{}
func utilityExtnetListCheckPresence(ctx context.Context, d *schema.ResourceData, m interface{}) (extnet.ListExtNets, error) {
c := m.(*controller.ControllerCfg)
urlValues := &url.Values{}
req := extnet.ListRequest{}
if accountId, ok := d.GetOk("account_id"); ok {
urlValues.Add("accountId", strconv.Itoa(accountId.(int)))
req.AccountID = uint64(accountId.(int))
}
if page, ok := d.GetOk("page"); ok {
urlValues.Add("page", strconv.Itoa(page.(int)))
req.Page = uint64(page.(int))
}
if size, ok := d.GetOk("size"); ok {
urlValues.Add("size", strconv.Itoa(size.(int)))
req.Size = uint64(size.(int))
}
log.Debugf("utilityExtnetListCheckPresence")
extnetListRaw, err := c.DecortAPICall(ctx, "POST", extnetListAPI, urlValues)
if err != nil {
return nil, err
}
err = json.Unmarshal([]byte(extnetListRaw), &extnetList)
extnetList, err := c.CloudAPI().ExtNet().List(ctx, req)
if err != nil {
return nil, err
}

View File

@@ -1,41 +0,0 @@
/*
Copyright (c) 2019-2022 Digital Energy Cloud Solutions LLC. All Rights Reserved.
Authors:
Petr Krutov, <petr.krutov@digitalenergy.online>
Stanislav Solovev, <spsolovev@digitalenergy.online>
Kasim Baybikov, <kmbaybikov@basistech.ru>
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://repository.basistech.ru/BASIS/terraform-provider-decort
Please see README.md to learn where to place source code so that it
builds seamlessly.
Documentation: https://repository.basistech.ru/BASIS/terraform-provider-decort/wiki
*/
package image
const imageCreateAPI = "/restmachine/cloudapi/image/create"
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"

View File

@@ -41,34 +41,6 @@ import (
"repository.basistech.ru/BASIS/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 {

View File

@@ -1,13 +1,16 @@
package image
import "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema"
import (
"github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema"
"repository.basistech.ru/BASIS/decort-golang-sdk/pkg/cloudapi/image"
)
func flattenHistory(history []History) []map[string]interface{} {
func flattenHistory(history []image.History) []map[string]interface{} {
temp := make([]map[string]interface{}, 0)
for _, item := range history {
t := map[string]interface{}{
"id": item.Id,
"guid": item.Guid,
"id": item.ID,
"guid": item.GUID,
"timestamp": item.Timestamp,
}
@@ -16,24 +19,24 @@ func flattenHistory(history []History) []map[string]interface{} {
return temp
}
func flattenImage(d *schema.ResourceData, img *ImageExtend) {
func flattenImage(d *schema.ResourceData, img *image.RecordImage) {
d.Set("unc_path", img.UNCPath)
d.Set("ckey", img.CKey)
d.Set("account_id", img.AccountId)
d.Set("acl", img.Acl)
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("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("gid", img.GID)
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("image_id", img.ID)
d.Set("last_modified", img.LastModified)
d.Set("link_to", img.LinkTo)
d.Set("milestones", img.Milestones)
@@ -43,9 +46,9 @@ func flattenImage(d *schema.ResourceData, img *ImageExtend) {
d.Set("provider_name", img.ProviderName)
d.Set("purge_attempts", img.PurgeAttempts)
d.Set("present_to", img.PresentTo)
d.Set("res_id", img.ResId)
d.Set("res_id", img.ResID)
d.Set("rescuecd", img.RescueCD)
d.Set("sep_id", img.SepId)
d.Set("sep_id", img.SepID)
d.Set("shared_with", img.SharedWith)
d.Set("size", img.Size)
d.Set("status", img.Status)
@@ -54,3 +57,31 @@ func flattenImage(d *schema.ResourceData, img *ImageExtend) {
d.Set("username", img.Username)
d.Set("version", img.Version)
}
func flattenImageList(il image.ListImages) []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
}

View File

@@ -79,7 +79,7 @@ func dataSourceImageExtendSchemaMake() map[string]*schema.Schema {
Computed: true,
},
"deleted_time": {
Type: schema.TypeString,
Type: schema.TypeInt,
Computed: true,
},
"desc": {

View File

@@ -1,150 +0,0 @@
/*
Copyright (c) 2019-2022 Digital Energy Cloud Solutions LLC. All Rights Reserved.
Authors:
Petr Krutov, <petr.krutov@digitalenergy.online>
Stanislav Solovev, <spsolovev@digitalenergy.online>
Kasim Baybikov, <kmbaybikov@basistech.ru>
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://repository.basistech.ru/BASIS/terraform-provider-decort
Please see README.md to learn where to place source code so that it
builds seamlessly.
Documentation: https://repository.basistech.ru/BASIS/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"`
PresentTo []int `json:"presentTo"`
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"`
}

View File

@@ -2,76 +2,35 @@ package image
import (
"context"
"encoding/json"
"net/url"
"github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema"
"repository.basistech.ru/BASIS/decort-golang-sdk/pkg/cloudapi/account"
"repository.basistech.ru/BASIS/decort-golang-sdk/pkg/cloudapi/locations"
"repository.basistech.ru/BASIS/terraform-provider-decort/internal/controller"
)
func existAccountID(ctx context.Context, d *schema.ResourceData, m interface{}) (bool, error) {
c := m.(*controller.ControllerCfg)
accountId := uint64(d.Get("account_id").(int))
req := account.ListRequest{}
urlValues := &url.Values{}
accountList := []struct {
ID int `json:"id"`
}{}
accountListAPI := "/restmachine/cloudapi/account/list"
accountListRaw, err := c.DecortAPICall(ctx, "POST", accountListAPI, urlValues)
accounts, err := c.CloudAPI().Account().List(ctx, req)
if err != nil {
return false, err
}
err = json.Unmarshal([]byte(accountListRaw), &accountList)
if err != nil {
return false, err
}
haveAccount := false
myAccount := d.Get("account_id").(int)
for _, account := range accountList {
if account.ID == myAccount {
haveAccount = true
break
}
}
return haveAccount, nil
return len(accounts.FilterByID(accountId)) != 0, nil
}
func existGID(ctx context.Context, d *schema.ResourceData, m interface{}) (bool, error) {
c := m.(*controller.ControllerCfg)
gid := uint64(d.Get("gid").(int))
req := locations.ListRequest{}
urlValues := &url.Values{}
locationList := []struct {
GID int `json:"gid"`
}{}
locationsListAPI := "/restmachine/cloudapi/locations/list"
locationListRaw, err := c.DecortAPICall(ctx, "POST", locationsListAPI, urlValues)
locationList, err := c.CloudAPI().Locations().List(ctx, req)
if err != nil {
return false, err
}
err = json.Unmarshal([]byte(locationListRaw), &locationList)
if err != nil {
return false, err
}
haveGID := false
gid := d.Get("gid").(int)
for _, location := range locationList {
if location.GID == gid {
haveGID = true
break
}
}
return haveGID, nil
return len(locationList.FilterByGID(gid)) != 0, nil
}

View File

@@ -34,13 +34,12 @@ package image
import (
"context"
"encoding/json"
"net/url"
"strconv"
"github.com/hashicorp/terraform-plugin-sdk/v2/diag"
"github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema"
log "github.com/sirupsen/logrus"
"repository.basistech.ru/BASIS/decort-golang-sdk/pkg/cloudapi/image"
"repository.basistech.ru/BASIS/terraform-provider-decort/internal/constants"
"repository.basistech.ru/BASIS/terraform-provider-decort/internal/controller"
"repository.basistech.ru/BASIS/terraform-provider-decort/internal/status"
@@ -70,68 +69,55 @@ func resourceImageCreate(ctx context.Context, d *schema.ResourceData, m interfac
}
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("type").(string))
req := image.CreateRequest{}
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
req.Name = d.Get("name").(string)
req.URL = d.Get("url").(string)
req.GID = uint64(d.Get("gid").(int))
req.BootType = d.Get("boot_type").(string)
req.ImageType = d.Get("type").(string)
drivers := []string{}
for _, driver := range d.Get("drivers").([]interface{}) {
drivers = append(drivers, driver.(string))
}
temp = "[" + temp + "]"
urlValues.Add("drivers", temp)
req.Drivers = drivers
if hotresize, ok := d.GetOk("hot_resize"); ok {
urlValues.Add("hotresize", strconv.FormatBool(hotresize.(bool)))
req.HotResize = hotresize.(bool)
}
if username, ok := d.GetOk("username"); ok {
urlValues.Add("username", username.(string))
req.Username = username.(string)
}
if password, ok := d.GetOk("password"); ok {
urlValues.Add("password", password.(string))
req.Password = password.(string)
}
if accountId, ok := d.GetOk("account_id"); ok {
urlValues.Add("accountId", strconv.Itoa(accountId.(int)))
req.AccountID = uint64(accountId.(int))
}
if usernameDL, ok := d.GetOk("username_dl"); ok {
urlValues.Add("usernameDL", usernameDL.(string))
req.UsernameDL = usernameDL.(string)
}
if passwordDL, ok := d.GetOk("password_dl"); ok {
urlValues.Add("passwordDL", passwordDL.(string))
req.PasswordDL = passwordDL.(string)
}
if sepId, ok := d.GetOk("sep_id"); ok {
urlValues.Add("sepId", strconv.Itoa(sepId.(int)))
req.SEPID = uint64(sepId.(int))
}
if poolName, ok := d.GetOk("pool_name"); ok {
urlValues.Add("poolName", poolName.(string))
req.Pool = poolName.(string)
}
if architecture, ok := d.GetOk("architecture"); ok {
urlValues.Add("architecture", architecture.(string))
req.Architecture = architecture.(string)
}
res, err := c.DecortAPICall(ctx, "POST", imageCreateAPI, urlValues)
imageId, err := c.CloudAPI().Image().Create(ctx, req)
if err != nil {
return diag.FromErr(err)
}
i := make([]interface{}, 0)
err = json.Unmarshal([]byte(res), &i)
if err != nil {
return diag.FromErr(err)
}
imageId := strconv.Itoa(int(i[1].(float64)))
// end innovation
d.SetId(imageId)
d.SetId(strconv.FormatUint(imageId, 10))
d.Set("image_id", imageId)
_, err = utilityImageCheckPresence(ctx, d, m)
@@ -139,12 +125,7 @@ func resourceImageCreate(ctx context.Context, d *schema.ResourceData, m interfac
return diag.FromErr(err)
}
diagnostics := resourceImageRead(ctx, d, m)
if diagnostics != nil {
return diagnostics
}
return nil
return resourceImageRead(ctx, d, m)
}
func resourceImageRead(ctx context.Context, d *schema.ResourceData, m interface{}) diag.Diagnostics {
@@ -174,38 +155,39 @@ 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(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)
_, err := utilityImageCheckPresence(ctx, d, m)
if err != nil {
return diag.FromErr(err)
}
c := m.(*controller.ControllerCfg)
req := image.DeleteRequest{
ImageID: uint64(d.Get("image_id").(int)),
}
if permanently, ok := d.GetOk("permanently"); ok {
req.Permanently = permanently.(bool)
}
_, err = c.CloudAPI().Image().Delete(ctx, req)
if err != nil {
return diag.FromErr(err)
}
d.SetId("")
return nil
}
func resourceImageEditName(ctx context.Context, d *schema.ResourceData, m interface{}) error {
func resourceImageRename(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)
req := image.RenameRequest{
ImageID: uint64(d.Get("image_id").(int)),
Name: d.Get("name").(string),
}
_, err := c.CloudAPI().Image().Rename(ctx, req)
if err != nil {
return err
}
@@ -214,7 +196,7 @@ func resourceImageEditName(ctx context.Context, d *schema.ResourceData, m interf
}
func resourceImageUpdate(ctx context.Context, d *schema.ResourceData, m interface{}) diag.Diagnostics {
log.Debugf("resourceImageEdit: called for %s, id: %s", d.Get("name").(string), d.Id())
log.Debugf("resourceImageUpdate: called for %s, id: %s", d.Get("name").(string), d.Id())
haveGID, err := existGID(ctx, d, m)
if err != nil {
@@ -255,7 +237,7 @@ func resourceImageUpdate(ctx context.Context, d *schema.ResourceData, m interfac
}
if d.HasChange("name") {
err := resourceImageEditName(ctx, d, m)
err := resourceImageRename(ctx, d, m)
if err != nil {
return diag.FromErr(err)
}

View File

@@ -34,30 +34,31 @@ package image
import (
"context"
"net/url"
"strconv"
"github.com/hashicorp/terraform-plugin-sdk/v2/diag"
"github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema"
log "github.com/sirupsen/logrus"
"repository.basistech.ru/BASIS/decort-golang-sdk/pkg/cloudapi/image"
"repository.basistech.ru/BASIS/terraform-provider-decort/internal/constants"
"repository.basistech.ru/BASIS/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)))
req := image.CreateVirtualRequest{
Name: d.Get("name").(string),
TargetID: uint64(d.Get("target_id").(int)),
}
imageId, err := c.DecortAPICall(ctx, "POST", imageCreateVirtualAPI, urlValues)
imageId, err := c.CloudAPI().Image().CreateVirtual(ctx, req)
if err != nil {
return diag.FromErr(err)
}
d.SetId(imageId)
d.SetId(strconv.FormatUint(imageId, 10))
d.Set("image_id", imageId)
_, err = utilityImageCheckPresence(ctx, d, m)
@@ -65,19 +66,14 @@ func resourceImageVirtualCreate(ctx context.Context, d *schema.ResourceData, m i
return diag.FromErr(err)
}
diagnostics := resourceImageRead(ctx, d, m)
if diagnostics != nil {
return diagnostics
}
return nil
return resourceImageRead(ctx, d, m)
}
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())
func resourceImageVirtualUpdate(ctx context.Context, d *schema.ResourceData, m interface{}) diag.Diagnostics {
log.Debugf("resourceImageUpdate: called for %s, id: %s", d.Get("name").(string), d.Id())
if d.HasChange("name") {
err := resourceImageEditName(ctx, d, m)
err := resourceImageRename(ctx, d, m)
if err != nil {
return diag.FromErr(err)
}
@@ -96,10 +92,12 @@ func resourceImageVirtualEdit(ctx context.Context, d *schema.ResourceData, m int
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)
req := image.LinkRequest{
ImageID: uint64(d.Get("image_id").(int)),
TargetID: uint64(d.Get("link_to").(int)),
}
_, err := c.CloudAPI().Image().Link(ctx, req)
if err != nil {
return err
}
@@ -113,7 +111,7 @@ func ResourceImageVirtual() *schema.Resource {
CreateContext: resourceImageVirtualCreate,
ReadContext: resourceImageRead,
UpdateContext: resourceImageVirtualEdit,
UpdateContext: resourceImageVirtualUpdate,
DeleteContext: resourceImageDelete,
Importer: &schema.ResourceImporter{

View File

@@ -34,43 +34,32 @@ package image
import (
"context"
"encoding/json"
"errors"
"fmt"
"net/url"
"strconv"
"github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema"
"repository.basistech.ru/BASIS/decort-golang-sdk/pkg/cloudapi/image"
"repository.basistech.ru/BASIS/terraform-provider-decort/internal/controller"
)
func utilityImageCheckPresence(ctx context.Context, d *schema.ResourceData, m interface{}) (*ImageExtend, error) {
func utilityImageCheckPresence(ctx context.Context, d *schema.ResourceData, m interface{}) (*image.RecordImage, error) {
c := m.(*controller.ControllerCfg)
urlValues := &url.Values{}
req := image.GetRequest{}
if (strconv.Itoa(d.Get("image_id").(int))) != "0" {
urlValues.Add("imageId", strconv.Itoa(d.Get("image_id").(int)))
req.ImageID = uint64(d.Get("image_id").(int))
} else {
urlValues.Add("imageId", d.Id())
id, _ := strconv.ParseUint(d.Id(), 10, 64)
req.ImageID = id
}
if showAll, ok := d.GetOk("show_all"); ok {
urlValues.Add("page", strconv.FormatBool(showAll.(bool)))
req.ShowAll = showAll.(bool)
}
resp, err := c.DecortAPICall(ctx, "POST", imageGetAPI, urlValues)
image, err := c.CloudAPI().Image().Get(ctx, req)
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
}

View File

@@ -34,39 +34,31 @@ package image
import (
"context"
"encoding/json"
"net/url"
"strconv"
"repository.basistech.ru/BASIS/terraform-provider-decort/internal/controller"
log "github.com/sirupsen/logrus"
"repository.basistech.ru/BASIS/decort-golang-sdk/pkg/cloudapi/image"
"repository.basistech.ru/BASIS/terraform-provider-decort/internal/controller"
"github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema"
)
func utilityImageListCheckPresence(ctx context.Context, d *schema.ResourceData, m interface{}) (ImageList, error) {
imageList := ImageList{}
func utilityImageListCheckPresence(ctx context.Context, d *schema.ResourceData, m interface{}) (image.ListImages, error) {
c := m.(*controller.ControllerCfg)
urlValues := &url.Values{}
req := image.ListRequest{}
if accountId, ok := d.GetOk("account_id"); ok {
urlValues.Add("accountId", strconv.Itoa(accountId.(int)))
req.AccountID = uint64(accountId.(int))
}
if page, ok := d.GetOk("page"); ok {
urlValues.Add("page", strconv.Itoa(page.(int)))
req.Page = uint64(page.(int))
}
if size, ok := d.GetOk("size"); ok {
urlValues.Add("size", strconv.Itoa(size.(int)))
req.Size = uint64(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)
imageList, err := c.CloudAPI().Image().List(ctx, req)
if err != nil {
return nil, err
}

View File

@@ -1,56 +0,0 @@
/*
Copyright (c) 2019-2022 Digital Energy Cloud Solutions LLC. All Rights Reserved.
Authors:
Petr Krutov, <petr.krutov@digitalenergy.online>
Stanislav Solovev, <spsolovev@digitalenergy.online>
Kasim Baybikov, <kmbaybikov@basistech.ru>
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://repository.basistech.ru/BASIS/terraform-provider-decort
Please see README.md to learn where to place source code so that it
builds seamlessly.
Documentation: https://repository.basistech.ru/BASIS/terraform-provider-decort/wiki
*/
package k8s
const (
K8sCreateAPI = "/restmachine/cloudapi/k8s/create"
K8sGetAPI = "/restmachine/cloudapi/k8s/get"
K8sUpdateAPI = "/restmachine/cloudapi/k8s/update"
K8sDeleteAPI = "/restmachine/cloudapi/k8s/delete"
K8sListAPI = "/restmachine/cloudapi/k8s/list"
K8sListDeletedAPI = "/restmachine/cloudapi/k8s/listDeleted"
K8sRestoreAPI = "/restmachine/cloudapi/k8s/restore"
K8sEnableAPI = "/restmachine/cloudapi/k8s/enable"
K8sWgCreateAPI = "/restmachine/cloudapi/k8s/workersGroupAdd"
K8sWgDeleteAPI = "/restmachine/cloudapi/k8s/workersGroupDelete"
K8sWorkerAddAPI = "/restmachine/cloudapi/k8s/workerAdd"
K8sWorkerDeleteAPI = "/restmachine/cloudapi/k8s/deleteWorkerFromGroup"
K8sGetConfigAPI = "/restmachine/cloudapi/k8s/getConfig"
LbGetAPI = "/restmachine/cloudapi/lb/get"
AsyncTaskGetAPI = "/restmachine/cloudapi/tasks/get"
)

View File

@@ -34,52 +34,53 @@ package k8s
import (
"context"
"encoding/json"
"net/url"
"strconv"
"github.com/hashicorp/terraform-plugin-sdk/v2/diag"
"github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema"
log "github.com/sirupsen/logrus"
"repository.basistech.ru/BASIS/decort-golang-sdk/pkg/cloudapi/compute"
"repository.basistech.ru/BASIS/decort-golang-sdk/pkg/cloudapi/k8s"
"repository.basistech.ru/BASIS/decort-golang-sdk/pkg/cloudapi/lb"
"repository.basistech.ru/BASIS/terraform-provider-decort/internal/constants"
"repository.basistech.ru/BASIS/terraform-provider-decort/internal/controller"
log "github.com/sirupsen/logrus"
"repository.basistech.ru/BASIS/terraform-provider-decort/internal/service/cloudapi/kvmvm"
)
func dataSourceK8sRead(ctx context.Context, d *schema.ResourceData, m interface{}) diag.Diagnostics {
k8s, err := utilityDataK8sCheckPresence(ctx, d, m)
cluster, err := utilityDataK8sCheckPresence(ctx, d, m)
if err != nil {
return diag.FromErr(err)
}
d.SetId(strconv.FormatUint(k8s.ID, 10))
d.SetId(strconv.FormatUint(cluster.ID, 10))
k8sList, err := utilityK8sListCheckPresence(ctx, d, m, K8sListAPI)
k8sList, err := utilityK8sListCheckPresence(ctx, d, m)
if err != nil {
d.SetId("")
return diag.FromErr(err)
}
curK8s := K8SItem{}
curK8s := k8s.ItemK8SCluster{}
for _, k8sCluster := range k8sList {
if k8sCluster.ID == k8s.ID {
if k8sCluster.ID == cluster.ID {
curK8s = k8sCluster
}
}
if curK8s.ID == 0 {
return diag.Errorf("Cluster with id %d not found in List clusters", k8s.ID)
return diag.Errorf("Cluster with id %d not found in List clusters", cluster.ID)
}
d.Set("vins_id", curK8s.VINSID)
masterComputeList := make([]kvmvm.ComputeGetResp, 0, len(k8s.K8SGroups.Masters.DetailedInfo))
workersComputeList := make([]kvmvm.ComputeGetResp, 0, len(k8s.K8SGroups.Workers))
for _, masterNode := range k8s.K8SGroups.Masters.DetailedInfo {
masterComputeList := make([]compute.RecordCompute, 0, len(cluster.K8SGroups.Masters.DetailedInfo))
workersComputeList := make([]compute.RecordCompute, 0, len(cluster.K8SGroups.Workers))
for _, masterNode := range cluster.K8SGroups.Masters.DetailedInfo {
compute, err := utilityComputeCheckPresence(ctx, d, m, masterNode.ID)
if err != nil {
return diag.FromErr(err)
}
masterComputeList = append(masterComputeList, *compute)
}
for _, worker := range k8s.K8SGroups.Workers {
for _, worker := range cluster.K8SGroups.Workers {
for _, info := range worker.DetailedInfo {
compute, err := utilityComputeCheckPresence(ctx, d, m, info.ID)
if err != nil {
@@ -90,29 +91,27 @@ func dataSourceK8sRead(ctx context.Context, d *schema.ResourceData, m interface{
}
c := m.(*controller.ControllerCfg)
urlValues := &url.Values{}
urlValues.Add("k8sId", d.Id())
kubeconfig, err := c.DecortAPICall(ctx, "POST", K8sGetConfigAPI, urlValues)
k8sId, _ := strconv.ParseUint(d.Id(), 10, 64)
getConfigReq := k8s.GetConfigRequest{K8SID: k8sId}
kubeconfig, err := c.CloudAPI().K8S().GetConfig(ctx, getConfigReq)
if err != nil {
log.Warnf("could not get kubeconfig: %v", err)
}
d.Set("kubeconfig", kubeconfig)
urlValues = &url.Values{}
urlValues.Add("lbId", strconv.FormatUint(k8s.LBID, 10))
resp, err := c.DecortAPICall(ctx, "POST", LbGetAPI, urlValues)
getLbReq := lb.GetRequest{LBID: cluster.LBID}
lb, err := c.CloudAPI().LB().Get(ctx, getLbReq)
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)
flattenK8sData(d, *k8s, masterComputeList, workersComputeList)
flattenK8sData(d, *cluster, masterComputeList, workersComputeList)
return nil
}

View File

@@ -42,7 +42,7 @@ import (
)
func dataSourceK8sListRead(ctx context.Context, d *schema.ResourceData, m interface{}) diag.Diagnostics {
k8sList, err := utilityK8sListCheckPresence(ctx, d, m, K8sListAPI)
k8sList, err := utilityK8sListCheckPresence(ctx, d, m)
if err != nil {
d.SetId("")
return diag.FromErr(err)

View File

@@ -42,7 +42,7 @@ import (
)
func dataSourceK8sListDeletedRead(ctx context.Context, d *schema.ResourceData, m interface{}) diag.Diagnostics {
k8sList, err := utilityK8sListCheckPresence(ctx, d, m, K8sListDeletedAPI)
k8sList, err := utilityK8sListDeletedCheckPresence(ctx, d, m)
if err != nil {
d.SetId("")
return diag.FromErr(err)

View File

@@ -34,40 +34,14 @@ package k8s
import (
"context"
"encoding/json"
"net/url"
"strconv"
"github.com/hashicorp/terraform-plugin-sdk/v2/diag"
"github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema"
"repository.basistech.ru/BASIS/decort-golang-sdk/pkg/cloudapi/compute"
"repository.basistech.ru/BASIS/terraform-provider-decort/internal/constants"
"repository.basistech.ru/BASIS/terraform-provider-decort/internal/controller"
"repository.basistech.ru/BASIS/terraform-provider-decort/internal/service/cloudapi/kvmvm"
)
func utilityK8sWgListCheckPresence(ctx context.Context, d *schema.ResourceData, m interface{}) (K8SGroupList, 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
}
return k8s.K8SGroups.Workers, nil
}
func dataSourceK8sWgListRead(ctx context.Context, d *schema.ResourceData, m interface{}) diag.Diagnostics {
wgList, err := utilityK8sWgListCheckPresence(ctx, d, m)
if err != nil {
@@ -76,9 +50,9 @@ func dataSourceK8sWgListRead(ctx context.Context, d *schema.ResourceData, m inte
d.SetId(strconv.Itoa(d.Get("k8s_id").(int)))
workersComputeList := make(map[uint64][]kvmvm.ComputeGetResp)
workersComputeList := make(map[uint64][]compute.RecordCompute)
for _, worker := range wgList {
workersComputeList[worker.ID] = make([]kvmvm.ComputeGetResp, 0, len(worker.DetailedInfo))
workersComputeList[worker.ID] = make([]compute.RecordCompute, 0, len(worker.DetailedInfo))
for _, info := range worker.DetailedInfo {
compute, err := utilityComputeCheckPresence(ctx, d, m, info.ID)
if err != nil {

View File

@@ -34,10 +34,11 @@ package k8s
import (
"github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema"
"repository.basistech.ru/BASIS/terraform-provider-decort/internal/service/cloudapi/kvmvm"
"repository.basistech.ru/BASIS/decort-golang-sdk/pkg/cloudapi/compute"
"repository.basistech.ru/BASIS/decort-golang-sdk/pkg/cloudapi/k8s"
)
func flattenAclList(aclList ACLList) []map[string]interface{} {
func flattenAclList(aclList k8s.ListACL) []map[string]interface{} {
res := make([]map[string]interface{}, 0)
for _, acl := range aclList {
temp := map[string]interface{}{
@@ -53,7 +54,7 @@ func flattenAclList(aclList ACLList) []map[string]interface{} {
return res
}
func flattenAcl(acl ACLGroup) []map[string]interface{} {
func flattenAcl(acl k8s.RecordACL) []map[string]interface{} {
res := make([]map[string]interface{}, 0)
temp := map[string]interface{}{
"account_acl": flattenAclList(acl.AccountACL),
@@ -65,11 +66,11 @@ func flattenAcl(acl ACLGroup) []map[string]interface{} {
return res
}
func flattenInterfaces(interfaces []kvmvm.InterfaceRecord) []map[string]interface{} {
func flattenInterfaces(interfaces compute.ListInterfaces) []map[string]interface{} {
res := make([]map[string]interface{}, 0)
for _, interfaceCompute := range interfaces {
temp := map[string]interface{}{
"def_gw": interfaceCompute.DefaultGW,
"def_gw": interfaceCompute.DefGW,
"ip_address": interfaceCompute.IPAddress,
}
res = append(res, temp)
@@ -78,7 +79,7 @@ func flattenInterfaces(interfaces []kvmvm.InterfaceRecord) []map[string]interfac
return res
}
func flattenDetailedInfo(detailedInfoList DetailedInfoList, computes []kvmvm.ComputeGetResp) []map[string]interface{} {
func flattenDetailedInfo(detailedInfoList k8s.ListDetailedInfo, computes []compute.RecordCompute) []map[string]interface{} {
res := make([]map[string]interface{}, 0)
if computes != nil {
for i, detailedInfo := range detailedInfoList {
@@ -88,8 +89,8 @@ func flattenDetailedInfo(detailedInfoList DetailedInfoList, computes []kvmvm.Com
"status": detailedInfo.Status,
"tech_status": detailedInfo.TechStatus,
"interfaces": flattenInterfaces(computes[i].Interfaces),
"natable_vins_ip": computes[i].NatableVinsIP,
"natable_vins_network": computes[i].NatableVinsNet,
"natable_vins_ip": computes[i].NatableVINSIP,
"natable_vins_network": computes[i].NatableVINSNetwork,
}
res = append(res, temp)
}
@@ -108,7 +109,7 @@ func flattenDetailedInfo(detailedInfoList DetailedInfoList, computes []kvmvm.Com
return res
}
func flattenMasterGroup(mastersGroup MasterGroup, masters []kvmvm.ComputeGetResp) []map[string]interface{} {
func flattenMasterGroup(mastersGroup k8s.MasterGroup, masters []compute.RecordCompute) []map[string]interface{} {
res := make([]map[string]interface{}, 0)
temp := map[string]interface{}{
"cpu": mastersGroup.CPU,
@@ -124,7 +125,7 @@ func flattenMasterGroup(mastersGroup MasterGroup, masters []kvmvm.ComputeGetResp
return res
}
func flattenK8sGroup(k8SGroupList K8SGroupList, workers []kvmvm.ComputeGetResp) []map[string]interface{} {
func flattenK8sGroup(k8SGroupList k8s.ListK8SGroups, workers []compute.RecordCompute) []map[string]interface{} {
res := make([]map[string]interface{}, 0)
for _, k8sGroup := range k8SGroupList {
temp := map[string]interface{}{
@@ -146,7 +147,7 @@ func flattenK8sGroup(k8SGroupList K8SGroupList, workers []kvmvm.ComputeGetResp)
return res
}
func flattenK8sGroups(k8sGroups K8SGroups, masters []kvmvm.ComputeGetResp, workers []kvmvm.ComputeGetResp) []map[string]interface{} {
func flattenK8sGroups(k8sGroups k8s.RecordK8SGroups, masters []compute.RecordCompute, workers []compute.RecordCompute) []map[string]interface{} {
res := make([]map[string]interface{}, 0)
temp := map[string]interface{}{
"masters": flattenMasterGroup(k8sGroups.Masters, masters),
@@ -156,30 +157,30 @@ func flattenK8sGroups(k8sGroups K8SGroups, masters []kvmvm.ComputeGetResp, worke
return res
}
func flattenK8sData(d *schema.ResourceData, k8s K8SRecord, masters []kvmvm.ComputeGetResp, workers []kvmvm.ComputeGetResp) {
d.Set("acl", flattenAcl(k8s.ACL))
d.Set("account_id", k8s.AccountID)
d.Set("account_name", k8s.AccountName)
d.Set("bservice_id", k8s.BServiceID)
d.Set("k8sci_id", k8s.CIID)
d.Set("created_by", k8s.CreatedBy)
d.Set("created_time", k8s.CreatedTime)
d.Set("deleted_by", k8s.DeletedBy)
d.Set("deleted_time", k8s.DeletedTime)
d.Set("k8s_ci_name", k8s.K8CIName)
d.Set("masters", flattenMasterGroup(k8s.K8SGroups.Masters, masters))
d.Set("workers", flattenK8sGroup(k8s.K8SGroups.Workers, workers))
d.Set("lb_id", k8s.LBID)
d.Set("name", k8s.Name)
d.Set("rg_id", k8s.RGID)
d.Set("rg_name", k8s.RGName)
d.Set("status", k8s.Status)
d.Set("tech_status", k8s.TechStatus)
d.Set("updated_by", k8s.UpdatedBy)
d.Set("updated_time", k8s.UpdatedTime)
func flattenK8sData(d *schema.ResourceData, cluster k8s.RecordK8S, masters []compute.RecordCompute, workers []compute.RecordCompute) {
d.Set("acl", flattenAcl(cluster.ACL))
d.Set("account_id", cluster.AccountID)
d.Set("account_name", cluster.AccountName)
d.Set("bservice_id", cluster.BServiceID)
d.Set("k8sci_id", cluster.CIID)
d.Set("created_by", cluster.CreatedBy)
d.Set("created_time", cluster.CreatedTime)
d.Set("deleted_by", cluster.DeletedBy)
d.Set("deleted_time", cluster.DeletedTime)
d.Set("k8s_ci_name", cluster.K8CIName)
d.Set("masters", flattenMasterGroup(cluster.K8SGroups.Masters, masters))
d.Set("workers", flattenK8sGroup(cluster.K8SGroups.Workers, workers))
d.Set("lb_id", cluster.LBID)
d.Set("name", cluster.Name)
d.Set("rg_id", cluster.RGID)
d.Set("rg_name", cluster.RGName)
d.Set("status", cluster.Status)
d.Set("tech_status", cluster.TechStatus)
d.Set("updated_by", cluster.UpdatedBy)
d.Set("updated_time", cluster.UpdatedTime)
}
func flattenServiceAccount(serviceAccount ServiceAccount) []map[string]interface{} {
func flattenServiceAccount(serviceAccount k8s.RecordServiceAccount) []map[string]interface{} {
res := make([]map[string]interface{}, 0)
temp := map[string]interface{}{
"guid": serviceAccount.GUID,
@@ -190,7 +191,7 @@ func flattenServiceAccount(serviceAccount ServiceAccount) []map[string]interface
return res
}
func flattenWorkersGroup(workersGroups K8SGroupList) []map[string]interface{} {
func flattenWorkersGroup(workersGroups k8s.ListK8SGroups) []map[string]interface{} {
res := make([]map[string]interface{}, 0)
for _, worker := range workersGroups {
temp := map[string]interface{}{
@@ -211,11 +212,7 @@ func flattenWorkersGroup(workersGroups K8SGroupList) []map[string]interface{} {
return res
}
func flattenConfig(config interface{}) map[string]interface{} {
return config.(map[string]interface{})
}
func flattenK8sItems(k8sItems K8SList) []map[string]interface{} {
func flattenK8sItems(k8sItems k8s.ListK8SClusters) []map[string]interface{} {
res := make([]map[string]interface{}, 0)
for _, item := range k8sItems {
temp := map[string]interface{}{
@@ -252,11 +249,11 @@ func flattenK8sItems(k8sItems K8SList) []map[string]interface{} {
return res
}
func flattenK8sList(d *schema.ResourceData, k8sItems K8SList) {
func flattenK8sList(d *schema.ResourceData, k8sItems k8s.ListK8SClusters) {
d.Set("items", flattenK8sItems(k8sItems))
}
func flattenResourceK8s(d *schema.ResourceData, k8s K8SRecord, masters []kvmvm.ComputeGetResp, workers []kvmvm.ComputeGetResp) {
func flattenResourceK8s(d *schema.ResourceData, k8s k8s.RecordK8S, masters []compute.RecordCompute, workers []compute.RecordCompute) {
wg_name := k8s.K8SGroups.Workers[0].Name
d.Set("acl", flattenAcl(k8s.ACL))
@@ -282,9 +279,10 @@ func flattenResourceK8s(d *schema.ResourceData, k8s K8SRecord, masters []kvmvm.C
d.Set("updated_by", k8s.UpdatedBy)
d.Set("updated_time", k8s.UpdatedTime)
d.Set("default_wg_id", k8s.K8SGroups.Workers[0].ID)
d.Set("network_plugin", k8s.NetworkPlugin)
}
func flattenWg(d *schema.ResourceData, wg K8SGroup, computes []kvmvm.ComputeGetResp) {
func flattenWg(d *schema.ResourceData, wg k8s.ItemK8SGroup, computes []compute.RecordCompute) {
d.Set("annotations", wg.Annotations)
d.Set("cpu", wg.CPU)
d.Set("detailed_info", flattenDetailedInfo(wg.DetailedInfo, computes))
@@ -297,7 +295,7 @@ func flattenWg(d *schema.ResourceData, wg K8SGroup, computes []kvmvm.ComputeGetR
d.Set("taints", wg.Taints)
}
func flattenWgList(wgList K8SGroupList, computesMap map[uint64][]kvmvm.ComputeGetResp) []map[string]interface{} {
func flattenWgList(wgList k8s.ListK8SGroups, computesMap map[uint64][]compute.RecordCompute) []map[string]interface{} {
res := make([]map[string]interface{}, 0)
for _, wg := range wgList {
computes := computesMap[wg.ID]
@@ -320,6 +318,6 @@ func flattenWgList(wgList K8SGroupList, computesMap map[uint64][]kvmvm.ComputeGe
return res
}
func flattenItemsWg(d *schema.ResourceData, wgList K8SGroupList, computes map[uint64][]kvmvm.ComputeGetResp) {
func flattenItemsWg(d *schema.ResourceData, wgList k8s.ListK8SGroups, computes map[uint64][]compute.RecordCompute) {
d.Set("items", flattenWgList(wgList, computes))
}

View File

@@ -87,21 +87,18 @@ func nodeK8sSubresourceSchemaMake() map[string]*schema.Schema {
"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.",
},
}

View File

@@ -2,142 +2,68 @@ package k8s
import (
"context"
"encoding/json"
"net/url"
"github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema"
"repository.basistech.ru/BASIS/decort-golang-sdk/pkg/cloudapi/extnet"
"repository.basistech.ru/BASIS/decort-golang-sdk/pkg/cloudapi/k8ci"
"repository.basistech.ru/BASIS/decort-golang-sdk/pkg/cloudapi/k8s"
"repository.basistech.ru/BASIS/decort-golang-sdk/pkg/cloudapi/rg"
"repository.basistech.ru/BASIS/terraform-provider-decort/internal/controller"
)
func existK8sID(ctx context.Context, d *schema.ResourceData, m interface{}) (bool, error) {
c := m.(*controller.ControllerCfg)
urlValues := &url.Values{}
k8sID := uint64(d.Get("k8s_id").(int))
req := k8s.ListRequest{}
k8sList := []struct {
ID int `json:"id"`
}{}
k8sListAPI := "/restmachine/cloudapi/k8s/list"
k8sListRaw, err := c.DecortAPICall(ctx, "POST", k8sListAPI, urlValues)
k8sList, err := c.CloudAPI().K8S().List(ctx, req)
if err != nil {
return false, err
}
err = json.Unmarshal([]byte(k8sListRaw), &k8sList)
if err != nil {
return false, err
}
haveK8s := false
k8sID := d.Get("k8s_id").(int)
for _, k8s := range k8sList {
if k8s.ID == k8sID {
haveK8s = true
break
}
}
return haveK8s, nil
return len(k8sList.FilterByID(k8sID)) != 0, nil
}
func existK8sCIID(ctx context.Context, d *schema.ResourceData, m interface{}) (bool, error) {
c := m.(*controller.ControllerCfg)
urlValues := &url.Values{}
k8sciID := uint64(d.Get("k8sci_id").(int))
req := k8ci.ListRequest{}
k8sciList := []struct {
ID int `json:"id"`
}{}
k8sciListAPI := "/restmachine/cloudapi/k8ci/list"
k8sciListRaw, err := c.DecortAPICall(ctx, "POST", k8sciListAPI, urlValues)
k8sciList, err := c.CloudAPI().K8CI().List(ctx, req)
if err != nil {
return false, err
}
err = json.Unmarshal([]byte(k8sciListRaw), &k8sciList)
if err != nil {
return false, err
}
haveK8sCI := false
k8sciID := d.Get("k8sci_id").(int)
for _, k8ci := range k8sciList {
if k8ci.ID == k8sciID {
haveK8sCI = true
break
}
}
return haveK8sCI, nil
return len(k8sciList.FilterByID(k8sciID)) != 0, nil
}
func existRGID(ctx context.Context, d *schema.ResourceData, m interface{}) (bool, error) {
c := m.(*controller.ControllerCfg)
urlValues := &url.Values{}
rgID := uint64(d.Get("rg_id").(int))
req := rg.ListRequest{}
rgList := []struct {
ID int `json:"id"`
}{}
rgListAPI := "/restmachine/cloudapi/rg/list"
rgListRaw, err := c.DecortAPICall(ctx, "POST", rgListAPI, urlValues)
rgList, err := c.CloudAPI().RG().List(ctx, req)
if err != nil {
return false, err
}
err = json.Unmarshal([]byte(rgListRaw), &rgList)
if err != nil {
return false, err
}
haveRG := false
rgId := d.Get("rg_id").(int)
for _, rg := range rgList {
if rg.ID == rgId {
haveRG = true
break
}
}
return haveRG, nil
return len(rgList.FilterByID(rgID)) != 0, nil
}
func existExtNetID(ctx context.Context, d *schema.ResourceData, m interface{}) (bool, error) {
extNetID := d.Get("extnet_id").(int)
extNetID := uint64(d.Get("extnet_id").(int))
if extNetID == 0 {
return true, nil
}
c := m.(*controller.ControllerCfg)
urlValues := &url.Values{}
req := extnet.ListRequest{}
extNetList := []struct {
ID int `json:"id"`
}{}
extNetListAPI := "/restmachine/cloudapi/extnet/list"
extNetListRaw, err := c.DecortAPICall(ctx, "POST", extNetListAPI, urlValues)
extNetList, err := c.CloudAPI().ExtNet().List(ctx, req)
if err != nil {
return false, err
}
err = json.Unmarshal([]byte(extNetListRaw), &extNetList)
if err != nil {
return false, err
}
haveExtNet := false
for _, extNet := range extNetList {
if extNet.ID == extNetID {
haveExtNet = true
break
}
}
return haveExtNet, nil
return len(extNetList.FilterByID(extNetID)) != 0, nil
}

View File

@@ -34,19 +34,21 @@ 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/hashicorp/terraform-plugin-sdk/v2/helper/validation"
log "github.com/sirupsen/logrus"
"repository.basistech.ru/BASIS/decort-golang-sdk/pkg/cloudapi/compute"
"repository.basistech.ru/BASIS/decort-golang-sdk/pkg/cloudapi/k8s"
"repository.basistech.ru/BASIS/decort-golang-sdk/pkg/cloudapi/lb"
"repository.basistech.ru/BASIS/decort-golang-sdk/pkg/cloudapi/tasks"
"repository.basistech.ru/BASIS/terraform-provider-decort/internal/constants"
"repository.basistech.ru/BASIS/terraform-provider-decort/internal/controller"
"repository.basistech.ru/BASIS/terraform-provider-decort/internal/service/cloudapi/kvmvm"
"repository.basistech.ru/BASIS/terraform-provider-decort/internal/status"
)
@@ -83,11 +85,13 @@ func resourceK8sCreate(ctx context.Context, d *schema.ResourceData, m interface{
}
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))
createReq := k8s.CreateRequest{}
createReq.Name = d.Get("name").(string)
createReq.RGID = uint64(d.Get("rg_id").(int))
createReq.K8SCIID = uint64(d.Get("k8sci_id").(int))
createReq.WorkerGroupName = d.Get("wg_name").(string)
createReq.NetworkPlugin = d.Get("network_plugin").(string)
var masterNode K8sNodeRecord
if masters, ok := d.GetOk("masters"); ok {
@@ -95,12 +99,12 @@ func resourceK8sCreate(ctx context.Context, d *schema.ResourceData, m 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))
urlValues.Add("masterSepId", strconv.Itoa(masterNode.SepID))
urlValues.Add("masterSepPool", masterNode.SepPool)
createReq.MasterNum = uint(masterNode.Num)
createReq.MasterCPU = uint(masterNode.Cpu)
createReq.MasterRAM = uint(masterNode.Ram)
createReq.MasterDisk = uint(masterNode.Disk)
createReq.MasterSEPID = uint64(masterNode.SepID)
createReq.MasterSEPPool = masterNode.SepPool
var workerNode K8sNodeRecord
if workers, ok := d.GetOk("workers"); ok {
@@ -108,68 +112,66 @@ func resourceK8sCreate(ctx context.Context, d *schema.ResourceData, m 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))
urlValues.Add("workerSepId", strconv.Itoa(workerNode.SepID))
urlValues.Add("workerSepPool", workerNode.SepPool)
createReq.WorkerNum = uint(workerNode.Num)
createReq.WorkerCPU = uint(workerNode.Cpu)
createReq.WorkerRAM = uint(workerNode.Ram)
createReq.WorkerDisk = uint(workerNode.Disk)
createReq.WorkerSEPID = uint64(workerNode.SepID)
createReq.WorkerSEPPool = workerNode.SepPool
if labels, ok := d.GetOk("labels"); ok {
labels := labels.([]interface{})
for _, label := range labels {
urlValues.Add("labels", label.(string))
createReq.Labels = append(createReq.Labels, label.(string))
}
}
if taints, ok := d.GetOk("taints"); ok {
taints := taints.([]interface{})
for _, taint := range taints {
urlValues.Add("taints", taint.(string))
createReq.Taints = append(createReq.Taints, taint.(string))
}
}
if annotations, ok := d.GetOk("annotations"); ok {
annotations := annotations.([]interface{})
for _, annotation := range annotations {
urlValues.Add("annotations", annotation.(string))
createReq.Annotations = append(createReq.Annotations, annotation.(string))
}
}
if withLB, ok := d.GetOk("with_lb"); ok {
urlValues.Add("withLB", strconv.FormatBool(withLB.(bool)))
createReq.WithLB = withLB.(bool)
} else {
urlValues.Add("withLB", strconv.FormatBool(true))
createReq.WithLB = true
}
if extNet, ok := d.GetOk("extnet_id"); ok {
urlValues.Add("extnetId", strconv.Itoa(extNet.(int)))
createReq.ExtNetID = uint64(extNet.(int))
} else {
urlValues.Add("extnetId", "0")
createReq.ExtNetID = 0
}
if desc, ok := d.GetOk("desc"); ok {
urlValues.Add("desc", desc.(string))
createReq.Description = desc.(string)
}
resp, err := c.DecortAPICall(ctx, "POST", K8sCreateAPI, urlValues)
resp, err := c.CloudAPI().K8S().Create(ctx, createReq)
if err != nil {
return diag.FromErr(err)
}
urlValues = &url.Values{}
urlValues.Add("auditId", strings.Trim(resp, `"`))
taskReq := tasks.GetRequest{
AuditID: strings.Trim(resp, `"`),
}
for {
resp, err := c.DecortAPICall(ctx, "POST", AsyncTaskGetAPI, urlValues)
task, err := c.CloudAPI().Tasks().Get(ctx, taskReq)
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 {
@@ -188,7 +190,7 @@ func resourceK8sCreate(ctx context.Context, d *schema.ResourceData, m interface{
}
func resourceK8sRead(ctx context.Context, d *schema.ResourceData, m interface{}) diag.Diagnostics {
k8s, err := utilityK8sCheckPresence(ctx, d, m)
cluster, err := utilityK8sCheckPresence(ctx, d, m)
if err != nil {
d.SetId("")
return diag.FromErr(err)
@@ -198,29 +200,35 @@ func resourceK8sRead(ctx context.Context, d *schema.ResourceData, m interface{})
hasChanged := false
switch k8s.Status {
switch cluster.Status {
case status.Modeled:
return diag.Errorf("The k8s cluster is in status: %s, please, contact support for more information", k8s.Status)
return diag.Errorf("The k8s cluster is in status: %s, please, contact support for more information", cluster.Status)
case status.Creating:
case status.Created:
case status.Deleting:
case status.Deleted:
urlVal := &url.Values{}
urlVal.Add("k8sId", d.Id())
id, _ := strconv.ParseUint(d.Id(), 10, 64)
restoreReq := k8s.RestoreRequest{
K8SID: id,
}
_, err := c.DecortAPICall(ctx, "POST", K8sRestoreAPI, urlVal)
_, err := c.CloudAPI().K8S().Restore(ctx, restoreReq)
if err != nil {
return diag.FromErr(err)
}
_, err = c.DecortAPICall(ctx, "POST", K8sEnableAPI, urlVal)
enableReq := k8s.DisabelEnableRequest{
K8SID: id,
}
_, err = c.CloudAPI().K8S().Enable(ctx, enableReq)
if err != nil {
return diag.FromErr(err)
}
hasChanged = true
case status.Destroying:
return diag.Errorf("The k8s cluster is in progress with status: %s", k8s.Status)
return diag.Errorf("The k8s cluster is in progress with status: %s", cluster.Status)
case status.Destroyed:
d.SetId("")
return resourceK8sCreate(ctx, d, m)
@@ -228,13 +236,13 @@ func resourceK8sRead(ctx context.Context, d *schema.ResourceData, m interface{})
case status.Enabled:
case status.Disabling:
case status.Disabled:
log.Debugf("The k8s cluster is in status: %s, troubles may occur with update. Please, enable compute first.", k8s.Status)
log.Debugf("The k8s cluster is in status: %s, troubles may occur with update. Please, enable compute first.", cluster.Status)
case status.Restoring:
}
if hasChanged {
k8s, err = utilityK8sCheckPresence(ctx, d, m)
if k8s == nil {
cluster, err = utilityK8sCheckPresence(ctx, d, m)
if cluster == nil {
d.SetId("")
if err != nil {
return diag.FromErr(err)
@@ -243,32 +251,45 @@ func resourceK8sRead(ctx context.Context, d *schema.ResourceData, m interface{})
}
}
k8sList, err := utilityK8sListCheckPresence(ctx, d, m, K8sListAPI)
if d.Get("start").(bool) {
if cluster.TechStatus == "STOPPED" {
req := k8s.StartRequest{
K8SID: cluster.ID,
}
_, err := c.CloudAPI().K8S().Start(ctx, req)
if err != nil {
return diag.FromErr(err)
}
}
}
k8sList, err := utilityK8sListCheckPresence(ctx, d, m)
if err != nil {
d.SetId("")
return diag.FromErr(err)
}
curK8s := K8SItem{}
curK8s := k8s.ItemK8SCluster{}
for _, k8sCluster := range k8sList {
if k8sCluster.ID == k8s.ID {
if k8sCluster.ID == cluster.ID {
curK8s = k8sCluster
}
}
if curK8s.ID == 0 {
return diag.Errorf("Cluster with id %d not found", k8s.ID)
return diag.Errorf("Cluster with id %d not found", cluster.ID)
}
d.Set("vins_id", curK8s.VINSID)
masterComputeList := make([]kvmvm.ComputeGetResp, 0, len(k8s.K8SGroups.Masters.DetailedInfo))
workersComputeList := make([]kvmvm.ComputeGetResp, 0, len(k8s.K8SGroups.Workers))
for _, masterNode := range k8s.K8SGroups.Masters.DetailedInfo {
masterComputeList := make([]compute.RecordCompute, 0, len(cluster.K8SGroups.Masters.DetailedInfo))
workersComputeList := make([]compute.RecordCompute, 0, len(cluster.K8SGroups.Workers))
for _, masterNode := range cluster.K8SGroups.Masters.DetailedInfo {
compute, err := utilityComputeCheckPresence(ctx, d, m, masterNode.ID)
if err != nil {
return diag.FromErr(err)
}
masterComputeList = append(masterComputeList, *compute)
}
for _, worker := range k8s.K8SGroups.Workers {
for _, worker := range cluster.K8SGroups.Workers {
for _, info := range worker.DetailedInfo {
compute, err := utilityComputeCheckPresence(ctx, d, m, info.ID)
if err != nil {
@@ -278,29 +299,29 @@ func resourceK8sRead(ctx context.Context, d *schema.ResourceData, m interface{})
}
}
flattenResourceK8s(d, *k8s, masterComputeList, workersComputeList)
flattenResourceK8s(d, *cluster, masterComputeList, workersComputeList)
urlValues := &url.Values{}
urlValues.Add("lbId", strconv.FormatUint(k8s.LBID, 10))
lbGetReq := lb.GetRequest{
LBID: cluster.LBID,
}
resp, err := c.DecortAPICall(ctx, "POST", LbGetAPI, urlValues)
lb, err := c.CloudAPI().LB().Get(ctx, lbGetReq)
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)
kubeconfigReq := k8s.GetConfigRequest{
K8SID: cluster.ID,
}
kubeconfig, err := c.CloudAPI().K8S().GetConfig(ctx, kubeconfigReq)
if err != nil {
log.Warnf("could not get kubeconfig: %v", err)
}
d.Set("kubeconfig", kubeconfig)
return nil
@@ -329,36 +350,42 @@ func resourceK8sUpdate(ctx context.Context, d *schema.ResourceData, m interface{
return diag.Errorf("resourceK8sUpdate: can't update k8s cluster because K8sCIID %d is not allowed or does not exist", d.Get("k8sci_id").(int))
}
k8s, err := utilityK8sCheckPresence(ctx, d, m)
cluster, err := utilityK8sCheckPresence(ctx, d, m)
if err != nil {
return diag.FromErr(err)
}
hasChanged := false
switch k8s.Status {
switch cluster.Status {
case status.Modeled:
return diag.Errorf("The k8s cluster is in status: %s, please, contact support for more information", k8s.Status)
return diag.Errorf("The k8s cluster is in status: %s, please, contact support for more information", cluster.Status)
case status.Creating:
case status.Created:
case status.Deleting:
case status.Deleted:
urlVal := &url.Values{}
urlVal.Add("k8sId", d.Id())
id, _ := strconv.ParseUint(d.Id(), 10, 64)
restoreReq := k8s.RestoreRequest{
K8SID: id,
}
_, err := c.DecortAPICall(ctx, "POST", K8sRestoreAPI, urlVal)
_, err := c.CloudAPI().K8S().Restore(ctx, restoreReq)
if err != nil {
return diag.FromErr(err)
}
_, err = c.DecortAPICall(ctx, "POST", K8sEnableAPI, urlVal)
enableReq := k8s.DisabelEnableRequest{
K8SID: id,
}
_, err = c.CloudAPI().K8S().Enable(ctx, enableReq)
if err != nil {
return diag.FromErr(err)
}
hasChanged = true
case status.Destroying:
return diag.Errorf("The k8s cluster is in progress with status: %s", k8s.Status)
return diag.Errorf("The k8s cluster is in progress with status: %s", cluster.Status)
case status.Destroyed:
d.SetId("")
return resourceK8sCreate(ctx, d, m)
@@ -366,13 +393,13 @@ func resourceK8sUpdate(ctx context.Context, d *schema.ResourceData, m interface{
case status.Enabled:
case status.Disabling:
case status.Disabled:
log.Debugf("The k8s cluster is in status: %s, troubles may occur with update. Please, enable compute first.", k8s.Status)
log.Debugf("The k8s cluster is in status: %s, troubles may occur with update. Please, enable compute first.", cluster.Status)
case status.Restoring:
}
if hasChanged {
k8s, err = utilityK8sCheckPresence(ctx, d, m)
if k8s == nil {
cluster, err = utilityK8sCheckPresence(ctx, d, m)
if cluster == nil {
d.SetId("")
if err != nil {
return diag.FromErr(err)
@@ -382,33 +409,64 @@ func resourceK8sUpdate(ctx context.Context, d *schema.ResourceData, m interface{
}
if d.HasChange("name") {
urlValues := &url.Values{}
urlValues.Add("k8sId", d.Id())
urlValues.Add("name", d.Get("name").(string))
req := k8s.UpdateRequest{
K8SID: cluster.ID,
Name: d.Get("name").(string),
}
_, err := c.DecortAPICall(ctx, "POST", K8sUpdateAPI, urlValues)
_, err := c.CloudAPI().K8S().Update(ctx, req)
if err != nil {
return diag.FromErr(err)
}
}
if d.HasChange("workers") {
wg := k8s.K8SGroups.Workers[0]
urlValues := &url.Values{}
urlValues.Add("k8sId", d.Id())
urlValues.Add("workersGroupId", strconv.FormatUint(wg.ID, 10))
wg := cluster.K8SGroups.Workers[0]
newWorkers := parseNode(d.Get("workers").([]interface{}))
if uint64(newWorkers.Num) > wg.Num {
urlValues.Add("num", strconv.FormatUint(uint64(newWorkers.Num)-wg.Num, 10))
if _, err := c.DecortAPICall(ctx, "POST", K8sWorkerAddAPI, urlValues); err != nil {
req := k8s.WorkerAddRequest{
K8SID: cluster.ID,
WorkersGroupID: wg.ID,
Num: uint64(newWorkers.Num - int(wg.Num)),
}
if _, err := c.CloudAPI().K8S().WorkerAdd(ctx, req); err != nil {
return diag.FromErr(err)
}
} else {
for i := int(wg.Num) - 1; i >= newWorkers.Num; i-- {
urlValues.Set("workerId", strconv.FormatUint(wg.DetailedInfo[i].ID, 10))
if _, err := c.DecortAPICall(ctx, "POST", K8sWorkerDeleteAPI, urlValues); err != nil {
req := k8s.DeleteWorkerFromGroupRequest{
K8SID: cluster.ID,
WorkersGroupID: wg.ID,
WorkerID: wg.DetailedInfo[i].ID,
}
if _, err := c.CloudAPI().K8S().DeleteWorkerFromGroup(ctx, req); err != nil {
return diag.FromErr(err)
}
}
}
}
if d.HasChange("start") {
if d.Get("start").(bool) {
if cluster.TechStatus == "STOPPED" {
req := k8s.StartRequest{
K8SID: cluster.ID,
}
_, err := c.CloudAPI().K8S().Start(ctx, req)
if err != nil {
return diag.FromErr(err)
}
}
} else {
if cluster.TechStatus == "STARTED" {
req := k8s.StopRequest{
K8SID: cluster.ID,
}
_, err := c.CloudAPI().K8S().Stop(ctx, req)
if err != nil {
return diag.FromErr(err)
}
}
@@ -421,20 +479,18 @@ 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(ctx, d, m)
if k8s == nil {
if err != nil {
return diag.FromErr(err)
}
return nil
cluster, err := utilityK8sCheckPresence(ctx, d, m)
if err != nil {
return diag.FromErr(err)
}
c := m.(*controller.ControllerCfg)
urlValues := &url.Values{}
urlValues.Add("k8sId", d.Id())
urlValues.Add("permanently", "true")
req := k8s.DeleteRequest{
K8SID: cluster.ID,
Permanently: true,
}
_, err = c.DecortAPICall(ctx, "POST", K8sDeleteAPI, urlValues)
_, err = c.CloudAPI().K8S().Delete(ctx, req)
if err != nil {
return diag.FromErr(err)
}
@@ -466,6 +522,12 @@ func resourceK8sSchemaMake() map[string]*schema.Schema {
Required: true,
Description: "Name for first worker group created with cluster.",
},
"network_plugin": {
Type: schema.TypeString,
Required: true,
Description: "Network plugin to be used",
ValidateFunc: validation.StringInSlice([]string{"flannel", "weavenet", "calico"}, true),
},
"labels": {
Type: schema.TypeList,
Optional: true,
@@ -526,6 +588,12 @@ func resourceK8sSchemaMake() map[string]*schema.Schema {
Optional: true,
Description: "Text description of this instance.",
},
"start": {
Type: schema.TypeBool,
Optional: true,
Default: true,
Description: "Start k8s cluster",
},
"acl": {
Type: schema.TypeList,

View File

@@ -34,16 +34,16 @@ package k8s
import (
"context"
"net/url"
"strconv"
"strings"
"github.com/hashicorp/terraform-plugin-sdk/v2/diag"
"github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema"
log "github.com/sirupsen/logrus"
"repository.basistech.ru/BASIS/decort-golang-sdk/pkg/cloudapi/compute"
"repository.basistech.ru/BASIS/decort-golang-sdk/pkg/cloudapi/k8s"
"repository.basistech.ru/BASIS/terraform-provider-decort/internal/constants"
"repository.basistech.ru/BASIS/terraform-provider-decort/internal/controller"
"repository.basistech.ru/BASIS/terraform-provider-decort/internal/service/cloudapi/kvmvm"
)
func resourceK8sWgCreate(ctx context.Context, d *schema.ResourceData, m interface{}) diag.Diagnostics {
@@ -59,54 +59,26 @@ func resourceK8sWgCreate(ctx context.Context, d *schema.ResourceData, m interfac
}
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)))
if d.Get("disk") == nil {
urlValues.Add("workerDisk", strconv.Itoa(0))
} else {
urlValues.Add("workerDisk", strconv.Itoa(d.Get("disk").(int)))
req := k8s.WorkersGroupAddRequest{
K8SID: uint64(d.Get("k8s_id").(int)),
Name: d.Get("name").(string),
WorkerNum: uint64(d.Get("num").(int)),
WorkerCPU: uint64(d.Get("cpu").(int)),
WorkerRAM: uint64(d.Get("ram").(int)),
}
resp, err := c.DecortAPICall(ctx, "POST", K8sWgCreateAPI, urlValues)
if d.Get("disk") == nil {
req.WorkerDisk = 0
} else {
req.WorkerDisk = uint64(d.Get("disk").(int))
}
resp, err := c.CloudAPI().K8S().WorkersGroupAdd(ctx, req)
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)
//}
d.SetId(strconv.FormatUint(resp, 10))
return resourceK8sWgRead(ctx, d, m)
}
@@ -119,7 +91,7 @@ func resourceK8sWgRead(ctx context.Context, d *schema.ResourceData, m interface{
return diag.FromErr(err)
}
workersComputeList := make([]kvmvm.ComputeGetResp, 0, 0)
workersComputeList := make([]compute.RecordCompute, 0, 0)
for _, info := range wg.DetailedInfo {
compute, err := utilityComputeCheckPresence(ctx, d, m, info.ID)
if err != nil {
@@ -165,20 +137,27 @@ func resourceK8sWgUpdate(ctx context.Context, d *schema.ResourceData, m interfac
return diag.FromErr(err)
}
urlValues := &url.Values{}
urlValues.Add("k8sId", strconv.Itoa(d.Get("k8s_id").(int)))
urlValues.Add("workersGroupId", d.Id())
wgId, _ := strconv.ParseUint(d.Id(), 10, 64)
if newNum := d.Get("num").(int); uint64(newNum) > wg.Num {
urlValues.Add("num", strconv.FormatUint(uint64(newNum)-wg.Num, 10))
_, err := c.DecortAPICall(ctx, "POST", K8sWorkerAddAPI, urlValues)
req := k8s.WorkerAddRequest{
K8SID: uint64(d.Get("k8s_id").(int)),
WorkersGroupID: wgId,
Num: uint64(newNum) - wg.Num,
}
_, err := c.CloudAPI().K8S().WorkerAdd(ctx, req)
if err != nil {
return diag.FromErr(err)
}
} else {
for i := int(wg.Num) - 1; i >= newNum; i-- {
urlValues.Set("workerId", strconv.FormatUint(wg.DetailedInfo[i].ID, 10))
_, err := c.DecortAPICall(ctx, "POST", K8sWorkerDeleteAPI, urlValues)
req := k8s.DeleteWorkerFromGroupRequest{
K8SID: uint64(d.Get("k8s_id").(int)),
WorkersGroupID: wgId,
WorkerID: wg.DetailedInfo[i].ID,
}
_, err := c.CloudAPI().K8S().DeleteWorkerFromGroup(ctx, req)
if err != nil {
return diag.FromErr(err)
}
@@ -192,19 +171,17 @@ func resourceK8sWgDelete(ctx context.Context, d *schema.ResourceData, m interfac
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
if err != nil {
return diag.FromErr(err)
}
c := m.(*controller.ControllerCfg)
urlValues := &url.Values{}
urlValues.Add("k8sId", strconv.Itoa(d.Get("k8s_id").(int)))
urlValues.Add("workersGroupId", strconv.FormatUint(wg.ID, 10))
req := k8s.WorkersGroupDeleteRequest{
K8SID: uint64(d.Get("k8s_id").(int)),
WorkersGroupID: wg.ID,
}
_, err = c.DecortAPICall(ctx, "POST", K8sWgDeleteAPI, urlValues)
_, err = c.CloudAPI().K8S().WorkersGroupDelete(ctx, req)
if err != nil {
return diag.FromErr(err)
}

View File

@@ -34,50 +34,37 @@ package k8s
import (
"context"
"encoding/json"
"net/url"
"strconv"
"github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema"
"repository.basistech.ru/BASIS/decort-golang-sdk/pkg/cloudapi/compute"
"repository.basistech.ru/BASIS/decort-golang-sdk/pkg/cloudapi/k8s"
"repository.basistech.ru/BASIS/terraform-provider-decort/internal/controller"
"repository.basistech.ru/BASIS/terraform-provider-decort/internal/service/cloudapi/kvmvm"
)
func utilityK8sCheckPresence(ctx context.Context, d *schema.ResourceData, m interface{}) (*K8SRecord, error) {
func utilityK8sCheckPresence(ctx context.Context, d *schema.ResourceData, m interface{}) (*k8s.RecordK8S, error) {
c := m.(*controller.ControllerCfg)
urlValues := &url.Values{}
urlValues.Add("k8sId", d.Id())
resp, err := c.DecortAPICall(ctx, "POST", K8sGetAPI, urlValues)
k8sID, _ := strconv.ParseUint(d.Id(), 10, 64)
req := k8s.GetRequest{
K8SID: k8sID,
}
k8s, err := c.CloudAPI().K8S().Get(ctx, req)
if err != nil {
return nil, err
}
if resp == "" {
return nil, nil
}
k8s := K8SRecord{}
if err := json.Unmarshal([]byte(resp), &k8s); err != nil {
return nil, err
}
return &k8s, nil
return k8s, nil
}
func utilityComputeCheckPresence(ctx context.Context, d *schema.ResourceData, m interface{}, computeID uint64) (*kvmvm.ComputeGetResp, error) {
func utilityComputeCheckPresence(ctx context.Context, d *schema.ResourceData, m interface{}, computeID uint64) (*compute.RecordCompute, error) {
c := m.(*controller.ControllerCfg)
urlValues := &url.Values{}
urlValues.Add("computeId", strconv.FormatUint(computeID, 10))
computeRaw, err := c.DecortAPICall(ctx, "POST", kvmvm.ComputeGetAPI, urlValues)
if err != nil {
return nil, err
req := compute.GetRequest{
ComputeID: computeID,
}
compute := &kvmvm.ComputeGetResp{}
err = json.Unmarshal([]byte(computeRaw), compute)
compute, err := c.CloudAPI().Compute().Get(ctx, req)
if err != nil {
return nil, err
}
@@ -85,41 +72,43 @@ func utilityComputeCheckPresence(ctx context.Context, d *schema.ResourceData, m
return compute, nil
}
func utilityDataK8sCheckPresence(ctx context.Context, d *schema.ResourceData, m interface{}) (*K8SRecord, error) {
func utilityDataK8sCheckPresence(ctx context.Context, d *schema.ResourceData, m interface{}) (*k8s.RecordK8S, error) {
c := m.(*controller.ControllerCfg)
urlValues := &url.Values{}
urlValues.Add("k8sId", strconv.Itoa(d.Get("k8s_id").(int)))
k8sRaw, err := c.DecortAPICall(ctx, "POST", K8sGetAPI, urlValues)
req := k8s.GetRequest{
K8SID: uint64(d.Get("k8s_id").(int)),
}
k8s, err := c.CloudAPI().K8S().Get(ctx, req)
if err != nil {
return nil, err
}
k8s := &K8SRecord{}
err = json.Unmarshal([]byte(k8sRaw), k8s)
if err != nil {
return nil, err
}
return k8s, nil
}
func utilityK8sListCheckPresence(ctx context.Context, d *schema.ResourceData, m interface{}, api string) (K8SList, error) {
func utilityK8sListCheckPresence(ctx context.Context, d *schema.ResourceData, m interface{}) (k8s.ListK8SClusters, error) {
c := m.(*controller.ControllerCfg)
urlValues := &url.Values{}
urlValues.Add("includedeleted", "false")
urlValues.Add("page", "0")
urlValues.Add("size", "0")
req := k8s.ListRequest{
IncludeDeleted: false,
}
k8sListRaw, err := c.DecortAPICall(ctx, "POST", api, urlValues)
k8sList, err := c.CloudAPI().K8S().List(ctx, req)
if err != nil {
return nil, err
}
return k8sList, nil
}
func utilityK8sListDeletedCheckPresence(ctx context.Context, d *schema.ResourceData, m interface{}) (k8s.ListK8SClusters, error) {
c := m.(*controller.ControllerCfg)
req := k8s.ListDeletedRequest{}
k8sList, err := c.CloudAPI().K8S().ListDeleted(ctx, req)
if err != nil {
return nil, err
}
k8sList := K8SList{}
err = json.Unmarshal([]byte(k8sListRaw), &k8sList)
if err != nil {
return nil, err
}
return k8sList, nil
}

View File

@@ -34,40 +34,34 @@ package k8s
import (
"context"
"encoding/json"
"fmt"
"net/url"
"strconv"
"strings"
"github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema"
"repository.basistech.ru/BASIS/decort-golang-sdk/pkg/cloudapi/compute"
"repository.basistech.ru/BASIS/decort-golang-sdk/pkg/cloudapi/k8s"
"repository.basistech.ru/BASIS/terraform-provider-decort/internal/controller"
"repository.basistech.ru/BASIS/terraform-provider-decort/internal/service/cloudapi/kvmvm"
)
func utilityDataK8sWgCheckPresence(ctx context.Context, d *schema.ResourceData, m interface{}) (*K8SGroup, []kvmvm.ComputeGetResp, error) {
func utilityDataK8sWgCheckPresence(ctx context.Context, d *schema.ResourceData, m interface{}) (*k8s.ItemK8SGroup, []compute.RecordCompute, error) {
c := m.(*controller.ControllerCfg)
urlValues := &url.Values{}
k8sId := d.Get("k8s_id").(int)
wgId := d.Get("wg_id").(int)
k8sId := uint64(d.Get("k8s_id").(int))
wgId := uint64(d.Get("wg_id").(int))
urlValues.Add("k8sId", strconv.Itoa(k8sId))
k8sGetReq := k8s.GetRequest{
K8SID: k8sId,
}
k8sRaw, err := c.DecortAPICall(ctx, "POST", K8sGetAPI, urlValues)
cluster, err := c.CloudAPI().K8S().Get(ctx, k8sGetReq)
if err != nil {
return nil, nil, err
}
k8s := K8SRecord{}
err = json.Unmarshal([]byte(k8sRaw), &k8s)
if err != nil {
return nil, nil, err
}
curWg := K8SGroup{}
for _, wg := range k8s.K8SGroups.Workers {
if wg.ID == uint64(wgId) {
curWg := k8s.ItemK8SGroup{}
for _, wg := range cluster.K8SGroups.Workers {
if wg.ID == wgId {
curWg = wg
break
}
@@ -76,7 +70,7 @@ func utilityDataK8sWgCheckPresence(ctx context.Context, d *schema.ResourceData,
return nil, nil, fmt.Errorf("WG with id %v in k8s cluster %v not found", wgId, k8sId)
}
workersComputeList := make([]kvmvm.ComputeGetResp, 0, 0)
workersComputeList := make([]compute.RecordCompute, 0, 0)
for _, info := range curWg.DetailedInfo {
compute, err := utilityComputeCheckPresence(ctx, d, m, info.ID)
if err != nil {
@@ -89,9 +83,8 @@ func utilityDataK8sWgCheckPresence(ctx context.Context, d *schema.ResourceData,
return &curWg, workersComputeList, nil
}
func utilityK8sWgCheckPresence(ctx context.Context, d *schema.ResourceData, m interface{}) (*K8SGroup, error) {
func utilityK8sWgCheckPresence(ctx context.Context, d *schema.ResourceData, m interface{}) (*k8s.ItemK8SGroup, error) {
c := m.(*controller.ControllerCfg)
urlValues := &url.Values{}
var wgId int
var k8sId int
var err error
@@ -113,27 +106,34 @@ func utilityK8sWgCheckPresence(ctx context.Context, d *schema.ResourceData, m in
k8sId = d.Get("k8s_id").(int)
}
urlValues.Add("k8sId", strconv.Itoa(k8sId))
req := k8s.GetRequest{
K8SID: uint64(k8sId),
}
resp, err := c.DecortAPICall(ctx, "POST", K8sGetAPI, urlValues)
cluster, err := c.CloudAPI().K8S().Get(ctx, req)
if err != nil {
return nil, err
}
if resp == "" {
return nil, err
}
var k8s K8SRecord
if err := json.Unmarshal([]byte(resp), &k8s); err != nil {
return nil, err
}
for _, wg := range k8s.K8SGroups.Workers {
for _, wg := range cluster.K8SGroups.Workers {
if wg.ID == uint64(wgId) {
return &wg, nil
}
}
return nil, fmt.Errorf("Not found wg with id: %v in k8s cluster: %v", wgId, k8s.ID)
return nil, fmt.Errorf("Not found wg with id: %v in k8s cluster: %v", wgId, cluster.ID)
}
func utilityK8sWgListCheckPresence(ctx context.Context, d *schema.ResourceData, m interface{}) (k8s.ListK8SGroups, error) {
c := m.(*controller.ControllerCfg)
req := k8s.GetRequest{
K8SID: uint64(d.Get("k8s_id").(int)),
}
cluster, err := c.CloudAPI().K8S().Get(ctx, req)
if err != nil {
return nil, err
}
return cluster.K8SGroups.Workers, nil
}

View File

@@ -1,88 +0,0 @@
/*
Copyright (c) 2019-2022 Digital Energy Cloud Solutions LLC. All Rights Reserved.
Authors:
Petr Krutov, <petr.krutov@digitalenergy.online>
Stanislav Solovev, <spsolovev@digitalenergy.online>
Kasim Baybikov, <kmbaybikov@basistech.ru>
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://repository.basistech.ru/BASIS/terraform-provider-decort
Please see README.md to learn where to place source code so that it
builds seamlessly.
Documentation: https://repository.basistech.ru/BASIS/terraform-provider-decort/wiki
*/
package kvmvm
const (
KvmX86CreateAPI = "/restmachine/cloudapi/kvmx86/create"
KvmPPCCreateAPI = "/restmachine/cloudapi/kvmppc/create"
ComputeGetAPI = "/restmachine/cloudapi/compute/get"
RgListComputesAPI = "/restmachine/cloudapi/rg/listComputes"
ComputeNetAttachAPI = "/restmachine/cloudapi/compute/netAttach"
ComputeNetDetachAPI = "/restmachine/cloudapi/compute/netDetach"
ComputeDiskAttachAPI = "/restmachine/cloudapi/compute/diskAttach"
ComputeDiskDetachAPI = "/restmachine/cloudapi/compute/diskDetach"
ComputeStartAPI = "/restmachine/cloudapi/compute/start"
ComputeStopAPI = "/restmachine/cloudapi/compute/stop"
ComputeResizeAPI = "/restmachine/cloudapi/compute/resize"
DisksResizeAPI = "/restmachine/cloudapi/disks/resize2"
ComputeDeleteAPI = "/restmachine/cloudapi/compute/delete"
ComputeUpdateAPI = "/restmachine/cloudapi/compute/update"
ComputeDiskAddAPI = "/restmachine/cloudapi/compute/diskAdd"
ComputeDiskDeleteAPI = "/restmachine/cloudapi/compute/diskDel"
ComputeRestoreAPI = "/restmachine/cloudapi/compute/restore"
ComputeEnableAPI = "/restmachine/cloudapi/compute/enable"
ComputeDisableAPI = "/restmachine/cloudapi/compute/disable"
ComputeAffinityLabelSetAPI = "/restmachine/cloudapi/compute/affinityLabelSet"
ComputeAffinityLabelRemoveAPI = "/restmachine/cloudapi/compute/affinityLabelRemove"
ComputeAffinityRuleAddAPI = "/restmachine/cloudapi/compute/affinityRuleAdd"
ComputeAffinityRuleRemoveAPI = "/restmachine/cloudapi/compute/affinityRuleRemove"
ComputeAffinityRulesClearAPI = "/restmachine/cloudapi/compute/affinityRulesClear"
ComputeAntiAffinityRuleAddAPI = "/restmachine/cloudapi/compute/antiAffinityRuleAdd"
ComputeAntiAffinityRuleRemoveAPI = "/restmachine/cloudapi/compute/antiAffinityRuleRemove"
ComputeAntiAffinityRulesClearAPI = "/restmachine/cloudapi/compute/antiAffinityRulesClear"
ComputeListAPI = "/restmachine/cloudapi/compute/list"
ComputeAuditsAPI = "/restmachine/cloudapi/compute/audits"
ComputeGetAuditsAPI = "/restmachine/cloudapi/compute/getAudits"
ComputeGetConsoleUrlAPI = "/restmachine/cloudapi/compute/getConsoleUrl"
ComputeGetLogAPI = "/restmachine/cloudapi/compute/getLog"
ComputePfwListAPI = "/restmachine/cloudapi/compute/pfwList"
ComputeUserListAPI = "/restmachine/cloudapi/compute/userList"
ComputeTagAddAPI = "/restmachine/cloudapi/compute/tagAdd"
ComputeTagRemoveAPI = "/restmachine/cloudapi/compute/tagRemove"
ComputePinToStackAPI = "/restmachine/cloudapi/compute/pinToStack"
ComputeUnpinFromStackAPI = "/restmachine/cloudapi/compute/unpinFromStack"
ComputePfwAddAPI = "/restmachine/cloudapi/compute/pfwAdd"
ComputePfwDelAPI = "/restmachine/cloudapi/compute/pfwDel"
ComputeUserGrantAPI = "/restmachine/cloudapi/compute/userGrant"
ComputeUserRevokeAPI = "/restmachine/cloudapi/compute/userRevoke"
ComputeSnapshotCreateAPI = "/restmachine/cloudapi/compute/snapshotCreate"
ComputeSnapshotDeleteAPI = "/restmachine/cloudapi/compute/snapshotCreate"
ComputeSnapshotUsageAPI = "/restmachine/cloudapi/compute/snapshotUsage"
ComputeSnapshotRollbackAPI = "/restmachine/cloudapi/compute/snapshotRollback"
ComputePauseAPI = "/restmachine/cloudapi/compute/pause"
ComputeResumeAPI = "/restmachine/cloudapi/compute/resume"
ComputeCdInsertAPI = "/restmachine/cloudapi/compute/cdInsert"
ComputeCdEjectAPI = "/restmachine/cloudapi/compute/cdEject"
ComputeResetAPI = "/restmachine/cloudapi/compute/reset"
ComputeRedeployAPI = "/restmachine/cloudapi/compute/redeploy"
)

View File

@@ -10,7 +10,7 @@ import (
)
func dataSourceComputeSnapshotUsageRead(ctx context.Context, d *schema.ResourceData, m interface{}) diag.Diagnostics {
computeSnapshotUsage, err := utilityComputeSnapshotUasgeCheckPresence(ctx, d, m)
computeSnapshotUsage, err := utilityComputeSnapshotUsageCheckPresence(ctx, d, m)
if err != nil {
return diag.FromErr(err)
}

View File

@@ -39,10 +39,11 @@ import (
"github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema"
log "github.com/sirupsen/logrus"
"repository.basistech.ru/BASIS/decort-golang-sdk/pkg/cloudapi/compute"
"repository.basistech.ru/BASIS/terraform-provider-decort/internal/status"
)
func flattenDisks(disks []InfoDisk) []map[string]interface{} {
func flattenDisks(disks []compute.InfoDisk) []map[string]interface{} {
res := make([]map[string]interface{}, 0)
for _, disk := range disks {
temp := map[string]interface{}{
@@ -53,7 +54,7 @@ func flattenDisks(disks []InfoDisk) []map[string]interface{} {
}
return res
}
func flattenQOS(qos QOS) []map[string]interface{} {
func flattenQOS(qos compute.QOS) []map[string]interface{} {
res := make([]map[string]interface{}, 0)
temp := map[string]interface{}{
"e_rate": qos.ERate,
@@ -64,7 +65,7 @@ func flattenQOS(qos QOS) []map[string]interface{} {
res = append(res, temp)
return res
}
func flattenInterfaces(interfaces ListInterfaces) []map[string]interface{} {
func flattenInterfaces(interfaces compute.ListInterfaces) []map[string]interface{} {
res := make([]map[string]interface{}, 0)
for _, interfaceItem := range interfaces {
temp := map[string]interface{}{
@@ -90,7 +91,7 @@ func flattenInterfaces(interfaces ListInterfaces) []map[string]interface{} {
}
return res
}
func flattenSnapSets(snapSets ListSnapSets) []map[string]interface{} {
func flattenSnapSets(snapSets compute.ListSnapSets) []map[string]interface{} {
res := make([]map[string]interface{}, 0)
for _, snapSet := range snapSets {
temp := map[string]interface{}{
@@ -115,7 +116,7 @@ func flattenTags(tags map[string]string) []map[string]interface{} {
return res
}
func flattenListRules(listRules ListRules) []map[string]interface{} {
func flattenListRules(listRules compute.ListRules) []map[string]interface{} {
res := make([]map[string]interface{}, 0)
for _, rule := range listRules {
temp := map[string]interface{}{
@@ -130,18 +131,11 @@ func flattenListRules(listRules ListRules) []map[string]interface{} {
}
return res
}
func flattenListACL(listAcl ListACL) []map[string]interface{} {
func flattenListACL(listAcl compute.ListACL) []map[string]interface{} {
res := make([]map[string]interface{}, 0)
for _, acl := range listAcl {
var explicit interface{}
switch acl.Explicit.(type) { //Платформенный хак
case bool:
explicit = acl.Explicit.(bool)
case string:
explicit, _ = strconv.ParseBool(acl.Explicit.(string))
}
temp := map[string]interface{}{
"explicit": explicit,
"explicit": acl.Explicit,
"guid": acl.GUID,
"right": acl.Right,
"status": acl.Status,
@@ -152,7 +146,8 @@ func flattenListACL(listAcl ListACL) []map[string]interface{} {
}
return res
}
func flattenComputeList(computes ListComputes) []map[string]interface{} {
func flattenComputeList(computes compute.ListComputes) []map[string]interface{} {
res := make([]map[string]interface{}, 0)
for _, compute := range computes {
customFields, _ := json.Marshal(compute.CustomFields)
@@ -219,7 +214,29 @@ func flattenComputeList(computes ListComputes) []map[string]interface{} {
return res
}
func flattenComputeDisksDemo(disksList ListComputeDisks, extraDisks []interface{}) []map[string]interface{} {
func flattenBootDisk(bootDisk *compute.ItemComputeDisk) []map[string]interface{} {
res := make([]map[string]interface{}, 0)
temp := map[string]interface{}{
"disk_name": bootDisk.Name,
"disk_id": bootDisk.ID,
"disk_type": bootDisk.Type,
"sep_id": bootDisk.SepID,
"shareable": bootDisk.Shareable,
"size_max": bootDisk.SizeMax,
"size_used": bootDisk.SizeUsed,
"pool": bootDisk.Pool,
"desc": bootDisk.Description,
"image_id": bootDisk.ImageID,
"size": bootDisk.SizeMax,
}
res = append(res, temp)
return res
}
func flattenComputeDisksDemo(disksList compute.ListComputeDisks, extraDisks []interface{}) []map[string]interface{} {
res := make([]map[string]interface{}, 0, len(disksList))
for _, disk := range disksList {
if disk.Name == "bootdisk" || findInExtraDisks(uint(disk.ID), extraDisks) { //skip main bootdisk and extraDisks
@@ -246,7 +263,7 @@ func flattenComputeDisksDemo(disksList ListComputeDisks, extraDisks []interface{
return res
}
func flattenNetwork(interfaces ListInterfaces) []map[string]interface{} {
func flattenNetwork(interfaces compute.ListInterfaces) []map[string]interface{} {
res := make([]map[string]interface{}, 0, len(interfaces))
//index := 0
for _, network := range interfaces {
@@ -261,7 +278,7 @@ func flattenNetwork(interfaces ListInterfaces) []map[string]interface{} {
return res
}
func findBootDisk(disks ListComputeDisks) *ItemComputeDisk {
func findBootDisk(disks compute.ListComputeDisks) *compute.ItemComputeDisk {
for _, disk := range disks {
if disk.Name == "bootdisk" {
return &disk
@@ -270,139 +287,109 @@ func findBootDisk(disks ListComputeDisks) *ItemComputeDisk {
return nil
}
func flattenCompute(d *schema.ResourceData, compute RecordCompute) error {
func flattenCompute(d *schema.ResourceData, computeRec compute.RecordCompute) 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
log.Debugf("flattenCompute: ID %d, RG ID %d", compute.ID, compute.RGID)
log.Debugf("flattenCompute: ID %d, RG ID %d", computeRec.ID, computeRec.RGID)
devices, _ := json.Marshal(compute.Devices)
userdata, _ := json.Marshal(compute.Userdata)
devices, _ := json.Marshal(computeRec.Devices)
userdata, _ := json.Marshal(computeRec.Userdata)
bootDisk := findBootDisk(computeRec.Disks)
//check extraDisks, ipa_type, is,
d.SetId(strconv.FormatUint(compute.ID, 10))
d.Set("acl", flattenACL(compute.ACL))
d.Set("account_id", compute.AccountID)
d.Set("account_name", compute.AccountName)
d.Set("affinity_weight", compute.AffinityWeight)
d.Set("arch", compute.Architecture)
d.Set("boot_order", compute.BootOrder)
d.Set("boot_disk_size", compute.BootDiskSize)
bootDisk := findBootDisk(compute.Disks)
d.SetId(strconv.FormatUint(computeRec.ID, 10))
d.Set("acl", flattenACL(computeRec.ACL))
d.Set("account_id", computeRec.AccountID)
d.Set("account_name", computeRec.AccountName)
d.Set("affinity_weight", computeRec.AffinityWeight)
d.Set("arch", computeRec.Architecture)
d.Set("boot_order", computeRec.BootOrder)
d.Set("boot_disk_size", computeRec.BootDiskSize)
d.Set("boot_disk", flattenBootDisk(bootDisk))
d.Set("boot_disk_id", bootDisk.ID)
d.Set("sep_id", bootDisk.SepID)
d.Set("pool", bootDisk.Pool)
d.Set("clone_reference", compute.CloneReference)
d.Set("clones", compute.Clones)
d.Set("clone_reference", computeRec.CloneReference)
d.Set("clones", computeRec.Clones)
if string(userdata) != "{}" {
d.Set("cloud_init", string(userdata))
}
d.Set("computeci_id", compute.ComputeCIID)
d.Set("created_by", compute.CreatedBy)
d.Set("created_time", compute.CreatedTime)
d.Set("custom_fields", flattenCustomFields(compute.CustomFields))
d.Set("deleted_by", compute.DeletedBy)
d.Set("deleted_time", compute.DeletedTime)
d.Set("description", compute.Description)
d.Set("computeci_id", computeRec.ComputeCIID)
d.Set("created_by", computeRec.CreatedBy)
d.Set("created_time", computeRec.CreatedTime)
d.Set("custom_fields", flattenCustomFields(computeRec.CustomFields))
d.Set("deleted_by", computeRec.DeletedBy)
d.Set("deleted_time", computeRec.DeletedTime)
d.Set("description", computeRec.Description)
d.Set("devices", string(devices))
err := d.Set("disks", flattenComputeDisksDemo(compute.Disks, d.Get("extra_disks").(*schema.Set).List()))
err := d.Set("disks", flattenComputeDisksDemo(computeRec.Disks, d.Get("extra_disks").(*schema.Set).List()))
if err != nil {
return err
}
d.Set("driver", compute.Driver)
d.Set("cpu", compute.CPU)
d.Set("gid", compute.GID)
d.Set("guid", compute.GUID)
d.Set("compute_id", compute.ID)
if compute.VirtualImageID != 0 {
d.Set("image_id", compute.VirtualImageID)
d.Set("driver", computeRec.Driver)
d.Set("cpu", computeRec.CPU)
d.Set("gid", computeRec.GID)
d.Set("guid", computeRec.GUID)
d.Set("compute_id", computeRec.ID)
if computeRec.VirtualImageID != 0 {
d.Set("image_id", computeRec.VirtualImageID)
} else {
d.Set("image_id", compute.ImageID)
d.Set("image_id", computeRec.ImageID)
}
d.Set("interfaces", flattenInterfaces(compute.Interfaces))
d.Set("lock_status", compute.LockStatus)
d.Set("manager_id", compute.ManagerID)
d.Set("manager_type", compute.ManagerType)
d.Set("migrationjob", compute.MigrationJob)
d.Set("milestones", compute.Milestones)
d.Set("name", compute.Name)
d.Set("natable_vins_id", compute.NatableVINSID)
d.Set("natable_vins_ip", compute.NatableVINSIP)
d.Set("natable_vins_name", compute.NatableVINSName)
d.Set("natable_vins_network", compute.NatableVINSNetwork)
d.Set("natable_vins_network_name", compute.NatableVINSNetworkName)
if err := d.Set("os_users", parseOsUsers(compute.OSUsers)); err != nil {
d.Set("interfaces", flattenInterfaces(computeRec.Interfaces))
d.Set("lock_status", computeRec.LockStatus)
d.Set("manager_id", computeRec.ManagerID)
d.Set("manager_type", computeRec.ManagerType)
d.Set("migrationjob", computeRec.MigrationJob)
d.Set("milestones", computeRec.Milestones)
d.Set("name", computeRec.Name)
d.Set("natable_vins_id", computeRec.NatableVINSID)
d.Set("natable_vins_ip", computeRec.NatableVINSIP)
d.Set("natable_vins_name", computeRec.NatableVINSName)
d.Set("natable_vins_network", computeRec.NatableVINSNetwork)
d.Set("natable_vins_network_name", computeRec.NatableVINSNetworkName)
if err := d.Set("os_users", parseOsUsers(computeRec.OSUsers)); err != nil {
return err
}
d.Set("pinned", compute.Pinned)
d.Set("ram", compute.RAM)
d.Set("reference_id", compute.ReferenceID)
d.Set("registered", compute.Registered)
d.Set("res_name", compute.ResName)
d.Set("rg_id", compute.RGID)
d.Set("rg_name", compute.RGName)
d.Set("snap_sets", flattenSnapSets(compute.SnapSets))
d.Set("stateless_sep_id", compute.StatelessSepID)
d.Set("stateless_sep_type", compute.StatelessSepType)
d.Set("status", compute.Status)
d.Set("tags", flattenTags(compute.Tags))
d.Set("tech_status", compute.TechStatus)
d.Set("updated_by", compute.UpdatedBy)
d.Set("updated_time", compute.UpdatedTime)
d.Set("user_managed", compute.UserManaged)
d.Set("vgpus", compute.VGPUs)
d.Set("virtual_image_id", compute.VirtualImageID)
d.Set("virtual_image_name", compute.VirtualImageName)
d.Set("pinned", computeRec.Pinned)
d.Set("ram", computeRec.RAM)
d.Set("reference_id", computeRec.ReferenceID)
d.Set("registered", computeRec.Registered)
d.Set("res_name", computeRec.ResName)
d.Set("rg_id", computeRec.RGID)
d.Set("rg_name", computeRec.RGName)
d.Set("snap_sets", flattenSnapSets(computeRec.SnapSets))
d.Set("stateless_sep_id", computeRec.StatelessSepID)
d.Set("stateless_sep_type", computeRec.StatelessSepType)
d.Set("status", computeRec.Status)
d.Set("tags", flattenTags(computeRec.Tags))
d.Set("tech_status", computeRec.TechStatus)
d.Set("updated_by", computeRec.UpdatedBy)
d.Set("updated_time", computeRec.UpdatedTime)
d.Set("user_managed", computeRec.UserManaged)
d.Set("vgpus", computeRec.VGPUs)
d.Set("virtual_image_id", computeRec.VirtualImageID)
d.Set("virtual_image_name", computeRec.VirtualImageName)
d.Set("enabled", false)
if compute.Status == status.Enabled {
if computeRec.Status == status.Enabled {
d.Set("enabled", true)
}
d.Set("started", false)
if compute.TechStatus == "STARTED" {
if computeRec.TechStatus == "STARTED" {
d.Set("started", true)
}
d.Set("network", flattenNetwork(compute.Interfaces))
//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
//}
//}
d.Set("network", flattenNetwork(computeRec.Interfaces))
return nil
}
func flattenDataComputeDisksDemo(disksList ListComputeDisks, extraDisks []interface{}) []map[string]interface{} {
res := make([]map[string]interface{}, 0)
for _, disk := range disksList {
if findInExtraDisks(uint(disk.ID), extraDisks) { //skip main bootdisk and extraDisks
continue
}
temp := map[string]interface{}{
"disk_name": disk.Name,
"disk_id": disk.ID,
"disk_type": disk.Type,
"sep_id": disk.SepID,
"shareable": disk.Shareable,
"size_max": disk.SizeMax,
"size_used": disk.SizeUsed,
"pool": disk.Pool,
"desc": disk.Description,
"image_id": disk.ImageID,
"size": disk.SizeMax,
}
res = append(res, temp)
}
return res
}
func flattenACL(acl RecordACL) []map[string]interface{} {
func flattenACL(acl compute.RecordACL) []map[string]interface{} {
res := make([]map[string]interface{}, 0)
temp := map[string]interface{}{
"account_acl": flattenListACL(acl.AccountACL),
@@ -413,7 +400,7 @@ func flattenACL(acl RecordACL) []map[string]interface{} {
return res
}
func flattenAffinityRules(affinityRules ListRules) []map[string]interface{} {
func flattenAffinityRules(affinityRules compute.ListRules) []map[string]interface{} {
res := make([]map[string]interface{}, 0)
for _, affinityRule := range affinityRules {
temp := map[string]interface{}{
@@ -430,7 +417,7 @@ func flattenAffinityRules(affinityRules ListRules) []map[string]interface{} {
return res
}
func flattenIotune(iotune IOTune) []map[string]interface{} {
func flattenIotune(iotune compute.IOTune) []map[string]interface{} {
res := make([]map[string]interface{}, 0)
temp := map[string]interface{}{
"read_bytes_sec": iotune.ReadBytesSec,
@@ -452,7 +439,7 @@ func flattenIotune(iotune IOTune) []map[string]interface{} {
return res
}
func flattenSnapshots(snapshots SnapshotExtendList) []map[string]interface{} {
func flattenSnapshots(snapshots compute.SnapshotExtendList) []map[string]interface{} {
res := make([]map[string]interface{}, 0)
for _, snapshot := range snapshots {
temp := map[string]interface{}{
@@ -469,7 +456,7 @@ func flattenSnapshots(snapshots SnapshotExtendList) []map[string]interface{} {
return res
}
func flattenListComputeDisks(disks ListComputeDisks) []map[string]interface{} {
func flattenListComputeDisks(disks compute.ListComputeDisks) []map[string]interface{} {
res := make([]map[string]interface{}, 0)
for _, disk := range disks {
acl, _ := json.Marshal(disk.ACL)
@@ -532,7 +519,7 @@ func flattenCustomFields(customFileds map[string]interface{}) []map[string]inter
}
return res
}
func flattenOsUsers(osUsers ListOSUser) []map[string]interface{} {
func flattenOsUsers(osUsers compute.ListOSUser) []map[string]interface{} {
res := make([]map[string]interface{}, 0)
for _, user := range osUsers {
temp := map[string]interface{}{
@@ -546,72 +533,72 @@ func flattenOsUsers(osUsers ListOSUser) []map[string]interface{} {
return res
}
func flattenDataCompute(d *schema.ResourceData, compute RecordCompute) {
devices, _ := json.Marshal(compute.Devices)
userdata, _ := json.Marshal(compute.Userdata)
d.Set("acl", flattenACL(compute.ACL))
d.Set("account_id", compute.AccountID)
d.Set("account_name", compute.AccountName)
d.Set("affinity_label", compute.AffinityLabel)
d.Set("affinity_rules", flattenAffinityRules(compute.AffinityRules))
d.Set("affinity_weight", compute.AffinityWeight)
d.Set("anti_affinity_rules", flattenListRules(compute.AntiAffinityRules))
d.Set("arch", compute.Architecture)
d.Set("boot_order", compute.BootOrder)
d.Set("bootdisk_size", compute.BootDiskSize)
d.Set("clone_reference", compute.CloneReference)
d.Set("clones", compute.Clones)
d.Set("computeci_id", compute.ComputeCIID)
d.Set("cpus", compute.CPU)
d.Set("created_by", compute.CreatedBy)
d.Set("created_time", compute.CreatedTime)
d.Set("custom_fields", flattenCustomFields(compute.CustomFields))
d.Set("deleted_by", compute.DeletedBy)
d.Set("deleted_time", compute.DeletedTime)
d.Set("desc", compute.Description)
func flattenDataCompute(d *schema.ResourceData, computeRec compute.RecordCompute) {
devices, _ := json.Marshal(computeRec.Devices)
userdata, _ := json.Marshal(computeRec.Userdata)
d.Set("acl", flattenACL(computeRec.ACL))
d.Set("account_id", computeRec.AccountID)
d.Set("account_name", computeRec.AccountName)
d.Set("affinity_label", computeRec.AffinityLabel)
d.Set("affinity_rules", flattenAffinityRules(computeRec.AffinityRules))
d.Set("affinity_weight", computeRec.AffinityWeight)
d.Set("anti_affinity_rules", flattenListRules(computeRec.AntiAffinityRules))
d.Set("arch", computeRec.Architecture)
d.Set("boot_order", computeRec.BootOrder)
d.Set("bootdisk_size", computeRec.BootDiskSize)
d.Set("clone_reference", computeRec.CloneReference)
d.Set("clones", computeRec.Clones)
d.Set("computeci_id", computeRec.ComputeCIID)
d.Set("cpus", computeRec.CPU)
d.Set("created_by", computeRec.CreatedBy)
d.Set("created_time", computeRec.CreatedTime)
d.Set("custom_fields", flattenCustomFields(computeRec.CustomFields))
d.Set("deleted_by", computeRec.DeletedBy)
d.Set("deleted_time", computeRec.DeletedTime)
d.Set("desc", computeRec.Description)
d.Set("devices", string(devices))
d.Set("disks", flattenListComputeDisks(compute.Disks))
d.Set("driver", compute.Driver)
d.Set("gid", compute.GID)
d.Set("guid", compute.GUID)
d.Set("compute_id", compute.ID)
d.Set("image_id", compute.ImageID)
d.Set("interfaces", flattenInterfaces(compute.Interfaces))
d.Set("lock_status", compute.LockStatus)
d.Set("manager_id", compute.ManagerID)
d.Set("manager_type", compute.ManagerType)
d.Set("migrationjob", compute.MigrationJob)
d.Set("milestones", compute.Milestones)
d.Set("name", compute.Name)
d.Set("natable_vins_id", compute.NatableVINSID)
d.Set("natable_vins_ip", compute.NatableVINSIP)
d.Set("natable_vins_name", compute.NatableVINSName)
d.Set("natable_vins_network", compute.NatableVINSNetwork)
d.Set("natable_vins_network_name", compute.NatableVINSNetworkName)
d.Set("os_users", flattenOsUsers(compute.OSUsers))
d.Set("pinned", compute.Pinned)
d.Set("ram", compute.RAM)
d.Set("reference_id", compute.ReferenceID)
d.Set("registered", compute.Registered)
d.Set("res_name", compute.ResName)
d.Set("rg_id", compute.RGID)
d.Set("rg_name", compute.RGName)
d.Set("snap_sets", flattenSnapSets(compute.SnapSets))
d.Set("stateless_sep_id", compute.StatelessSepID)
d.Set("stateless_sep_type", compute.StatelessSepType)
d.Set("status", compute.Status)
d.Set("tags", compute.Tags)
d.Set("tech_status", compute.TechStatus)
d.Set("updated_by", compute.UpdatedBy)
d.Set("updated_time", compute.UpdatedTime)
d.Set("user_managed", compute.UserManaged)
d.Set("disks", flattenListComputeDisks(computeRec.Disks))
d.Set("driver", computeRec.Driver)
d.Set("gid", computeRec.GID)
d.Set("guid", computeRec.GUID)
d.Set("compute_id", computeRec.ID)
d.Set("image_id", computeRec.ImageID)
d.Set("interfaces", flattenInterfaces(computeRec.Interfaces))
d.Set("lock_status", computeRec.LockStatus)
d.Set("manager_id", computeRec.ManagerID)
d.Set("manager_type", computeRec.ManagerType)
d.Set("migrationjob", computeRec.MigrationJob)
d.Set("milestones", computeRec.Milestones)
d.Set("name", computeRec.Name)
d.Set("natable_vins_id", computeRec.NatableVINSID)
d.Set("natable_vins_ip", computeRec.NatableVINSIP)
d.Set("natable_vins_name", computeRec.NatableVINSName)
d.Set("natable_vins_network", computeRec.NatableVINSNetwork)
d.Set("natable_vins_network_name", computeRec.NatableVINSNetworkName)
d.Set("os_users", flattenOsUsers(computeRec.OSUsers))
d.Set("pinned", computeRec.Pinned)
d.Set("ram", computeRec.RAM)
d.Set("reference_id", computeRec.ReferenceID)
d.Set("registered", computeRec.Registered)
d.Set("res_name", computeRec.ResName)
d.Set("rg_id", computeRec.RGID)
d.Set("rg_name", computeRec.RGName)
d.Set("snap_sets", flattenSnapSets(computeRec.SnapSets))
d.Set("stateless_sep_id", computeRec.StatelessSepID)
d.Set("stateless_sep_type", computeRec.StatelessSepType)
d.Set("status", computeRec.Status)
d.Set("tags", computeRec.Tags)
d.Set("tech_status", computeRec.TechStatus)
d.Set("updated_by", computeRec.UpdatedBy)
d.Set("updated_time", computeRec.UpdatedTime)
d.Set("user_managed", computeRec.UserManaged)
d.Set("userdata", string(userdata))
d.Set("vgpus", compute.VGPUs)
d.Set("virtual_image_id", compute.VirtualImageID)
d.Set("virtual_image_name", compute.VirtualImageName)
d.Set("vgpus", computeRec.VGPUs)
d.Set("virtual_image_id", computeRec.VirtualImageID)
d.Set("virtual_image_name", computeRec.VirtualImageName)
}
func flattenComputeAudits(computeAudits ListAudits) []map[string]interface{} {
func flattenComputeAudits(computeAudits compute.ListAudits) []map[string]interface{} {
res := make([]map[string]interface{}, 0)
for _, computeAudit := range computeAudits {
temp := map[string]interface{}{
@@ -626,7 +613,7 @@ func flattenComputeAudits(computeAudits ListAudits) []map[string]interface{} {
return res
}
func flattenPfwList(computePfws ListPFWs) []map[string]interface{} {
func flattenPfwList(computePfws compute.ListPFWs) []map[string]interface{} {
res := make([]map[string]interface{}, 0)
for _, computePfw := range computePfws {
temp := map[string]interface{}{
@@ -643,13 +630,13 @@ func flattenPfwList(computePfws ListPFWs) []map[string]interface{} {
return res
}
func flattenUserList(d *schema.ResourceData, userList RecordACL) {
func flattenUserList(d *schema.ResourceData, userList compute.RecordACL) {
d.Set("account_acl", flattenListACL(userList.AccountACL))
d.Set("compute_acl", flattenListACL(userList.ComputeACL))
d.Set("rg_acl", flattenListACL(userList.RGACL))
}
func flattenComputeGetAudits(computeAudits ListShortAudits) []map[string]interface{} {
func flattenComputeGetAudits(computeAudits compute.ListShortAudits) []map[string]interface{} {
res := make([]map[string]interface{}, 0)
for _, computeAudit := range computeAudits {
temp := map[string]interface{}{
@@ -661,9 +648,9 @@ func flattenComputeGetAudits(computeAudits ListShortAudits) []map[string]interfa
return res
}
func flattenSnapshotUsage(computeSnapshotUasges ListUsageSnapshots) []map[string]interface{} {
func flattenSnapshotUsage(computeSnapshotUsages compute.ListUsageSnapshots) []map[string]interface{} {
res := make([]map[string]interface{}, 0)
for _, computeUsage := range computeSnapshotUasges {
for _, computeUsage := range computeSnapshotUsages {
temp := map[string]interface{}{
"count": computeUsage.Count,
"stored": computeUsage.Stored,

File diff suppressed because it is too large Load Diff

View File

@@ -34,11 +34,12 @@ package kvmvm
import (
log "github.com/sirupsen/logrus"
"repository.basistech.ru/BASIS/decort-golang-sdk/pkg/cloudapi/compute"
"github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema"
)
func parseOsUsers(logins ListOSUser) []interface{} {
func parseOsUsers(logins compute.ListOSUser) []interface{} {
var result = make([]interface{}, len(logins))
for index, value := range logins {

View File

@@ -34,89 +34,68 @@ package kvmvm
import (
"context"
"encoding/json"
"net/url"
"github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema"
"repository.basistech.ru/BASIS/decort-golang-sdk/pkg/cloudapi/extnet"
"repository.basistech.ru/BASIS/decort-golang-sdk/pkg/cloudapi/image"
"repository.basistech.ru/BASIS/decort-golang-sdk/pkg/cloudapi/rg"
"repository.basistech.ru/BASIS/decort-golang-sdk/pkg/cloudapi/vins"
"repository.basistech.ru/BASIS/terraform-provider-decort/internal/controller"
)
func existRgID(ctx context.Context, d *schema.ResourceData, m interface{}) bool {
func existRgID(ctx context.Context, d *schema.ResourceData, m interface{}) (bool, error) {
c := m.(*controller.ControllerCfg)
urlValues := &url.Values{}
rgList := []struct {
ID int `json:"id"`
}{}
rgId := uint64(d.Get("rg_id").(int))
req := rg.ListRequest{
IncludeDeleted: false,
}
rgListAPI := "/restmachine/cloudapi/rg/list"
urlValues.Add("includedeleted", "false")
rgListRaw, err := c.DecortAPICall(ctx, "POST", rgListAPI, urlValues)
rgList, err := c.CloudAPI().RG().List(ctx, req)
if err != nil {
return false
return false, err
}
err = json.Unmarshal([]byte(rgListRaw), &rgList)
if err != nil {
return false
}
rgId := d.Get("rg_id").(int)
for _, rg := range rgList {
if rg.ID == rgId {
return true
}
}
return false
return len(rgList.FilterByID(rgId)) != 0, nil
}
func existImageId(ctx context.Context, d *schema.ResourceData, m interface{}) bool {
func existImageId(ctx context.Context, d *schema.ResourceData, m interface{}) (bool, error) {
c := m.(*controller.ControllerCfg)
urlValues := &url.Values{}
imageList := []struct {
ID int `json:"id"`
}{}
imageListAPI := "/restmachine/cloudapi/image/list"
imageListRaw, err := c.DecortAPICall(ctx, "POST", imageListAPI, urlValues)
imageId := uint64(d.Get("image_id").(int))
req := image.ListRequest{}
imageList, err := c.CloudAPI().Image().List(ctx, req)
if err != nil {
return false
return false, err
}
err = json.Unmarshal([]byte(imageListRaw), &imageList)
if err != nil {
return false
}
imageId := d.Get("image_id").(int)
for _, image := range imageList {
if image.ID == imageId {
return true
}
}
return false
return len(imageList.FilterByID(imageId)) != 0, nil
}
func existVinsIdInList(vinsId int, vinsList []struct {
ID int `json:"id"`
}) bool {
func existVinsIdInList(vinsId uint64, vinsList vins.ListVINS) bool {
for _, vins := range vinsList {
if vinsId == vins.ID {
return true
}
}
return false
}
func existExtNetIdInList(extId uint64, extList extnet.ListExtNets) bool {
for _, ext := range extList {
if extId == ext.ID {
return true
}
}
return false
}
func existVinsId(ctx context.Context, d *schema.ResourceData, m interface{}) (int, bool) {
c := m.(*controller.ControllerCfg)
urlValues := &url.Values{}
req := vins.ListRequest{IncludeDeleted: false}
vinsListAPI := "/restmachine/cloudapi/vins/list"
urlValues.Add("includeDeleted", "false")
vinsList := []struct {
ID int `json:"id"`
}{}
vinsListRaw, err := c.DecortAPICall(ctx, "POST", vinsListAPI, urlValues)
if err != nil {
return 0, false
}
err = json.Unmarshal([]byte(vinsListRaw), &vinsList)
vinsList, err := c.CloudAPI().VINS().List(ctx, req)
if err != nil {
return 0, false
}
@@ -124,11 +103,32 @@ func existVinsId(ctx context.Context, d *schema.ResourceData, m interface{}) (in
networks := d.Get("network").(*schema.Set).List()
for _, networkInterface := range networks {
networkItem := networkInterface.(map[string]interface{})
if !existVinsIdInList(networkItem["net_id"].(int), vinsList) {
if !existVinsIdInList(uint64(networkItem["net_id"].(int)), vinsList) {
return networkItem["net_id"].(int), false
}
}
return 0, true
}
func existExtNetId(ctx context.Context, d *schema.ResourceData, m interface{}) (int, bool) {
c := m.(*controller.ControllerCfg)
req := extnet.ListRequest{}
extNetList, err := c.CloudAPI().ExtNet().List(ctx, req)
if err != nil {
return 0, false
}
networks := d.Get("network").(*schema.Set).List()
for _, networkInterface := range networks {
networkItem := networkInterface.(map[string]interface{})
if !existExtNetIdInList(uint64(networkItem["net_id"].(int)), extNetList) {
return networkItem["net_id"].(int), false
}
}
return 0, true
}

File diff suppressed because it is too large Load Diff

View File

@@ -34,30 +34,20 @@ package kvmvm
import (
"context"
"encoding/json"
"fmt"
"net/url"
"strconv"
"repository.basistech.ru/BASIS/terraform-provider-decort/internal/controller"
log "github.com/sirupsen/logrus"
"repository.basistech.ru/BASIS/decort-golang-sdk/pkg/cloudapi/compute"
"repository.basistech.ru/BASIS/terraform-provider-decort/internal/controller"
"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
@@ -69,12 +59,14 @@ func utilityComputeExtraDisksConfigure(ctx context.Context, d *schema.ResourceDa
}
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)
computeId, _ := strconv.ParseUint(d.Id(), 10, 64)
req := compute.DiskAttachRequest{
ComputeID: computeId,
DiskID: uint64(disk.(int)),
}
_, err := c.CloudAPI().Compute().DiskAttach(ctx, req)
if err != nil {
// failed to attach extra disk - partial resource update
apiErrCount++
lastSavedError = err
}
@@ -93,29 +85,34 @@ func utilityComputeExtraDisksConfigure(ctx context.Context, d *schema.ResourceDa
log.Debugf("utilityComputeExtraDisksConfigure: detach set has %d items for Compute ID %s", detach_set.Len(), d.Id())
if detach_set.Len() > 0 {
urlValues := &url.Values{}
urlValues.Add("computeId", d.Id())
urlValues.Add("force", "false")
_, err := c.DecortAPICall(ctx, "POST", ComputeStopAPI, urlValues)
computeId, _ := strconv.ParseUint(d.Id(), 10, 64)
stopReq := compute.StopRequest{
ComputeID: computeId,
Force: false,
}
_, err := c.CloudAPI().Compute().Stop(ctx, stopReq)
if err != nil {
return err
}
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)
req := compute.DiskDetachRequest{
ComputeID: computeId,
DiskID: uint64(diskId.(int)),
}
_, err := c.CloudAPI().Compute().DiskDetach(ctx, req)
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
}
}
urlValues = &url.Values{}
urlValues.Add("computeId", d.Id())
urlValues.Add("altBootId", "0")
_, err = c.DecortAPICall(ctx, "POST", ComputeStartAPI, urlValues)
req := compute.StartRequest{
ComputeID: computeId,
AltBootID: 0,
}
_, err = c.CloudAPI().Compute().Start(ctx, req)
if err != nil {
return err
}
@@ -124,12 +121,14 @@ func utilityComputeExtraDisksConfigure(ctx context.Context, d *schema.ResourceDa
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)
computeId, _ := strconv.ParseUint(d.Id(), 10, 64)
req := compute.DiskAttachRequest{
ComputeID: computeId,
DiskID: uint64(diskId.(int)),
}
_, err := c.CloudAPI().Compute().DiskAttach(ctx, req)
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
@@ -146,12 +145,6 @@ func utilityComputeExtraDisksConfigure(ctx context.Context, d *schema.ResourceDa
}
func utilityComputeNetworksConfigure(ctx context.Context, d *schema.ResourceData, m interface{}, do_delta bool, skip_zero 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")
@@ -168,18 +161,20 @@ func utilityComputeNetworksConfigure(ctx context.Context, d *schema.ResourceData
if i == 0 && skip_zero {
continue
}
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))
computeId, _ := strconv.ParseUint(d.Id(), 10, 64)
req := compute.NetAttachRequest{
ComputeID: computeId,
NetType: net_data["net_type"].(string),
NetID: uint64(net_data["net_id"].(int)),
}
_, err := c.DecortAPICall(ctx, "POST", ComputeNetAttachAPI, urlValues)
ipaddr, ipSet := net_data["ip_address"]
if ipSet {
req.IPAddr = ipaddr.(string)
}
_, err := c.CloudAPI().Compute().NetAttach(ctx, req)
if err != nil {
// failed to attach network - partial resource update
apiErrCount++
lastSavedError = err
}
@@ -196,14 +191,16 @@ func utilityComputeNetworksConfigure(ctx context.Context, d *schema.ResourceData
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)
computeId, _ := strconv.ParseUint(d.Id(), 10, 64)
req := compute.NetDetachRequest{
ComputeID: computeId,
IPAddr: net_data["ip_address"].(string),
MAC: net_data["mac"].(string),
}
_, err := c.CloudAPI().Compute().NetDetach(ctx, req)
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++
@@ -214,17 +211,20 @@ func utilityComputeNetworksConfigure(ctx context.Context, d *schema.ResourceData
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))
computeId, _ := strconv.ParseUint(d.Id(), 10, 64)
req := compute.NetAttachRequest{
ComputeID: computeId,
NetType: net_data["net_type"].(string),
NetID: uint64(net_data["net_id"].(int)),
}
_, err := c.DecortAPICall(ctx, "POST", ComputeNetAttachAPI, urlValues)
if net_data["ip_address"].(string) != "" {
req.IPAddr = net_data["ip_address"].(string)
}
_, err := c.CloudAPI().Compute().NetAttach(ctx, req)
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++
@@ -241,20 +241,17 @@ func utilityComputeNetworksConfigure(ctx context.Context, d *schema.ResourceData
return nil
}
func utilityComputeCheckPresence(ctx context.Context, d *schema.ResourceData, m interface{}) (RecordCompute, error) {
func utilityComputeCheckPresence(ctx context.Context, d *schema.ResourceData, m interface{}) (compute.RecordCompute, error) {
c := m.(*controller.ControllerCfg)
urlValues := &url.Values{}
compute := &RecordCompute{}
urlValues.Add("computeId", d.Id())
computeRaw, err := c.DecortAPICall(ctx, "POST", ComputeGetAPI, urlValues)
if err != nil {
return *compute, err
computeId, _ := strconv.ParseUint(d.Id(), 10, 64)
req := compute.GetRequest{
ComputeID: computeId,
}
err = json.Unmarshal([]byte(computeRaw), &compute)
computeRecord, err := c.CloudAPI().Compute().Get(ctx, req)
if err != nil {
return *compute, err
return *computeRecord, err
}
return *compute, nil
return *computeRecord, nil
}

Some files were not shown because too many files have changed in this diff Show More