From f49d9f8860693960f4b652133539887c12e73ce7 Mon Sep 17 00:00:00 2001 From: loskutovanl Date: Tue, 19 Dec 2023 16:37:50 +0300 Subject: [PATCH] 4.5.2 --- CHANGELOG.md | 56 +- Makefile | 2 +- go.mod | 3 +- go.sum | 6 +- internal/controller/controller.go | 141 +- .../cloudapi/account/data_source_account.go | 5 + .../data_source_account_audits_list.go | 255 +-- .../data_source_account_computes_list.go | 515 +++--- .../data_source_account_consumed_units.go | 226 +-- ...a_source_account_consumed_units_by_type.go | 181 +- .../data_source_account_deleted_list.go | 155 +- .../account/data_source_account_disks_list.go | 343 ++-- .../data_source_account_flipgroups_list.go | 505 +++--- ...source_account_get_resource_consumption.go | 1 + .../account/data_source_account_list.go | 419 ++--- .../data_source_account_reserved_units.go | 226 +-- ...ource_account_resource_consumption_list.go | 1 + .../account/data_source_account_rg_list.go | 743 ++++---- .../data_source_account_templates_list.go | 371 ++-- .../account/data_source_account_vins_list.go | 445 ++--- .../cloudapi/account/resource_account.go | 1297 +++++++------- .../cloudapi/bservice/data_source_bservice.go | 595 +++---- .../data_source_bservice_deleted_list.go | 169 +- .../bservice/data_source_bservice_group.go | 609 +++---- .../bservice/data_source_bservice_list.go | 527 +++--- .../data_source_bservice_snapshot_list.go | 215 +-- .../cloudapi/bservice/resource_bservice.go | 1426 ++++++++-------- .../bservice/resource_bservice_group.go | 1241 +++++++------- .../cloudapi/disks/data_source_disk.go | 1 + .../cloudapi/disks/data_source_disk_list.go | 999 +++++------ .../disks/data_source_disk_list_types.go | 1 + .../data_source_disk_list_types_detailed.go | 17 +- .../disks/data_source_disk_list_unattached.go | 6 + .../disks/data_source_disk_snapshot.go | 1 + .../disks/data_source_disk_snapshot_list.go | 1 + .../disks/data_source_list_deleted.go | 1 + internal/service/cloudapi/disks/flattens.go | 1 + .../service/cloudapi/disks/resource_disk.go | 14 +- .../cloudapi/disks/resource_disk_snapshot.go | 13 +- .../cloudapi/extnet/data_source_extnet.go | 571 +++---- .../data_source_extnet_computes_list.go | 323 ++-- .../extnet/data_source_extnet_default.go | 171 +- .../extnet/data_source_extnet_list.go | 295 ++-- internal/service/cloudapi/extnet/flattens.go | 3 +- .../flipgroup/data_source_flipgroup.go | 38 +- .../flipgroup/data_source_flipgroup_list.go | 7 + .../service/cloudapi/flipgroup/flattens.go | 14 + .../cloudapi/flipgroup/resource_flipgroup.go | 40 +- .../cloudapi/image/data_source_image.go | 7 +- .../cloudapi/image/data_source_image_list.go | 319 ++-- internal/service/cloudapi/image/flattens.go | 18 +- .../service/cloudapi/image/resource_image.go | 550 +++--- .../service/cloudapi/k8s/data_source_k8s.go | 5 + .../cloudapi/k8s/data_source_k8s_list.go | 4 + .../cloudapi/k8s/data_source_k8s_wg.go | 1 + .../k8s/data_source_k8s_wg_cloud_init.go | 1 + .../cloudapi/k8s/data_source_k8s_wg_list.go | 1 + internal/service/cloudapi/k8s/flattens.go | 14 +- .../service/cloudapi/k8s/node_subresource.go | 18 +- internal/service/cloudapi/k8s/old_schemas.go | 20 +- internal/service/cloudapi/k8s/resource_k8s.go | 27 +- .../service/cloudapi/k8s/resource_k8s_cp.go | 28 +- .../service/cloudapi/k8s/resource_k8s_wg.go | 29 +- internal/service/cloudapi/k8s/utility_k8s.go | 15 + .../cloudapi/kvmvm/data_source_compute.go | 9 + .../kvmvm/data_source_compute_audits.go | 1 + .../kvmvm/data_source_compute_get_audits.go | 1 + .../data_source_compute_get_console_url.go | 5 +- .../kvmvm/data_source_compute_get_log.go | 1 + .../kvmvm/data_source_compute_list.go | 1 + .../kvmvm/data_source_compute_list_deleted.go | 1 + .../data_source_compute_pci_device_list.go | 9 +- .../kvmvm/data_source_compute_pfw_list.go | 1 + .../data_source_compute_snapshot_usage.go | 1 + .../kvmvm/data_source_compute_user_list.go | 1 + .../kvmvm/data_source_compute_vgpu_list.go | 14 +- internal/service/cloudapi/kvmvm/flattens.go | 32 +- .../cloudapi/kvmvm/resource_compute.go | 468 +++-- .../service/cloudapi/kvmvm/utility_compute.go | 69 +- .../service/cloudapi/lb/data_source_lb.go | 141 +- .../cloudapi/lb/data_source_lb_list.go | 141 +- .../lb/data_source_lb_list_deleted.go | 141 +- internal/service/cloudapi/lb/resource_lb.go | 899 +++++----- .../cloudapi/lb/resource_lb_backend.go | 753 +++++---- .../cloudapi/lb/resource_lb_backend_server.go | 634 +++---- .../cloudapi/lb/resource_lb_frontend.go | 386 ++--- .../cloudapi/lb/resource_lb_frontend_bind.go | 427 ++--- .../locations/data_source_locations_list.go | 371 ++-- .../locations/data_source_locations_url.go | 169 +- .../service/cloudapi/rg/data_source_rg.go | 318 ++-- .../data_source_rg_affinity_group_computes.go | 2 +- .../rg/data_source_rg_affinity_groups_get.go | 2 +- .../rg/data_source_rg_affinity_groups_list.go | 1 + .../cloudapi/rg/data_source_rg_audits.go | 2 +- ...data_source_rg_get_resource_consumption.go | 1 + .../cloudapi/rg/data_source_rg_list.go | 567 +++---- .../rg/data_source_rg_list_computes.go | 1 + .../rg/data_source_rg_list_deleted.go | 12 +- .../cloudapi/rg/data_source_rg_list_lb.go | 9 + .../cloudapi/rg/data_source_rg_list_pfw.go | 1 + .../cloudapi/rg/data_source_rg_list_vins.go | 1 + ...ata_source_rg_resource_consumption_list.go | 1 + .../cloudapi/rg/data_source_rg_usage.go | 1 + internal/service/cloudapi/rg/flattens.go | 4 +- internal/service/cloudapi/rg/models.go | 1498 ++++++++--------- internal/service/cloudapi/rg/old_schemas.go | 292 ++++ .../service/cloudapi/rg/quota_subresource.go | 79 +- internal/service/cloudapi/rg/resource_rg.go | 372 ++-- .../service/cloudapi/rg/state_upgraders.go | 28 + internal/service/cloudapi/rg/utility_rg.go | 48 +- .../cloudapi/stack/data_source_stack.go | 220 +-- .../cloudapi/stack/data_source_stack_list.go | 273 +-- internal/service/cloudapi/stack/flattens.go | 138 +- .../cloudapi/vins/data_source_static_route.go | 215 +-- .../vins/data_source_static_route_list.go | 243 +-- .../service/cloudapi/vins/data_source_vins.go | 58 + .../cloudapi/vins/data_source_vins_audits.go | 1 + .../vins/data_source_vins_ext_net_list.go | 1 + .../cloudapi/vins/data_source_vins_ip_list.go | 1 + .../cloudapi/vins/data_source_vins_list.go | 1 + .../vins/data_source_vins_list_deleted.go | 1 + .../vins/data_source_vins_nat_rule_list.go | 1 + internal/service/cloudapi/vins/flattens.go | 22 +- .../cloudapi/vins/resource_static_route.go | 553 +++--- .../service/cloudapi/vins/resource_vins.go | 154 +- .../service/cloudapi/vins/utility_vins.go | 5 +- .../cloudapi/vins/utility_vins_audits.go | 4 +- .../vins/utility_vins_ext_net_list.go | 4 +- .../cloudapi/vins/utility_vins_ip_list.go | 4 +- .../vins/utility_vins_nat_rule_list.go | 4 +- .../cloudbroker/kvmvm/utility_compute.go | 79 +- .../main.tf | 13 +- samples/cloudapi/data_disk_list_types/main.tf | 6 - .../data_disk_list_types_detailed/main.tf | 18 - samples/cloudapi/data_k8s_wg/main.tf | 2 +- samples/cloudapi/data_kvmvm/main.tf | 2 +- samples/cloudapi/data_kvmvm_audits/main.tf | 2 +- .../cloudapi/data_kvmvm_get_audits/main.tf | 2 +- .../data_kvmvm_get_console_url/main.tf | 2 +- samples/cloudapi/data_kvmvm_get_log/main.tf | 2 +- samples/cloudapi/data_kvmvm_list/main.tf | 2 +- samples/cloudapi/data_kvmvm_pfw_list/main.tf | 2 +- samples/cloudapi/data_kvmvm_user_list/main.tf | 2 +- samples/cloudapi/resource_account/main.tf | 6 - samples/cloudapi/resource_bservice/main.tf | 3 - samples/cloudapi/resource_image/main.tf | 5 + .../cloudapi/resource_image_virtual/main.tf | 14 +- samples/cloudapi/resource_k8s/main.tf | 6 +- samples/cloudapi/resource_kvmvm/main.tf | 5 + samples/cloudapi/resource_rg/main.tf | 11 + 150 files changed, 12564 insertions(+), 11691 deletions(-) create mode 100644 internal/service/cloudapi/rg/old_schemas.go create mode 100644 internal/service/cloudapi/rg/state_upgraders.go diff --git a/CHANGELOG.md b/CHANGELOG.md index fc991bf..db6876b 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,24 +1,36 @@ -## Version 4.5.1 - -## Feature -- Refactoring BVS config -- Added and updated data sources and resources for cloudbroker groups: - * account - * audit - * disks - * extnet - * flipgroup - * grid - * image - * k8ci - * k8s - * kvmvm (compute) - * lb (load balancer) - * pcidevice - * rg (resource group) - * sep - * stack - * vins +## Version 4.5.2 ### Bugfix -- Fixed description update for compute in cloudapi/kvmvm +- Added resource_limits.cu_dm string field for account, account_consumed_units and account_reserved_units data sources in cloudapi/account +- Fixed restore of account resource in cloudapi/account, it happens if restore parameter is set to true +- Fixed restore of bservice resource in cloudapi/bservice, it happens if restore parameter is set to true and only once +- Fixed enable of bservice resource in cloudapi/bservice, it happens if enable parameter is set to true +- Fixed terraform state update for bservice resource update in cloudapi/bservice +- Fixed terraform state update for bservice_group resource update in cloudapi/bservice +- Added entry_count field for bservice_snapshot_list data source in cloudapi/bservice +- Added items.shareable boolean field for disk_list_unattached data source in cloudapi/disks +- Added items.status string field for extnet_list data source in cloudapi/extnet +- Fixed multiple minor typos in samples/cloudapi +- Added account_name string, created_by string, created_time int, deleted_by string, deleted_time int, network string, rg_id int, rg_name string, updated_by string, updated_by int fields for flipgroup data source and resource in cloudapi/flipgroup +- Removed net_mask string, ckey string fields for flipgroup data source and resource in cloudapi/flipgroup +- Add meta list field for flipgroup_list data source in cloudapi/flipgroup +- Fixed net_mask string field for fligroup_list data source in cloudapi/flipgroup +- Fixed id string field for image data source in cloudapi/image +- Fix account_name string field for k8s_list data source in cloudapi/k8s +- Add network_plugin string field for k8s and k8s_list data sources in cloudapi/k8s +- Fixed terraform state update for k8s, k8_cp and k8s_wg resources update in cloudapi/k8s +- Add image_name string, interfaces.enabled boolean fields for compute data source in cloudapi/kvmvm +- Add the interfaces field to the creation request in cloudapi/kvmvm +- Fixed restore of kvmvm resource in cloudapi/kvmvm, it happens if restore parameter is set to true +- The logic of network connection has been changed, only the first network connects to the kvmvm in the stopped status, the subsequent ones connect without stopping +- Token receipt has been removed from the controller +- Add start/stop function after create for lb in cloudapi/lb +- Fixed restore of lb resource in cloudapi/lb, it happens if restore parameter is set to true +- Add field auth_broker in data source location list in cloudapi/location +- Add fields cpu_allocation_parameter and cpu_allocation_ratio in data source rg list lb deleted in cloudapi/rg +- Add fields backend_haip and frontend_haip in data source rg list in cloudapi/rg +- Change type field Ram QuotaRecord struct in cloudapi/rg/models +- Add state upgrader for rg in cloudapi/rg +- Add field owner to the creation request in cloudapi/rg +- Fixed restore of rg resource in cloudapi/rg, it happens if restore parameter is set to true +- Add fields enabled and routesroutes in data source vins in cloudapi/vins \ No newline at end of file diff --git a/Makefile b/Makefile index f17baf6..5517689 100644 --- a/Makefile +++ b/Makefile @@ -7,7 +7,7 @@ ZIPDIR = ./zip BINARY=${NAME} WORKPATH= ./examples/terraform.d/plugins/${HOSTNAME}/${NAMESPACE}/${NAMESPACE}/${VERSION}/${OS_ARCH} MAINPATH = ./cmd/decort/ -VERSION=4.5.1 +VERSION=4.5.2 OS_ARCH=$(shell go env GOHOSTOS)_$(shell go env GOHOSTARCH) FILES = ${BINARY}_${VERSION}_darwin_amd64\ diff --git a/go.mod b/go.mod index 208badd..d6802aa 100644 --- a/go.mod +++ b/go.mod @@ -3,13 +3,12 @@ module repository.basistech.ru/BASIS/terraform-provider-decort go 1.18 require ( - github.com/golang-jwt/jwt/v4 v4.4.3 github.com/google/uuid v1.3.0 github.com/hashicorp/terraform-plugin-docs v0.13.0 github.com/hashicorp/terraform-plugin-sdk/v2 v2.24.1 github.com/sirupsen/logrus v1.9.0 golang.org/x/net v0.16.0 - repository.basistech.ru/BASIS/decort-golang-sdk v1.7.2 + repository.basistech.ru/BASIS/decort-golang-sdk v1.7.3 ) require ( diff --git a/go.sum b/go.sum index e5859a3..f7e9bac 100644 --- a/go.sum +++ b/go.sum @@ -58,8 +58,6 @@ github.com/go-playground/universal-translator v0.18.1/go.mod h1:xekY+UJKNuX9WP91 github.com/go-playground/validator/v10 v10.15.4 h1:zMXza4EpOdooxPel5xDqXEdXG5r+WggpvnAKMsalBjs= github.com/go-playground/validator/v10 v10.15.4/go.mod h1:9iXMNT7sEkjXb0I+enO7QXmzG6QCsPWY4zveKFVRSyU= github.com/go-test/deep v1.0.3 h1:ZrJSEWsXzPOxaZnFteGEfooLba+ju3FYIbOrS+rQd68= -github.com/golang-jwt/jwt/v4 v4.4.3 h1:Hxl6lhQFj4AnOX6MLrsCb/+7tCj7DxP7VA+2rDIq5AU= -github.com/golang-jwt/jwt/v4 v4.4.3/go.mod h1:m21LjoU+eqJr34lmDMbreY2eSTRJ1cv77w39/MY0Ch0= github.com/golang/protobuf v1.1.0/go.mod h1:6lQm79b+lXiMfvg/cZm0SGofjICqVBUtrP5yJMmIC1U= github.com/golang/protobuf v1.2.0/go.mod h1:6lQm79b+lXiMfvg/cZm0SGofjICqVBUtrP5yJMmIC1U= github.com/golang/protobuf v1.3.1/go.mod h1:6lQm79b+lXiMfvg/cZm0SGofjICqVBUtrP5yJMmIC1U= @@ -339,5 +337,5 @@ gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c/go.mod h1:K4uyk7z7BCEPqu6E+C gopkg.in/yaml.v3 v3.0.0/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA= gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= -repository.basistech.ru/BASIS/decort-golang-sdk v1.7.2 h1:Ll8MBcmDcElxxgxOUUaYbbafTSbIm4dcPEDLl4fdF8Q= -repository.basistech.ru/BASIS/decort-golang-sdk v1.7.2/go.mod h1:7fj8sgGZFiiExewQeqckCS4WxwOmU0oP6BO6mi1Lpkw= +repository.basistech.ru/BASIS/decort-golang-sdk v1.7.3 h1:NtvW72WsAezk0XYKE5+ag+xauIgKWKcbKLy7YTp5Fuc= +repository.basistech.ru/BASIS/decort-golang-sdk v1.7.3/go.mod h1:7fj8sgGZFiiExewQeqckCS4WxwOmU0oP6BO6mi1Lpkw= diff --git a/internal/controller/controller.go b/internal/controller/controller.go index d9614e7..226f359 100644 --- a/internal/controller/controller.go +++ b/internal/controller/controller.go @@ -21,7 +21,6 @@ limitations under the License. package controller import ( - "bytes" "crypto/tls" "fmt" "io" @@ -38,8 +37,6 @@ import ( "repository.basistech.ru/BASIS/decort-golang-sdk/pkg/cloudapi" "repository.basistech.ru/BASIS/decort-golang-sdk/pkg/cloudbroker" - jwt "github.com/golang-jwt/jwt/v4" - "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" ) @@ -204,27 +201,27 @@ func ControllerConfigure(d *schema.ResourceData) (*ControllerCfg, error) { case MODE_DECS3O: // on success getDECS3OJWT will set config.jwt to the obtained JWT, so there is no // need to set it once again here - _, err := ret_config.getDECS3OJWT() - if err != nil { - return nil, err - } + // _, err := ret_config.getDECS3OJWT() + // if err != nil { + // return nil, err + // } // we are not verifying the JWT when parsing because actual verification is done on the // OVC controller side. Here we do parsing solely to extract Oauth2 user name (claim "user") // and JWT issuer name (claim "iss") - parser := jwt.Parser{} - token, _, err := parser.ParseUnverified(ret_config.jwt, jwt.MapClaims{}) - if err != nil { - return nil, err - } - if claims, ok := token.Claims.(jwt.MapClaims); ok { - var tbuf bytes.Buffer - tbuf.WriteString(claims["username"].(string)) - tbuf.WriteString("@") - tbuf.WriteString(claims["iss"].(string)) - ret_config.decort_username = tbuf.String() - } else { - return nil, fmt.Errorf("failed to extract user and iss fields from JWT token in oauth2 mode") - } + // parser := jwt.Parser{} + // token, _, err := parser.ParseUnverified(ret_config.jwt, jwt.MapClaims{}) + // if err != nil { + // return nil, err + // } + // if claims, ok := token.Claims.(jwt.MapClaims); ok { + // var tbuf bytes.Buffer + // tbuf.WriteString(claims["username"].(string)) + // tbuf.WriteString("@") + // tbuf.WriteString(claims["iss"].(string)) + // ret_config.decort_username = tbuf.String() + // } else { + // return nil, fmt.Errorf("failed to extract user and iss fields from JWT token in oauth2 mode") + // } sdkConf := config.Config{ AppID: ret_config.app_id, @@ -263,57 +260,57 @@ func ControllerConfigure(d *schema.ResourceData) (*ControllerCfg, error) { return ret_config, nil } -func (config *ControllerCfg) GetDecortUsername() string { - return config.decort_username -} - -func (config *ControllerCfg) getDECS3OJWT() (string, error) { - // Obtain JWT from the Oauth2 provider using application ID and application secret provided in config. - if config.auth_mode_code == MODE_UNDEF { - return "", fmt.Errorf("getOAuth2JWT method called for undefined authorization mode") - } - if config.auth_mode_code != MODE_DECS3O { - return "", fmt.Errorf("getOAuth2JWT method called for incompatible authorization mode %q", config.auth_mode_txt) - } - - params := url.Values{} - params.Add("grant_type", "client_credentials") - params.Add("client_id", config.app_id) - params.Add("client_secret", config.app_secret) - params.Add("response_type", "id_token") - params.Add("validity", "3600") - params_str := params.Encode() - - req, err := http.NewRequest("POST", config.oauth2_url+"/v1/oauth/access_token", strings.NewReader(params_str)) - if err != nil { - return "", err - } - req.Header.Set("Content-Type", "application/x-www-form-urlencoded") - req.Header.Set("Content-Length", strconv.Itoa(len(params_str))) - - resp, err := config.cc_client.Do(req) - if err != nil { - return "", err - } - if resp.StatusCode != http.StatusOK { - // fmt.Println("response Status:", resp.Status) - // fmt.Println("response Headers:", resp.Header) - // fmt.Println("response Headers:", req.URL) - return "", fmt.Errorf("getOauth2JWT: unexpected status code %d when obtaining JWT from %q for APP_ID %q, request Body %q", - resp.StatusCode, req.URL, config.app_id, params_str) - } - defer resp.Body.Close() - - responseData, err := io.ReadAll(resp.Body) - if err != nil { - return "", err - } - - // validation successful - store JWT in the corresponding field of the ControllerCfg structure - config.jwt = strings.TrimSpace(string(responseData)) - - return config.jwt, nil -} +// func (config *ControllerCfg) GetDecortUsername() string { +// return config.decort_username +// } + +// func (config *ControllerCfg) getDECS3OJWT() (string, error) { +// // Obtain JWT from the Oauth2 provider using application ID and application secret provided in config. +// if config.auth_mode_code == MODE_UNDEF { +// return "", fmt.Errorf("getOAuth2JWT method called for undefined authorization mode") +// } +// if config.auth_mode_code != MODE_DECS3O { +// return "", fmt.Errorf("getOAuth2JWT method called for incompatible authorization mode %q", config.auth_mode_txt) +// } + +// params := url.Values{} +// params.Add("grant_type", "client_credentials") +// params.Add("client_id", config.app_id) +// params.Add("client_secret", config.app_secret) +// params.Add("response_type", "id_token") +// params.Add("validity", "3600") +// params_str := params.Encode() + +// req, err := http.NewRequest("POST", config.oauth2_url+"/v1/oauth/access_token", strings.NewReader(params_str)) +// if err != nil { +// return "", err +// } +// req.Header.Set("Content-Type", "application/x-www-form-urlencoded") +// req.Header.Set("Content-Length", strconv.Itoa(len(params_str))) + +// resp, err := config.cc_client.Do(req) +// if err != nil { +// return "", err +// } +// if resp.StatusCode != http.StatusOK { +// // fmt.Println("response Status:", resp.Status) +// // fmt.Println("response Headers:", resp.Header) +// // fmt.Println("response Headers:", req.URL) +// return "", fmt.Errorf("getOauth2JWT: unexpected status code %d when obtaining JWT from %q for APP_ID %q, request Body %q", +// resp.StatusCode, req.URL, config.app_id, params_str) +// } +// defer resp.Body.Close() + +// responseData, err := io.ReadAll(resp.Body) +// if err != nil { +// return "", err +// } + +// // validation successful - store JWT in the corresponding field of the ControllerCfg structure +// config.jwt = strings.TrimSpace(string(responseData)) + +// return config.jwt, nil +// } func (config *ControllerCfg) validateJWT(jwt string) (bool, error) { /* diff --git a/internal/service/cloudapi/account/data_source_account.go b/internal/service/cloudapi/account/data_source_account.go index da681df..af86671 100644 --- a/internal/service/cloudapi/account/data_source_account.go +++ b/internal/service/cloudapi/account/data_source_account.go @@ -45,6 +45,7 @@ import ( func dataSourceAccountRead(ctx context.Context, d *schema.ResourceData, m interface{}) diag.Diagnostics { acc, err := utilityAccountCheckPresence(ctx, d, m) if err != nil { + d.SetId("") return diag.FromErr(err) } @@ -99,6 +100,10 @@ func resourceLimitsSchemaMake() map[string]*schema.Schema { Type: schema.TypeFloat, Computed: true, }, + "cu_dm": { + Type: schema.TypeFloat, + Computed: true, + }, "cu_i": { Type: schema.TypeFloat, Computed: true, diff --git a/internal/service/cloudapi/account/data_source_account_audits_list.go b/internal/service/cloudapi/account/data_source_account_audits_list.go index 6a60efb..21ca7a5 100644 --- a/internal/service/cloudapi/account/data_source_account_audits_list.go +++ b/internal/service/cloudapi/account/data_source_account_audits_list.go @@ -1,127 +1,128 @@ -/* -Copyright (c) 2019-2022 Digital Energy Cloud Solutions LLC. All Rights Reserved. -Authors: -Petr Krutov, -Stanislav Solovev, -Kasim Baybikov, - -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 - -import ( - "context" - - "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 account.ListAudits) []map[string]interface{} { - res := make([]map[string]interface{}, 0) - for _, aa := range aal { - temp := map[string]interface{}{ - "call": aa.Call, - "responsetime": aa.ResponseTime, - "statuscode": aa.StatusCode, - "timestamp": aa.Timestamp, - "user": aa.User, - } - res = append(res, temp) - } - return res - -} - -func dataSourceAccountAuditsListRead(ctx context.Context, d *schema.ResourceData, m interface{}) diag.Diagnostics { - accountAuditsList, err := utilityAccountAuditsListCheckPresence(ctx, d, m) - if err != nil { - return diag.FromErr(err) - } - - id := uuid.New() - d.SetId(id.String()) - d.Set("items", flattenAccountAuditsList(accountAuditsList)) - - return nil -} - -func dataSourceAccountAuditsListSchemaMake() map[string]*schema.Schema { - res := map[string]*schema.Schema{ - "account_id": { - Type: schema.TypeInt, - Required: true, - Description: "ID of the account", - }, - "items": { - Type: schema.TypeList, - Computed: true, - Description: "Search Result", - Elem: &schema.Resource{ - Schema: map[string]*schema.Schema{ - "call": { - Type: schema.TypeString, - Computed: true, - }, - "responsetime": { - Type: schema.TypeFloat, - Computed: true, - }, - "statuscode": { - Type: schema.TypeInt, - Computed: true, - }, - "timestamp": { - Type: schema.TypeFloat, - Computed: true, - }, - "user": { - Type: schema.TypeString, - Computed: true, - }, - }, - }, - }, - } - return res -} - -func DataSourceAccountAuditsList() *schema.Resource { - return &schema.Resource{ - SchemaVersion: 1, - - ReadContext: dataSourceAccountAuditsListRead, - - Timeouts: &schema.ResourceTimeout{ - Read: &constants.Timeout30s, - Default: &constants.Timeout60s, - }, - - Schema: dataSourceAccountAuditsListSchemaMake(), - } -} +/* +Copyright (c) 2019-2022 Digital Energy Cloud Solutions LLC. All Rights Reserved. +Authors: +Petr Krutov, +Stanislav Solovev, +Kasim Baybikov, + +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 + +import ( + "context" + + "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 account.ListAudits) []map[string]interface{} { + res := make([]map[string]interface{}, 0) + for _, aa := range aal { + temp := map[string]interface{}{ + "call": aa.Call, + "responsetime": aa.ResponseTime, + "statuscode": aa.StatusCode, + "timestamp": aa.Timestamp, + "user": aa.User, + } + res = append(res, temp) + } + return res + +} + +func dataSourceAccountAuditsListRead(ctx context.Context, d *schema.ResourceData, m interface{}) diag.Diagnostics { + accountAuditsList, err := utilityAccountAuditsListCheckPresence(ctx, d, m) + if err != nil { + d.SetId("") + return diag.FromErr(err) + } + + id := uuid.New() + d.SetId(id.String()) + d.Set("items", flattenAccountAuditsList(accountAuditsList)) + + return nil +} + +func dataSourceAccountAuditsListSchemaMake() map[string]*schema.Schema { + res := map[string]*schema.Schema{ + "account_id": { + Type: schema.TypeInt, + Required: true, + Description: "ID of the account", + }, + "items": { + Type: schema.TypeList, + Computed: true, + Description: "Search Result", + Elem: &schema.Resource{ + Schema: map[string]*schema.Schema{ + "call": { + Type: schema.TypeString, + Computed: true, + }, + "responsetime": { + Type: schema.TypeFloat, + Computed: true, + }, + "statuscode": { + Type: schema.TypeInt, + Computed: true, + }, + "timestamp": { + Type: schema.TypeFloat, + Computed: true, + }, + "user": { + Type: schema.TypeString, + Computed: true, + }, + }, + }, + }, + } + return res +} + +func DataSourceAccountAuditsList() *schema.Resource { + return &schema.Resource{ + SchemaVersion: 1, + + ReadContext: dataSourceAccountAuditsListRead, + + Timeouts: &schema.ResourceTimeout{ + Read: &constants.Timeout30s, + Default: &constants.Timeout60s, + }, + + Schema: dataSourceAccountAuditsListSchemaMake(), + } +} diff --git a/internal/service/cloudapi/account/data_source_account_computes_list.go b/internal/service/cloudapi/account/data_source_account_computes_list.go index 16c8639..062cf60 100644 --- a/internal/service/cloudapi/account/data_source_account_computes_list.go +++ b/internal/service/cloudapi/account/data_source_account_computes_list.go @@ -1,257 +1,258 @@ -/* -Copyright (c) 2019-2022 Digital Energy Cloud Solutions LLC. All Rights Reserved. -Authors: -Petr Krutov, -Stanislav Solovev, -Kasim Baybikov, - -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 - -import ( - "context" - - "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 *account.ListComputes) []map[string]interface{} { - res := make([]map[string]interface{}, 0) - for _, acc := range acl.Data { - temp := map[string]interface{}{ - "account_id": acc.AccountID, - "account_name": acc.AccountName, - "cpus": acc.CPUs, - "created_by": acc.CreatedBy, - "created_time": acc.CreatedTime, - "deleted_by": acc.DeletedBy, - "deleted_time": acc.DeletedTime, - "compute_id": acc.ComputeID, - "compute_name": acc.ComputeName, - "ram": acc.RAM, - "registered": acc.Registered, - "rg_id": acc.RGID, - "rg_name": acc.RGName, - "status": acc.Status, - "tech_status": acc.TechStatus, - "total_disks_size": acc.TotalDisksSize, - "updated_by": acc.UpdatedBy, - "updated_time": acc.UpdatedTime, - "user_managed": acc.UserManaged, - "vins_connected": acc.VINSConnected, - } - res = append(res, temp) - } - return res - -} - -func dataSourceAccountComputesListRead(ctx context.Context, d *schema.ResourceData, m interface{}) diag.Diagnostics { - accountComputesList, err := utilityAccountComputesListCheckPresence(ctx, d, m) - if err != nil { - return diag.FromErr(err) - } - - id := uuid.New() - d.SetId(id.String()) - d.Set("items", flattenAccountComputesList(accountComputesList)) - d.Set("entry_count", accountComputesList.EntryCount) - - return nil -} - -func dataSourceAccountComputesListSchemaMake() map[string]*schema.Schema { - res := map[string]*schema.Schema{ - "account_id": { - Type: schema.TypeInt, - Required: true, - Description: "ID of the account", - }, - "compute_id": { - Type: schema.TypeInt, - Optional: true, - Description: "Filter by compute ID", - }, - "name": { - Type: schema.TypeString, - Optional: true, - Description: "Filter by compute name", - }, - "rg_name": { - Type: schema.TypeString, - Optional: true, - Description: "Filter by RG name", - }, - "rg_id": { - Type: schema.TypeInt, - Optional: true, - Description: "Filter by RG ID", - }, - "tech_status": { - Type: schema.TypeString, - Optional: true, - Description: "Filter by tech. status", - }, - "ip_address": { - Type: schema.TypeString, - Optional: true, - Description: "Filter by IP address", - }, - "extnet_name": { - Type: schema.TypeString, - Optional: true, - Description: "Filter by extnet name", - }, - "extnet_id": { - Type: schema.TypeInt, - Optional: true, - Description: "Filter by extnet ID", - }, - "page": { - Type: schema.TypeInt, - Optional: true, - Description: "Page number", - }, - "size": { - Type: schema.TypeInt, - Optional: true, - Description: "Page size", - }, - "items": { - Type: schema.TypeList, - Computed: true, - Description: "Search Result", - Elem: &schema.Resource{ - Schema: map[string]*schema.Schema{ - "account_id": { - Type: schema.TypeInt, - Computed: true, - }, - "account_name": { - Type: schema.TypeString, - Computed: true, - }, - "cpus": { - Type: schema.TypeInt, - Computed: true, - }, - "created_by": { - Type: schema.TypeString, - Computed: true, - }, - "created_time": { - Type: schema.TypeInt, - Computed: true, - }, - "deleted_by": { - Type: schema.TypeString, - Computed: true, - }, - "deleted_time": { - Type: schema.TypeInt, - Computed: true, - }, - "compute_id": { - Type: schema.TypeInt, - Computed: true, - }, - "compute_name": { - Type: schema.TypeString, - Computed: true, - }, - "ram": { - Type: schema.TypeInt, - Computed: true, - }, - "registered": { - Type: schema.TypeBool, - Computed: true, - }, - "rg_id": { - Type: schema.TypeInt, - Computed: true, - }, - "rg_name": { - Type: schema.TypeString, - Computed: true, - }, - "status": { - Type: schema.TypeString, - Computed: true, - }, - "tech_status": { - Type: schema.TypeString, - Computed: true, - }, - "total_disks_size": { - Type: schema.TypeInt, - Computed: true, - }, - "updated_by": { - Type: schema.TypeString, - Computed: true, - }, - "updated_time": { - Type: schema.TypeInt, - Computed: true, - }, - "user_managed": { - Type: schema.TypeBool, - Computed: true, - }, - "vins_connected": { - Type: schema.TypeInt, - Computed: true, - }, - }, - }, - }, - "entry_count": { - Type: schema.TypeInt, - Computed: true, - }, - } - return res -} - -func DataSourceAccountComputesList() *schema.Resource { - return &schema.Resource{ - SchemaVersion: 1, - - ReadContext: dataSourceAccountComputesListRead, - - Timeouts: &schema.ResourceTimeout{ - Read: &constants.Timeout30s, - Default: &constants.Timeout60s, - }, - - Schema: dataSourceAccountComputesListSchemaMake(), - } -} +/* +Copyright (c) 2019-2022 Digital Energy Cloud Solutions LLC. All Rights Reserved. +Authors: +Petr Krutov, +Stanislav Solovev, +Kasim Baybikov, + +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 + +import ( + "context" + + "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 *account.ListComputes) []map[string]interface{} { + res := make([]map[string]interface{}, 0) + for _, acc := range acl.Data { + temp := map[string]interface{}{ + "account_id": acc.AccountID, + "account_name": acc.AccountName, + "cpus": acc.CPUs, + "created_by": acc.CreatedBy, + "created_time": acc.CreatedTime, + "deleted_by": acc.DeletedBy, + "deleted_time": acc.DeletedTime, + "compute_id": acc.ComputeID, + "compute_name": acc.ComputeName, + "ram": acc.RAM, + "registered": acc.Registered, + "rg_id": acc.RGID, + "rg_name": acc.RGName, + "status": acc.Status, + "tech_status": acc.TechStatus, + "total_disks_size": acc.TotalDisksSize, + "updated_by": acc.UpdatedBy, + "updated_time": acc.UpdatedTime, + "user_managed": acc.UserManaged, + "vins_connected": acc.VINSConnected, + } + res = append(res, temp) + } + return res + +} + +func dataSourceAccountComputesListRead(ctx context.Context, d *schema.ResourceData, m interface{}) diag.Diagnostics { + accountComputesList, err := utilityAccountComputesListCheckPresence(ctx, d, m) + if err != nil { + d.SetId("") + return diag.FromErr(err) + } + + id := uuid.New() + d.SetId(id.String()) + d.Set("items", flattenAccountComputesList(accountComputesList)) + d.Set("entry_count", accountComputesList.EntryCount) + + return nil +} + +func dataSourceAccountComputesListSchemaMake() map[string]*schema.Schema { + res := map[string]*schema.Schema{ + "account_id": { + Type: schema.TypeInt, + Required: true, + Description: "ID of the account", + }, + "compute_id": { + Type: schema.TypeInt, + Optional: true, + Description: "Filter by compute ID", + }, + "name": { + Type: schema.TypeString, + Optional: true, + Description: "Filter by compute name", + }, + "rg_name": { + Type: schema.TypeString, + Optional: true, + Description: "Filter by RG name", + }, + "rg_id": { + Type: schema.TypeInt, + Optional: true, + Description: "Filter by RG ID", + }, + "tech_status": { + Type: schema.TypeString, + Optional: true, + Description: "Filter by tech. status", + }, + "ip_address": { + Type: schema.TypeString, + Optional: true, + Description: "Filter by IP address", + }, + "extnet_name": { + Type: schema.TypeString, + Optional: true, + Description: "Filter by extnet name", + }, + "extnet_id": { + Type: schema.TypeInt, + Optional: true, + Description: "Filter by extnet ID", + }, + "page": { + Type: schema.TypeInt, + Optional: true, + Description: "Page number", + }, + "size": { + Type: schema.TypeInt, + Optional: true, + Description: "Page size", + }, + "items": { + Type: schema.TypeList, + Computed: true, + Description: "Search Result", + Elem: &schema.Resource{ + Schema: map[string]*schema.Schema{ + "account_id": { + Type: schema.TypeInt, + Computed: true, + }, + "account_name": { + Type: schema.TypeString, + Computed: true, + }, + "cpus": { + Type: schema.TypeInt, + Computed: true, + }, + "created_by": { + Type: schema.TypeString, + Computed: true, + }, + "created_time": { + Type: schema.TypeInt, + Computed: true, + }, + "deleted_by": { + Type: schema.TypeString, + Computed: true, + }, + "deleted_time": { + Type: schema.TypeInt, + Computed: true, + }, + "compute_id": { + Type: schema.TypeInt, + Computed: true, + }, + "compute_name": { + Type: schema.TypeString, + Computed: true, + }, + "ram": { + Type: schema.TypeInt, + Computed: true, + }, + "registered": { + Type: schema.TypeBool, + Computed: true, + }, + "rg_id": { + Type: schema.TypeInt, + Computed: true, + }, + "rg_name": { + Type: schema.TypeString, + Computed: true, + }, + "status": { + Type: schema.TypeString, + Computed: true, + }, + "tech_status": { + Type: schema.TypeString, + Computed: true, + }, + "total_disks_size": { + Type: schema.TypeInt, + Computed: true, + }, + "updated_by": { + Type: schema.TypeString, + Computed: true, + }, + "updated_time": { + Type: schema.TypeInt, + Computed: true, + }, + "user_managed": { + Type: schema.TypeBool, + Computed: true, + }, + "vins_connected": { + Type: schema.TypeInt, + Computed: true, + }, + }, + }, + }, + "entry_count": { + Type: schema.TypeInt, + Computed: true, + }, + } + return res +} + +func DataSourceAccountComputesList() *schema.Resource { + return &schema.Resource{ + SchemaVersion: 1, + + ReadContext: dataSourceAccountComputesListRead, + + Timeouts: &schema.ResourceTimeout{ + Read: &constants.Timeout30s, + Default: &constants.Timeout60s, + }, + + Schema: dataSourceAccountComputesListSchemaMake(), + } +} diff --git a/internal/service/cloudapi/account/data_source_account_consumed_units.go b/internal/service/cloudapi/account/data_source_account_consumed_units.go index acfa112..e8375b1 100644 --- a/internal/service/cloudapi/account/data_source_account_consumed_units.go +++ b/internal/service/cloudapi/account/data_source_account_consumed_units.go @@ -1,110 +1,116 @@ -/* -Copyright (c) 2019-2022 Digital Energy Cloud Solutions LLC. All Rights Reserved. -Authors: -Petr Krutov, -Stanislav Solovev, -Kasim Baybikov, - -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 - -import ( - "context" - - "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" -) - -func dataSourceAccountConsumedUnitsRead(ctx context.Context, d *schema.ResourceData, m interface{}) diag.Diagnostics { - accountConsumedUnits, err := utilityAccountConsumedUnitsCheckPresence(ctx, d, m) - if err != nil { - return diag.FromErr(err) - } - - id := uuid.New() - d.SetId(id.String()) - d.Set("cu_c", accountConsumedUnits.CUC) - d.Set("cu_d", accountConsumedUnits.CUD) - d.Set("cu_i", accountConsumedUnits.CUI) - d.Set("cu_m", accountConsumedUnits.CUM) - d.Set("cu_np", accountConsumedUnits.CUNP) - d.Set("gpu_units", accountConsumedUnits.GPUUnits) - - return nil -} - -func dataSourceAccountConsumedUnitsSchemaMake() map[string]*schema.Schema { - res := map[string]*schema.Schema{ - "account_id": { - Type: schema.TypeInt, - Required: true, - Description: "ID of the account", - }, - "cu_c": { - Type: schema.TypeFloat, - Computed: true, - }, - "cu_d": { - Type: schema.TypeFloat, - Computed: true, - }, - "cu_i": { - Type: schema.TypeFloat, - Computed: true, - }, - "cu_m": { - Type: schema.TypeFloat, - Computed: true, - }, - "cu_np": { - Type: schema.TypeFloat, - Computed: true, - }, - "gpu_units": { - Type: schema.TypeFloat, - Computed: true, - }, - } - return res -} - -func DataSourceAccountConsumedUnits() *schema.Resource { - return &schema.Resource{ - SchemaVersion: 1, - - ReadContext: dataSourceAccountConsumedUnitsRead, - - Timeouts: &schema.ResourceTimeout{ - Read: &constants.Timeout30s, - Default: &constants.Timeout60s, - }, - - Schema: dataSourceAccountConsumedUnitsSchemaMake(), - } -} +/* +Copyright (c) 2019-2022 Digital Energy Cloud Solutions LLC. All Rights Reserved. +Authors: +Petr Krutov, +Stanislav Solovev, +Kasim Baybikov, + +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 + +import ( + "context" + + "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" +) + +func dataSourceAccountConsumedUnitsRead(ctx context.Context, d *schema.ResourceData, m interface{}) diag.Diagnostics { + accountConsumedUnits, err := utilityAccountConsumedUnitsCheckPresence(ctx, d, m) + if err != nil { + d.SetId("") + return diag.FromErr(err) + } + + id := uuid.New() + d.SetId(id.String()) + d.Set("cu_c", accountConsumedUnits.CUC) + d.Set("cu_d", accountConsumedUnits.CUD) + d.Set("cu_dm", accountConsumedUnits.CUDM) + d.Set("cu_i", accountConsumedUnits.CUI) + d.Set("cu_m", accountConsumedUnits.CUM) + d.Set("cu_np", accountConsumedUnits.CUNP) + d.Set("gpu_units", accountConsumedUnits.GPUUnits) + + return nil +} + +func dataSourceAccountConsumedUnitsSchemaMake() map[string]*schema.Schema { + res := map[string]*schema.Schema{ + "account_id": { + Type: schema.TypeInt, + Required: true, + Description: "ID of the account", + }, + "cu_c": { + Type: schema.TypeFloat, + Computed: true, + }, + "cu_d": { + Type: schema.TypeFloat, + Computed: true, + }, + "cu_dm": { + Type: schema.TypeFloat, + Computed: true, + }, + "cu_i": { + Type: schema.TypeFloat, + Computed: true, + }, + "cu_m": { + Type: schema.TypeFloat, + Computed: true, + }, + "cu_np": { + Type: schema.TypeFloat, + Computed: true, + }, + "gpu_units": { + Type: schema.TypeFloat, + Computed: true, + }, + } + return res +} + +func DataSourceAccountConsumedUnits() *schema.Resource { + return &schema.Resource{ + SchemaVersion: 1, + + ReadContext: dataSourceAccountConsumedUnitsRead, + + Timeouts: &schema.ResourceTimeout{ + Read: &constants.Timeout30s, + Default: &constants.Timeout60s, + }, + + Schema: dataSourceAccountConsumedUnitsSchemaMake(), + } +} diff --git a/internal/service/cloudapi/account/data_source_account_consumed_units_by_type.go b/internal/service/cloudapi/account/data_source_account_consumed_units_by_type.go index 906eb83..7c246ca 100644 --- a/internal/service/cloudapi/account/data_source_account_consumed_units_by_type.go +++ b/internal/service/cloudapi/account/data_source_account_consumed_units_by_type.go @@ -1,90 +1,91 @@ -/* -Copyright (c) 2019-2022 Digital Energy Cloud Solutions LLC. All Rights Reserved. -Authors: -Petr Krutov, -Stanislav Solovev, -Kasim Baybikov, - -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 - -import ( - "context" - - "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" -) - -func dataSourceAccountConsumedUnitsByTypeRead(ctx context.Context, d *schema.ResourceData, m interface{}) diag.Diagnostics { - result, err := utilityAccountConsumedUnitsByTypeCheckPresence(ctx, d, m) - if err != nil { - return diag.FromErr(err) - } - - id := uuid.New() - d.SetId(id.String()) - d.Set("cu_result", result) - - return nil -} - -func dataSourceAccountConsumedUnitsByTypeSchemaMake() map[string]*schema.Schema { - res := map[string]*schema.Schema{ - "account_id": { - Type: schema.TypeInt, - Required: true, - Description: "ID of the account", - }, - "cu_type": { - Type: schema.TypeString, - Required: true, - Description: "cloud unit resource type", - }, - "cu_result": { - Type: schema.TypeFloat, - Computed: true, - }, - } - return res -} - -func DataSourceAccountConsumedUnitsByType() *schema.Resource { - return &schema.Resource{ - SchemaVersion: 1, - - ReadContext: dataSourceAccountConsumedUnitsByTypeRead, - - Timeouts: &schema.ResourceTimeout{ - Read: &constants.Timeout30s, - Default: &constants.Timeout60s, - }, - - Schema: dataSourceAccountConsumedUnitsByTypeSchemaMake(), - } -} +/* +Copyright (c) 2019-2022 Digital Energy Cloud Solutions LLC. All Rights Reserved. +Authors: +Petr Krutov, +Stanislav Solovev, +Kasim Baybikov, + +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 + +import ( + "context" + + "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" +) + +func dataSourceAccountConsumedUnitsByTypeRead(ctx context.Context, d *schema.ResourceData, m interface{}) diag.Diagnostics { + result, err := utilityAccountConsumedUnitsByTypeCheckPresence(ctx, d, m) + if err != nil { + d.SetId("") + return diag.FromErr(err) + } + + id := uuid.New() + d.SetId(id.String()) + d.Set("cu_result", result) + + return nil +} + +func dataSourceAccountConsumedUnitsByTypeSchemaMake() map[string]*schema.Schema { + res := map[string]*schema.Schema{ + "account_id": { + Type: schema.TypeInt, + Required: true, + Description: "ID of the account", + }, + "cu_type": { + Type: schema.TypeString, + Required: true, + Description: "cloud unit resource type", + }, + "cu_result": { + Type: schema.TypeFloat, + Computed: true, + }, + } + return res +} + +func DataSourceAccountConsumedUnitsByType() *schema.Resource { + return &schema.Resource{ + SchemaVersion: 1, + + ReadContext: dataSourceAccountConsumedUnitsByTypeRead, + + Timeouts: &schema.ResourceTimeout{ + Read: &constants.Timeout30s, + Default: &constants.Timeout60s, + }, + + Schema: dataSourceAccountConsumedUnitsByTypeSchemaMake(), + } +} diff --git a/internal/service/cloudapi/account/data_source_account_deleted_list.go b/internal/service/cloudapi/account/data_source_account_deleted_list.go index 6549888..96ed76b 100644 --- a/internal/service/cloudapi/account/data_source_account_deleted_list.go +++ b/internal/service/cloudapi/account/data_source_account_deleted_list.go @@ -1,77 +1,78 @@ -/* -Copyright (c) 2019-2022 Digital Energy Cloud Solutions LLC. All Rights Reserved. -Authors: -Petr Krutov, -Stanislav Solovev, -Kasim Baybikov, - -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 - -import ( - "context" - - "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" -) - -func dataSourceAccountDeletedListRead(ctx context.Context, d *schema.ResourceData, m interface{}) diag.Diagnostics { - accountDeletedList, err := utilityAccountDeletedListCheckPresence(ctx, d, m) - if err != nil { - return diag.FromErr(err) - } - - id := uuid.New() - d.SetId(id.String()) - d.Set("items", flattenAccountList(accountDeletedList)) - d.Set("entry_count", accountDeletedList.EntryCount) - - return nil -} - -func dataSourceAccountDeletedListSchemaMake() map[string]*schema.Schema { - temp := dataSourceAccountListSchemaMake() - delete(temp, "status") - return temp -} - -func DataSourceAccountDeletedList() *schema.Resource { - return &schema.Resource{ - SchemaVersion: 1, - - ReadContext: dataSourceAccountDeletedListRead, - - Timeouts: &schema.ResourceTimeout{ - Read: &constants.Timeout30s, - Default: &constants.Timeout60s, - }, - - Schema: dataSourceAccountDeletedListSchemaMake(), - } -} +/* +Copyright (c) 2019-2022 Digital Energy Cloud Solutions LLC. All Rights Reserved. +Authors: +Petr Krutov, +Stanislav Solovev, +Kasim Baybikov, + +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 + +import ( + "context" + + "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" +) + +func dataSourceAccountDeletedListRead(ctx context.Context, d *schema.ResourceData, m interface{}) diag.Diagnostics { + accountDeletedList, err := utilityAccountDeletedListCheckPresence(ctx, d, m) + if err != nil { + d.SetId("") + return diag.FromErr(err) + } + + id := uuid.New() + d.SetId(id.String()) + d.Set("items", flattenAccountList(accountDeletedList)) + d.Set("entry_count", accountDeletedList.EntryCount) + + return nil +} + +func dataSourceAccountDeletedListSchemaMake() map[string]*schema.Schema { + temp := dataSourceAccountListSchemaMake() + delete(temp, "status") + return temp +} + +func DataSourceAccountDeletedList() *schema.Resource { + return &schema.Resource{ + SchemaVersion: 1, + + ReadContext: dataSourceAccountDeletedListRead, + + Timeouts: &schema.ResourceTimeout{ + Read: &constants.Timeout30s, + Default: &constants.Timeout60s, + }, + + Schema: dataSourceAccountDeletedListSchemaMake(), + } +} diff --git a/internal/service/cloudapi/account/data_source_account_disks_list.go b/internal/service/cloudapi/account/data_source_account_disks_list.go index df74f26..294ade3 100644 --- a/internal/service/cloudapi/account/data_source_account_disks_list.go +++ b/internal/service/cloudapi/account/data_source_account_disks_list.go @@ -1,171 +1,172 @@ -/* -Copyright (c) 2019-2022 Digital Energy Cloud Solutions LLC. All Rights Reserved. -Authors: -Petr Krutov, -Stanislav Solovev, -Kasim Baybikov, - -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 - -import ( - "context" - - "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 *account.ListDisks) []map[string]interface{} { - res := make([]map[string]interface{}, 0) - for _, ad := range adl.Data { - temp := map[string]interface{}{ - "disk_id": ad.ID, - "disk_name": ad.Name, - "pool": ad.Pool, - "sep_id": ad.SEPID, - "shareable": ad.Shareable, - "size_max": ad.SizeMax, - "type": ad.Type, - } - res = append(res, temp) - } - return res - -} - -func dataSourceAccountDisksListRead(ctx context.Context, d *schema.ResourceData, m interface{}) diag.Diagnostics { - accountDisksList, err := utilityAccountDisksListCheckPresence(ctx, d, m) - if err != nil { - return diag.FromErr(err) - } - - id := uuid.New() - d.SetId(id.String()) - d.Set("items", flattenAccountDisksList(accountDisksList)) - d.Set("entry_count", accountDisksList.EntryCount) - - return nil -} - -func dataSourceAccountDisksListSchemaMake() map[string]*schema.Schema { - res := map[string]*schema.Schema{ - "account_id": { - Type: schema.TypeInt, - Required: true, - Description: "ID of the account", - }, - "disk_id": { - Type: schema.TypeInt, - Optional: true, - Description: "Filter by disk ID", - }, - "name": { - Type: schema.TypeString, - Optional: true, - Description: "Filter by disk name", - }, - "disk_max_size": { - Type: schema.TypeInt, - Optional: true, - Description: "Filter by disk max size", - }, - "type": { - Type: schema.TypeString, - Optional: true, - Description: "Filter by disk type", - }, - "page": { - Type: schema.TypeInt, - Optional: true, - Description: "Page number", - }, - "size": { - Type: schema.TypeInt, - Optional: true, - Description: "Page size", - }, - "items": { - Type: schema.TypeList, - Computed: true, - Description: "Search Result", - Elem: &schema.Resource{ - Schema: map[string]*schema.Schema{ - "disk_id": { - Type: schema.TypeInt, - Computed: true, - }, - "disk_name": { - Type: schema.TypeString, - Computed: true, - }, - "pool": { - Type: schema.TypeString, - Computed: true, - }, - "sep_id": { - Type: schema.TypeInt, - Computed: true, - }, - "shareable": { - Type: schema.TypeBool, - Computed: true, - }, - "size_max": { - Type: schema.TypeInt, - Computed: true, - }, - "type": { - Type: schema.TypeString, - Computed: true, - }, - }, - }, - }, - "entry_count": { - Type: schema.TypeInt, - Computed: true, - }, - } - return res -} - -func DataSourceAccountDisksList() *schema.Resource { - return &schema.Resource{ - SchemaVersion: 1, - - ReadContext: dataSourceAccountDisksListRead, - - Timeouts: &schema.ResourceTimeout{ - Read: &constants.Timeout30s, - Default: &constants.Timeout60s, - }, - - Schema: dataSourceAccountDisksListSchemaMake(), - } -} +/* +Copyright (c) 2019-2022 Digital Energy Cloud Solutions LLC. All Rights Reserved. +Authors: +Petr Krutov, +Stanislav Solovev, +Kasim Baybikov, + +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 + +import ( + "context" + + "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 *account.ListDisks) []map[string]interface{} { + res := make([]map[string]interface{}, 0) + for _, ad := range adl.Data { + temp := map[string]interface{}{ + "disk_id": ad.ID, + "disk_name": ad.Name, + "pool": ad.Pool, + "sep_id": ad.SEPID, + "shareable": ad.Shareable, + "size_max": ad.SizeMax, + "type": ad.Type, + } + res = append(res, temp) + } + return res + +} + +func dataSourceAccountDisksListRead(ctx context.Context, d *schema.ResourceData, m interface{}) diag.Diagnostics { + accountDisksList, err := utilityAccountDisksListCheckPresence(ctx, d, m) + if err != nil { + d.SetId("") + return diag.FromErr(err) + } + + id := uuid.New() + d.SetId(id.String()) + d.Set("items", flattenAccountDisksList(accountDisksList)) + d.Set("entry_count", accountDisksList.EntryCount) + + return nil +} + +func dataSourceAccountDisksListSchemaMake() map[string]*schema.Schema { + res := map[string]*schema.Schema{ + "account_id": { + Type: schema.TypeInt, + Required: true, + Description: "ID of the account", + }, + "disk_id": { + Type: schema.TypeInt, + Optional: true, + Description: "Filter by disk ID", + }, + "name": { + Type: schema.TypeString, + Optional: true, + Description: "Filter by disk name", + }, + "disk_max_size": { + Type: schema.TypeInt, + Optional: true, + Description: "Filter by disk max size", + }, + "type": { + Type: schema.TypeString, + Optional: true, + Description: "Filter by disk type", + }, + "page": { + Type: schema.TypeInt, + Optional: true, + Description: "Page number", + }, + "size": { + Type: schema.TypeInt, + Optional: true, + Description: "Page size", + }, + "items": { + Type: schema.TypeList, + Computed: true, + Description: "Search Result", + Elem: &schema.Resource{ + Schema: map[string]*schema.Schema{ + "disk_id": { + Type: schema.TypeInt, + Computed: true, + }, + "disk_name": { + Type: schema.TypeString, + Computed: true, + }, + "pool": { + Type: schema.TypeString, + Computed: true, + }, + "sep_id": { + Type: schema.TypeInt, + Computed: true, + }, + "shareable": { + Type: schema.TypeBool, + Computed: true, + }, + "size_max": { + Type: schema.TypeInt, + Computed: true, + }, + "type": { + Type: schema.TypeString, + Computed: true, + }, + }, + }, + }, + "entry_count": { + Type: schema.TypeInt, + Computed: true, + }, + } + return res +} + +func DataSourceAccountDisksList() *schema.Resource { + return &schema.Resource{ + SchemaVersion: 1, + + ReadContext: dataSourceAccountDisksListRead, + + Timeouts: &schema.ResourceTimeout{ + Read: &constants.Timeout30s, + Default: &constants.Timeout60s, + }, + + Schema: dataSourceAccountDisksListSchemaMake(), + } +} diff --git a/internal/service/cloudapi/account/data_source_account_flipgroups_list.go b/internal/service/cloudapi/account/data_source_account_flipgroups_list.go index 59a2476..282ae4c 100644 --- a/internal/service/cloudapi/account/data_source_account_flipgroups_list.go +++ b/internal/service/cloudapi/account/data_source_account_flipgroups_list.go @@ -1,252 +1,253 @@ -/* -Copyright (c) 2019-2022 Digital Energy Cloud Solutions LLC. All Rights Reserved. -Authors: -Petr Krutov, -Stanislav Solovev, -Kasim Baybikov, - -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 - -import ( - "context" - - "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 *account.ListFLIPGroups) []map[string]interface{} { - res := make([]map[string]interface{}, 0) - for _, afg := range afgl.Data { - temp := map[string]interface{}{ - "account_id": afg.AccountID, - "client_type": afg.ClientType, - "conn_type": afg.ConnType, - "created_by": afg.CreatedBy, - "created_time": afg.CreatedTime, - "default_gw": afg.DefaultGW, - "deleted_by": afg.DeletedBy, - "deleted_time": afg.DeletedTime, - "desc": afg.Description, - "gid": afg.GID, - "guid": afg.GUID, - "fg_id": afg.ID, - "ip": afg.IP, - "milestones": afg.Milestones, - "fg_name": afg.Name, - "net_id": afg.NetID, - "net_type": afg.NetType, - "netmask": afg.NetMask, - "status": afg.Status, - "updated_by": afg.UpdatedBy, - "updated_time": afg.UpdatedTime, - } - res = append(res, temp) - } - return res - -} - -func dataSourceAccountFlipGroupsListRead(ctx context.Context, d *schema.ResourceData, m interface{}) diag.Diagnostics { - accountFlipGroupsList, err := utilityAccountFlipGroupsListCheckPresence(ctx, d, m) - if err != nil { - return diag.FromErr(err) - } - - id := uuid.New() - d.SetId(id.String()) - d.Set("items", flattenAccountFlipGroupsList(accountFlipGroupsList)) - d.Set("entry_count", accountFlipGroupsList.EntryCount) - - return nil -} - -func dataSourceAccountFlipGroupsListSchemaMake() map[string]*schema.Schema { - res := map[string]*schema.Schema{ - "account_id": { - Type: schema.TypeInt, - Required: true, - Description: "ID of the account", - }, - "name": { - Type: schema.TypeString, - Optional: true, - Description: "Filter by name", - }, - "vins_id": { - Type: schema.TypeInt, - Optional: true, - Description: "Filter by ViNS ID", - }, - "vins_name": { - Type: schema.TypeString, - Optional: true, - Description: "Filter by ViNS name", - }, - "extnet_id": { - Type: schema.TypeInt, - Optional: true, - Description: "Filter by extnet ID", - }, - "by_ip": { - Type: schema.TypeString, - Optional: true, - Description: "Filter by IP", - }, - "flipgroup_id": { - Type: schema.TypeInt, - Optional: true, - Description: "Filter by flipgroup ID", - }, - "page": { - Type: schema.TypeInt, - Optional: true, - Description: "Page number", - }, - "size": { - Type: schema.TypeInt, - Optional: true, - Description: "Page size", - }, - "items": { - Type: schema.TypeList, - Computed: true, - Description: "Search Result", - Elem: &schema.Resource{ - Schema: map[string]*schema.Schema{ - "account_id": { - Type: schema.TypeInt, - Computed: true, - }, - "client_type": { - Type: schema.TypeString, - Computed: true, - }, - "conn_type": { - Type: schema.TypeString, - Computed: true, - }, - "created_by": { - Type: schema.TypeString, - Computed: true, - }, - "created_time": { - Type: schema.TypeInt, - Computed: true, - }, - "default_gw": { - Type: schema.TypeString, - Computed: true, - }, - "deleted_by": { - Type: schema.TypeString, - Computed: true, - }, - "deleted_time": { - Type: schema.TypeInt, - Computed: true, - }, - "desc": { - Type: schema.TypeString, - Computed: true, - }, - "gid": { - Type: schema.TypeInt, - Computed: true, - }, - "guid": { - Type: schema.TypeInt, - Computed: true, - }, - "fg_id": { - Type: schema.TypeInt, - Computed: true, - }, - "ip": { - Type: schema.TypeString, - Computed: true, - }, - "milestones": { - Type: schema.TypeInt, - Computed: true, - }, - "fg_name": { - Type: schema.TypeString, - Computed: true, - }, - "net_id": { - Type: schema.TypeInt, - Computed: true, - }, - "net_type": { - Type: schema.TypeString, - Computed: true, - }, - "netmask": { - Type: schema.TypeInt, - Computed: true, - }, - "status": { - Type: schema.TypeString, - Computed: true, - }, - "updated_by": { - Type: schema.TypeString, - Computed: true, - }, - "updated_time": { - Type: schema.TypeInt, - Computed: true, - }, - }, - }, - }, - "entry_count": { - Type: schema.TypeInt, - Computed: true, - }, - } - return res -} - -func DataSourceAccountFlipGroupsList() *schema.Resource { - return &schema.Resource{ - SchemaVersion: 1, - - ReadContext: dataSourceAccountFlipGroupsListRead, - - Timeouts: &schema.ResourceTimeout{ - Read: &constants.Timeout30s, - Default: &constants.Timeout60s, - }, - - Schema: dataSourceAccountFlipGroupsListSchemaMake(), - } -} +/* +Copyright (c) 2019-2022 Digital Energy Cloud Solutions LLC. All Rights Reserved. +Authors: +Petr Krutov, +Stanislav Solovev, +Kasim Baybikov, + +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 + +import ( + "context" + + "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 *account.ListFLIPGroups) []map[string]interface{} { + res := make([]map[string]interface{}, 0) + for _, afg := range afgl.Data { + temp := map[string]interface{}{ + "account_id": afg.AccountID, + "client_type": afg.ClientType, + "conn_type": afg.ConnType, + "created_by": afg.CreatedBy, + "created_time": afg.CreatedTime, + "default_gw": afg.DefaultGW, + "deleted_by": afg.DeletedBy, + "deleted_time": afg.DeletedTime, + "desc": afg.Description, + "gid": afg.GID, + "guid": afg.GUID, + "fg_id": afg.ID, + "ip": afg.IP, + "milestones": afg.Milestones, + "fg_name": afg.Name, + "net_id": afg.NetID, + "net_type": afg.NetType, + "netmask": afg.NetMask, + "status": afg.Status, + "updated_by": afg.UpdatedBy, + "updated_time": afg.UpdatedTime, + } + res = append(res, temp) + } + return res + +} + +func dataSourceAccountFlipGroupsListRead(ctx context.Context, d *schema.ResourceData, m interface{}) diag.Diagnostics { + accountFlipGroupsList, err := utilityAccountFlipGroupsListCheckPresence(ctx, d, m) + if err != nil { + d.SetId("") + return diag.FromErr(err) + } + + id := uuid.New() + d.SetId(id.String()) + d.Set("items", flattenAccountFlipGroupsList(accountFlipGroupsList)) + d.Set("entry_count", accountFlipGroupsList.EntryCount) + + return nil +} + +func dataSourceAccountFlipGroupsListSchemaMake() map[string]*schema.Schema { + res := map[string]*schema.Schema{ + "account_id": { + Type: schema.TypeInt, + Required: true, + Description: "ID of the account", + }, + "name": { + Type: schema.TypeString, + Optional: true, + Description: "Filter by name", + }, + "vins_id": { + Type: schema.TypeInt, + Optional: true, + Description: "Filter by ViNS ID", + }, + "vins_name": { + Type: schema.TypeString, + Optional: true, + Description: "Filter by ViNS name", + }, + "extnet_id": { + Type: schema.TypeInt, + Optional: true, + Description: "Filter by extnet ID", + }, + "by_ip": { + Type: schema.TypeString, + Optional: true, + Description: "Filter by IP", + }, + "flipgroup_id": { + Type: schema.TypeInt, + Optional: true, + Description: "Filter by flipgroup ID", + }, + "page": { + Type: schema.TypeInt, + Optional: true, + Description: "Page number", + }, + "size": { + Type: schema.TypeInt, + Optional: true, + Description: "Page size", + }, + "items": { + Type: schema.TypeList, + Computed: true, + Description: "Search Result", + Elem: &schema.Resource{ + Schema: map[string]*schema.Schema{ + "account_id": { + Type: schema.TypeInt, + Computed: true, + }, + "client_type": { + Type: schema.TypeString, + Computed: true, + }, + "conn_type": { + Type: schema.TypeString, + Computed: true, + }, + "created_by": { + Type: schema.TypeString, + Computed: true, + }, + "created_time": { + Type: schema.TypeInt, + Computed: true, + }, + "default_gw": { + Type: schema.TypeString, + Computed: true, + }, + "deleted_by": { + Type: schema.TypeString, + Computed: true, + }, + "deleted_time": { + Type: schema.TypeInt, + Computed: true, + }, + "desc": { + Type: schema.TypeString, + Computed: true, + }, + "gid": { + Type: schema.TypeInt, + Computed: true, + }, + "guid": { + Type: schema.TypeInt, + Computed: true, + }, + "fg_id": { + Type: schema.TypeInt, + Computed: true, + }, + "ip": { + Type: schema.TypeString, + Computed: true, + }, + "milestones": { + Type: schema.TypeInt, + Computed: true, + }, + "fg_name": { + Type: schema.TypeString, + Computed: true, + }, + "net_id": { + Type: schema.TypeInt, + Computed: true, + }, + "net_type": { + Type: schema.TypeString, + Computed: true, + }, + "netmask": { + Type: schema.TypeInt, + Computed: true, + }, + "status": { + Type: schema.TypeString, + Computed: true, + }, + "updated_by": { + Type: schema.TypeString, + Computed: true, + }, + "updated_time": { + Type: schema.TypeInt, + Computed: true, + }, + }, + }, + }, + "entry_count": { + Type: schema.TypeInt, + Computed: true, + }, + } + return res +} + +func DataSourceAccountFlipGroupsList() *schema.Resource { + return &schema.Resource{ + SchemaVersion: 1, + + ReadContext: dataSourceAccountFlipGroupsListRead, + + Timeouts: &schema.ResourceTimeout{ + Read: &constants.Timeout30s, + Default: &constants.Timeout60s, + }, + + Schema: dataSourceAccountFlipGroupsListSchemaMake(), + } +} diff --git a/internal/service/cloudapi/account/data_source_account_get_resource_consumption.go b/internal/service/cloudapi/account/data_source_account_get_resource_consumption.go index 9fc659d..b672116 100644 --- a/internal/service/cloudapi/account/data_source_account_get_resource_consumption.go +++ b/internal/service/cloudapi/account/data_source_account_get_resource_consumption.go @@ -44,6 +44,7 @@ import ( func dataSourceAccountResourceConsumptionGetRead(ctx context.Context, d *schema.ResourceData, m interface{}) diag.Diagnostics { accountResourceConsumptionRec, err := utilityAccountResourceConsumptionGetCheckPresence(ctx, d, m) if err != nil { + d.SetId("") return diag.FromErr(err) } diff --git a/internal/service/cloudapi/account/data_source_account_list.go b/internal/service/cloudapi/account/data_source_account_list.go index eabe070..3728725 100644 --- a/internal/service/cloudapi/account/data_source_account_list.go +++ b/internal/service/cloudapi/account/data_source_account_list.go @@ -1,209 +1,210 @@ -/* -Copyright (c) 2019-2022 Digital Energy Cloud Solutions LLC. All Rights Reserved. -Authors: -Petr Krutov, -Stanislav Solovev, -Kasim Baybikov, - -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 - -import ( - "context" - - "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 *account.ListAccounts) []map[string]interface{} { - res := make([]map[string]interface{}, 0) - for _, acc := range al.Data { - temp := map[string]interface{}{ - "acl": flattenRgAcl(acc.ACL), - "created_time": acc.CreatedTime, - "deleted_time": acc.DeletedTime, - "account_id": acc.ID, - "account_name": acc.Name, - "status": acc.Status, - "updated_time": acc.UpdatedTime, - } - res = append(res, temp) - } - return res -} - -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, - "right": rgAcl.Rights, - "status": rgAcl.Status, - "type": rgAcl.Type, - "user_group_id": rgAcl.UgroupID, - } - res = append(res, temp) - } - return res -} - -func dataSourceAccountListRead(ctx context.Context, d *schema.ResourceData, m interface{}) diag.Diagnostics { - accountList, err := utilityAccountListCheckPresence(ctx, d, m) - if err != nil { - return diag.FromErr(err) - } - - id := uuid.New() - d.SetId(id.String()) - d.Set("items", flattenAccountList(accountList)) - d.Set("entry_count", accountList.EntryCount) - - return nil -} - -func dataSourceAccountListSchemaMake() map[string]*schema.Schema { - res := map[string]*schema.Schema{ - "by_id": { - Type: schema.TypeInt, - Optional: true, - Description: "Filter by ID", - }, - "name": { - Type: schema.TypeString, - Optional: true, - Description: "Filter by name", - }, - "acl": { - Type: schema.TypeString, - Optional: true, - Description: "Filter by ACL", - }, - "status": { - Type: schema.TypeString, - Optional: true, - Description: "Filter by status", - }, - "page": { - Type: schema.TypeInt, - Optional: true, - Description: "Page number", - }, - "size": { - Type: schema.TypeInt, - Optional: true, - Description: "Page size", - }, - "items": { - Type: schema.TypeList, - Computed: true, - Elem: &schema.Resource{ - Schema: map[string]*schema.Schema{ - "acl": { - Type: schema.TypeList, - Computed: true, - Elem: &schema.Resource{ - Schema: map[string]*schema.Schema{ - "explicit": { - Type: schema.TypeBool, - Computed: true, - }, - "guid": { - Type: schema.TypeString, - Computed: true, - }, - "right": { - Type: schema.TypeString, - Computed: true, - }, - "status": { - Type: schema.TypeString, - Computed: true, - }, - "type": { - Type: schema.TypeString, - Computed: true, - }, - "user_group_id": { - Type: schema.TypeString, - Computed: true, - }, - }, - }, - }, - "created_time": { - Type: schema.TypeInt, - Computed: true, - }, - "deleted_time": { - Type: schema.TypeInt, - Computed: true, - }, - "account_id": { - Type: schema.TypeInt, - Computed: true, - }, - "account_name": { - Type: schema.TypeString, - Computed: true, - }, - "status": { - Type: schema.TypeString, - Computed: true, - }, - "updated_time": { - Type: schema.TypeInt, - Computed: true, - }, - }, - }, - }, - "entry_count": { - Type: schema.TypeInt, - Computed: true, - }, - } - return res -} - -func DataSourceAccountList() *schema.Resource { - return &schema.Resource{ - SchemaVersion: 1, - - ReadContext: dataSourceAccountListRead, - - Timeouts: &schema.ResourceTimeout{ - Read: &constants.Timeout30s, - Default: &constants.Timeout60s, - }, - - Schema: dataSourceAccountListSchemaMake(), - } -} +/* +Copyright (c) 2019-2022 Digital Energy Cloud Solutions LLC. All Rights Reserved. +Authors: +Petr Krutov, +Stanislav Solovev, +Kasim Baybikov, + +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 + +import ( + "context" + + "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 *account.ListAccounts) []map[string]interface{} { + res := make([]map[string]interface{}, 0) + for _, acc := range al.Data { + temp := map[string]interface{}{ + "acl": flattenRgAcl(acc.ACL), + "created_time": acc.CreatedTime, + "deleted_time": acc.DeletedTime, + "account_id": acc.ID, + "account_name": acc.Name, + "status": acc.Status, + "updated_time": acc.UpdatedTime, + } + res = append(res, temp) + } + return res +} + +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, + "right": rgAcl.Rights, + "status": rgAcl.Status, + "type": rgAcl.Type, + "user_group_id": rgAcl.UgroupID, + } + res = append(res, temp) + } + return res +} + +func dataSourceAccountListRead(ctx context.Context, d *schema.ResourceData, m interface{}) diag.Diagnostics { + accountList, err := utilityAccountListCheckPresence(ctx, d, m) + if err != nil { + d.SetId("") + return diag.FromErr(err) + } + + id := uuid.New() + d.SetId(id.String()) + d.Set("items", flattenAccountList(accountList)) + d.Set("entry_count", accountList.EntryCount) + + return nil +} + +func dataSourceAccountListSchemaMake() map[string]*schema.Schema { + res := map[string]*schema.Schema{ + "by_id": { + Type: schema.TypeInt, + Optional: true, + Description: "Filter by ID", + }, + "name": { + Type: schema.TypeString, + Optional: true, + Description: "Filter by name", + }, + "acl": { + Type: schema.TypeString, + Optional: true, + Description: "Filter by ACL", + }, + "status": { + Type: schema.TypeString, + Optional: true, + Description: "Filter by status", + }, + "page": { + Type: schema.TypeInt, + Optional: true, + Description: "Page number", + }, + "size": { + Type: schema.TypeInt, + Optional: true, + Description: "Page size", + }, + "items": { + Type: schema.TypeList, + Computed: true, + Elem: &schema.Resource{ + Schema: map[string]*schema.Schema{ + "acl": { + Type: schema.TypeList, + Computed: true, + Elem: &schema.Resource{ + Schema: map[string]*schema.Schema{ + "explicit": { + Type: schema.TypeBool, + Computed: true, + }, + "guid": { + Type: schema.TypeString, + Computed: true, + }, + "right": { + Type: schema.TypeString, + Computed: true, + }, + "status": { + Type: schema.TypeString, + Computed: true, + }, + "type": { + Type: schema.TypeString, + Computed: true, + }, + "user_group_id": { + Type: schema.TypeString, + Computed: true, + }, + }, + }, + }, + "created_time": { + Type: schema.TypeInt, + Computed: true, + }, + "deleted_time": { + Type: schema.TypeInt, + Computed: true, + }, + "account_id": { + Type: schema.TypeInt, + Computed: true, + }, + "account_name": { + Type: schema.TypeString, + Computed: true, + }, + "status": { + Type: schema.TypeString, + Computed: true, + }, + "updated_time": { + Type: schema.TypeInt, + Computed: true, + }, + }, + }, + }, + "entry_count": { + Type: schema.TypeInt, + Computed: true, + }, + } + return res +} + +func DataSourceAccountList() *schema.Resource { + return &schema.Resource{ + SchemaVersion: 1, + + ReadContext: dataSourceAccountListRead, + + Timeouts: &schema.ResourceTimeout{ + Read: &constants.Timeout30s, + Default: &constants.Timeout60s, + }, + + Schema: dataSourceAccountListSchemaMake(), + } +} diff --git a/internal/service/cloudapi/account/data_source_account_reserved_units.go b/internal/service/cloudapi/account/data_source_account_reserved_units.go index a323019..9d2341c 100644 --- a/internal/service/cloudapi/account/data_source_account_reserved_units.go +++ b/internal/service/cloudapi/account/data_source_account_reserved_units.go @@ -1,110 +1,116 @@ -/* -Copyright (c) 2019-2022 Digital Energy Cloud Solutions LLC. All Rights Reserved. -Authors: -Petr Krutov, -Stanislav Solovev, -Kasim Baybikov, - -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 - -import ( - "context" - - "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" -) - -func dataSourceAccountReservedUnitsRead(ctx context.Context, d *schema.ResourceData, m interface{}) diag.Diagnostics { - accountReservedUnits, err := utilityAccountReservedUnitsCheckPresence(ctx, d, m) - if err != nil { - return diag.FromErr(err) - } - - id := uuid.New() - d.SetId(id.String()) - d.Set("cu_c", accountReservedUnits.CUC) - d.Set("cu_d", accountReservedUnits.CUD) - d.Set("cu_i", accountReservedUnits.CUI) - d.Set("cu_m", accountReservedUnits.CUM) - d.Set("cu_np", accountReservedUnits.CUNP) - d.Set("gpu_units", accountReservedUnits.GPUUnits) - - return nil -} - -func dataSourceAccountReservedUnitsSchemaMake() map[string]*schema.Schema { - res := map[string]*schema.Schema{ - "account_id": { - Type: schema.TypeInt, - Required: true, - Description: "ID of the account", - }, - "cu_c": { - Type: schema.TypeFloat, - Computed: true, - }, - "cu_d": { - Type: schema.TypeFloat, - Computed: true, - }, - "cu_i": { - Type: schema.TypeFloat, - Computed: true, - }, - "cu_m": { - Type: schema.TypeFloat, - Computed: true, - }, - "cu_np": { - Type: schema.TypeFloat, - Computed: true, - }, - "gpu_units": { - Type: schema.TypeFloat, - Computed: true, - }, - } - return res -} - -func DataSourceAccountReservedUnits() *schema.Resource { - return &schema.Resource{ - SchemaVersion: 1, - - ReadContext: dataSourceAccountReservedUnitsRead, - - Timeouts: &schema.ResourceTimeout{ - Read: &constants.Timeout30s, - Default: &constants.Timeout60s, - }, - - Schema: dataSourceAccountReservedUnitsSchemaMake(), - } -} +/* +Copyright (c) 2019-2022 Digital Energy Cloud Solutions LLC. All Rights Reserved. +Authors: +Petr Krutov, +Stanislav Solovev, +Kasim Baybikov, + +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 + +import ( + "context" + + "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" +) + +func dataSourceAccountReservedUnitsRead(ctx context.Context, d *schema.ResourceData, m interface{}) diag.Diagnostics { + accountReservedUnits, err := utilityAccountReservedUnitsCheckPresence(ctx, d, m) + if err != nil { + d.SetId("") + return diag.FromErr(err) + } + + id := uuid.New() + d.SetId(id.String()) + d.Set("cu_c", accountReservedUnits.CUC) + d.Set("cu_d", accountReservedUnits.CUD) + d.Set("cu_dm", accountReservedUnits.CUDM) + d.Set("cu_i", accountReservedUnits.CUI) + d.Set("cu_m", accountReservedUnits.CUM) + d.Set("cu_np", accountReservedUnits.CUNP) + d.Set("gpu_units", accountReservedUnits.GPUUnits) + + return nil +} + +func dataSourceAccountReservedUnitsSchemaMake() map[string]*schema.Schema { + res := map[string]*schema.Schema{ + "account_id": { + Type: schema.TypeInt, + Required: true, + Description: "ID of the account", + }, + "cu_c": { + Type: schema.TypeFloat, + Computed: true, + }, + "cu_d": { + Type: schema.TypeFloat, + Computed: true, + }, + "cu_dm": { + Type: schema.TypeFloat, + Computed: true, + }, + "cu_i": { + Type: schema.TypeFloat, + Computed: true, + }, + "cu_m": { + Type: schema.TypeFloat, + Computed: true, + }, + "cu_np": { + Type: schema.TypeFloat, + Computed: true, + }, + "gpu_units": { + Type: schema.TypeFloat, + Computed: true, + }, + } + return res +} + +func DataSourceAccountReservedUnits() *schema.Resource { + return &schema.Resource{ + SchemaVersion: 1, + + ReadContext: dataSourceAccountReservedUnitsRead, + + Timeouts: &schema.ResourceTimeout{ + Read: &constants.Timeout30s, + Default: &constants.Timeout60s, + }, + + Schema: dataSourceAccountReservedUnitsSchemaMake(), + } +} diff --git a/internal/service/cloudapi/account/data_source_account_resource_consumption_list.go b/internal/service/cloudapi/account/data_source_account_resource_consumption_list.go index ca50e28..120f9ec 100644 --- a/internal/service/cloudapi/account/data_source_account_resource_consumption_list.go +++ b/internal/service/cloudapi/account/data_source_account_resource_consumption_list.go @@ -44,6 +44,7 @@ import ( func dataSourceAccountResourceConsumptionListRead(ctx context.Context, d *schema.ResourceData, m interface{}) diag.Diagnostics { accountResourceConsumptionList, err := utilityAccountResourceConsumptionListCheckPresence(ctx, d, m) if err != nil { + d.SetId("") return diag.FromErr(err) } diff --git a/internal/service/cloudapi/account/data_source_account_rg_list.go b/internal/service/cloudapi/account/data_source_account_rg_list.go index d36f0b3..edad40f 100644 --- a/internal/service/cloudapi/account/data_source_account_rg_list.go +++ b/internal/service/cloudapi/account/data_source_account_rg_list.go @@ -1,371 +1,372 @@ -/* -Copyright (c) 2019-2022 Digital Energy Cloud Solutions LLC. All Rights Reserved. -Authors: -Petr Krutov, -Stanislav Solovev, -Kasim Baybikov, - -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 - -import ( - "context" - - "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 *account.ListRG) []map[string]interface{} { - res := make([]map[string]interface{}, 0) - for _, arg := range argl.Data { - temp := map[string]interface{}{ - "computes": flattenAccRGComputes(arg.Computes), - "resources": flattenAccRGResources(arg.Resources), - "created_by": arg.CreatedBy, - "created_time": arg.CreatedTime, - "deleted_by": arg.DeletedBy, - "deleted_time": arg.DeletedTime, - "rg_id": arg.RGID, - "milestones": arg.Milestones, - "rg_name": arg.RGName, - "status": arg.Status, - "updated_by": arg.UpdatedBy, - "updated_time": arg.UpdatedTime, - "vinses": arg.VINSes, - } - res = append(res, temp) - } - return res - -} - -func flattenAccRGComputes(argc account.RGComputes) []map[string]interface{} { - res := make([]map[string]interface{}, 0) - temp := map[string]interface{}{ - "started": argc.Started, - "stopped": argc.Stopped, - } - res = append(res, temp) - return res -} - -func 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, - "gpu": r.GPU, - "ram": r.RAM, - //"seps": flattenAccountSeps(r.SEPs), - } - res = append(res, temp) - return res -} - -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, - "gpu": r.GPU, - "ram": r.RAM, - } - res = append(res, temp) - return res -} - -func flattenAccRGResources(argr account.RGResources) []map[string]interface{} { - res := make([]map[string]interface{}, 0) - temp := map[string]interface{}{ - "consumed": flattenAccResourceRg(argr.Consumed), - "limits": flattenAccResourceHack(argr.Limits), - "reserved": flattenAccResourceRg(argr.Reserved), - } - res = append(res, temp) - return res -} - -func dataSourceAccountRGListRead(ctx context.Context, d *schema.ResourceData, m interface{}) diag.Diagnostics { - accountRGList, err := utilityAccountRGListCheckPresence(ctx, d, m) - if err != nil { - return diag.FromErr(err) - } - - id := uuid.New() - d.SetId(id.String()) - d.Set("items", flattenAccountRGList(accountRGList)) - d.Set("entry_count", accountRGList.EntryCount) - - return nil -} - -func dataSourceAccountRGListSchemaMake() map[string]*schema.Schema { - res := map[string]*schema.Schema{ - "account_id": { - Type: schema.TypeInt, - Required: true, - Description: "ID of the account", - }, - "page": { - Type: schema.TypeInt, - Optional: true, - Description: "Page number", - }, - "size": { - Type: schema.TypeInt, - Optional: true, - Description: "Page size", - }, - "rg_id": { - Type: schema.TypeInt, - Optional: true, - Description: "Filter by RG ID", - }, - "vins_id": { - Type: schema.TypeInt, - Optional: true, - Description: "Filter by ViNS ID", - }, - "vm_id": { - Type: schema.TypeInt, - Optional: true, - Description: "Filter by VM ID", - }, - "name": { - Type: schema.TypeString, - Optional: true, - Description: "Filter by name", - }, - "status": { - Type: schema.TypeString, - Optional: true, - Description: "Filter by status", - }, - "items": { - Type: schema.TypeList, - Computed: true, - Description: "Search Result", - Elem: &schema.Resource{ - Schema: map[string]*schema.Schema{ - "computes": { - Type: schema.TypeList, - Computed: true, - Elem: &schema.Resource{ - Schema: map[string]*schema.Schema{ - "started": { - Type: schema.TypeInt, - Computed: true, - }, - "stopped": { - Type: schema.TypeInt, - Computed: true, - }, - }, - }, - }, - "resources": { - Type: schema.TypeList, - Computed: true, - Elem: &schema.Resource{ - Schema: map[string]*schema.Schema{ - "consumed": { - Type: schema.TypeList, - Computed: true, - Elem: &schema.Resource{ - Schema: map[string]*schema.Schema{ - "cpu": { - Type: schema.TypeInt, - Computed: true, - }, - "disksize": { - Type: schema.TypeInt, - Computed: true, - }, - "extips": { - Type: schema.TypeInt, - Computed: true, - }, - "exttraffic": { - Type: schema.TypeInt, - Computed: true, - }, - "gpu": { - Type: schema.TypeInt, - Computed: true, - }, - "ram": { - Type: schema.TypeInt, - Computed: true, - }, - }, - }, - }, - - "limits": { - Type: schema.TypeList, - Computed: true, - Elem: &schema.Resource{ - Schema: map[string]*schema.Schema{ - "cpu": { - Type: schema.TypeInt, - Computed: true, - }, - "disksize": { - Type: schema.TypeInt, - Computed: true, - }, - "extips": { - Type: schema.TypeInt, - Computed: true, - }, - "exttraffic": { - Type: schema.TypeInt, - Computed: true, - }, - "gpu": { - Type: schema.TypeInt, - Computed: true, - }, - "ram": { - Type: schema.TypeInt, - Computed: true, - }, - }, - }, - }, - "reserved": { - Type: schema.TypeList, - Computed: true, - Elem: &schema.Resource{ - Schema: map[string]*schema.Schema{ - "cpu": { - Type: schema.TypeInt, - Computed: true, - }, - "disksize": { - Type: schema.TypeInt, - Computed: true, - }, - "extips": { - Type: schema.TypeInt, - Computed: true, - }, - "exttraffic": { - Type: schema.TypeInt, - Computed: true, - }, - "gpu": { - Type: schema.TypeInt, - Computed: true, - }, - "ram": { - Type: schema.TypeInt, - Computed: true, - }, - }, - }, - }, - }, - }, - }, - - "created_by": { - Type: schema.TypeString, - Computed: true, - }, - "created_time": { - Type: schema.TypeInt, - Computed: true, - }, - "deleted_by": { - Type: schema.TypeString, - Computed: true, - }, - "deleted_time": { - Type: schema.TypeInt, - Computed: true, - }, - "rg_id": { - Type: schema.TypeInt, - Computed: true, - }, - "milestones": { - Type: schema.TypeInt, - Computed: true, - }, - "rg_name": { - Type: schema.TypeString, - Computed: true, - }, - "status": { - Type: schema.TypeString, - Computed: true, - }, - "updated_by": { - Type: schema.TypeString, - Computed: true, - }, - "updated_time": { - Type: schema.TypeInt, - Computed: true, - }, - "vinses": { - Type: schema.TypeInt, - Computed: true, - }, - }, - }, - }, - "entry_count": { - Type: schema.TypeInt, - Computed: true, - }, - } - return res -} - -func DataSourceAccountRGList() *schema.Resource { - return &schema.Resource{ - SchemaVersion: 1, - - ReadContext: dataSourceAccountRGListRead, - - Timeouts: &schema.ResourceTimeout{ - Read: &constants.Timeout30s, - Default: &constants.Timeout60s, - }, - - Schema: dataSourceAccountRGListSchemaMake(), - } -} +/* +Copyright (c) 2019-2022 Digital Energy Cloud Solutions LLC. All Rights Reserved. +Authors: +Petr Krutov, +Stanislav Solovev, +Kasim Baybikov, + +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 + +import ( + "context" + + "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 *account.ListRG) []map[string]interface{} { + res := make([]map[string]interface{}, 0) + for _, arg := range argl.Data { + temp := map[string]interface{}{ + "computes": flattenAccRGComputes(arg.Computes), + "resources": flattenAccRGResources(arg.Resources), + "created_by": arg.CreatedBy, + "created_time": arg.CreatedTime, + "deleted_by": arg.DeletedBy, + "deleted_time": arg.DeletedTime, + "rg_id": arg.RGID, + "milestones": arg.Milestones, + "rg_name": arg.RGName, + "status": arg.Status, + "updated_by": arg.UpdatedBy, + "updated_time": arg.UpdatedTime, + "vinses": arg.VINSes, + } + res = append(res, temp) + } + return res + +} + +func flattenAccRGComputes(argc account.RGComputes) []map[string]interface{} { + res := make([]map[string]interface{}, 0) + temp := map[string]interface{}{ + "started": argc.Started, + "stopped": argc.Stopped, + } + res = append(res, temp) + return res +} + +func 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, + "gpu": r.GPU, + "ram": r.RAM, + //"seps": flattenAccountSeps(r.SEPs), + } + res = append(res, temp) + return res +} + +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, + "gpu": r.GPU, + "ram": r.RAM, + } + res = append(res, temp) + return res +} + +func flattenAccRGResources(argr account.RGResources) []map[string]interface{} { + res := make([]map[string]interface{}, 0) + temp := map[string]interface{}{ + "consumed": flattenAccResourceRg(argr.Consumed), + "limits": flattenAccResourceHack(argr.Limits), + "reserved": flattenAccResourceRg(argr.Reserved), + } + res = append(res, temp) + return res +} + +func dataSourceAccountRGListRead(ctx context.Context, d *schema.ResourceData, m interface{}) diag.Diagnostics { + accountRGList, err := utilityAccountRGListCheckPresence(ctx, d, m) + if err != nil { + d.SetId("") + return diag.FromErr(err) + } + + id := uuid.New() + d.SetId(id.String()) + d.Set("items", flattenAccountRGList(accountRGList)) + d.Set("entry_count", accountRGList.EntryCount) + + return nil +} + +func dataSourceAccountRGListSchemaMake() map[string]*schema.Schema { + res := map[string]*schema.Schema{ + "account_id": { + Type: schema.TypeInt, + Required: true, + Description: "ID of the account", + }, + "page": { + Type: schema.TypeInt, + Optional: true, + Description: "Page number", + }, + "size": { + Type: schema.TypeInt, + Optional: true, + Description: "Page size", + }, + "rg_id": { + Type: schema.TypeInt, + Optional: true, + Description: "Filter by RG ID", + }, + "vins_id": { + Type: schema.TypeInt, + Optional: true, + Description: "Filter by ViNS ID", + }, + "vm_id": { + Type: schema.TypeInt, + Optional: true, + Description: "Filter by VM ID", + }, + "name": { + Type: schema.TypeString, + Optional: true, + Description: "Filter by name", + }, + "status": { + Type: schema.TypeString, + Optional: true, + Description: "Filter by status", + }, + "items": { + Type: schema.TypeList, + Computed: true, + Description: "Search Result", + Elem: &schema.Resource{ + Schema: map[string]*schema.Schema{ + "computes": { + Type: schema.TypeList, + Computed: true, + Elem: &schema.Resource{ + Schema: map[string]*schema.Schema{ + "started": { + Type: schema.TypeInt, + Computed: true, + }, + "stopped": { + Type: schema.TypeInt, + Computed: true, + }, + }, + }, + }, + "resources": { + Type: schema.TypeList, + Computed: true, + Elem: &schema.Resource{ + Schema: map[string]*schema.Schema{ + "consumed": { + Type: schema.TypeList, + Computed: true, + Elem: &schema.Resource{ + Schema: map[string]*schema.Schema{ + "cpu": { + Type: schema.TypeInt, + Computed: true, + }, + "disksize": { + Type: schema.TypeInt, + Computed: true, + }, + "extips": { + Type: schema.TypeInt, + Computed: true, + }, + "exttraffic": { + Type: schema.TypeInt, + Computed: true, + }, + "gpu": { + Type: schema.TypeInt, + Computed: true, + }, + "ram": { + Type: schema.TypeInt, + Computed: true, + }, + }, + }, + }, + + "limits": { + Type: schema.TypeList, + Computed: true, + Elem: &schema.Resource{ + Schema: map[string]*schema.Schema{ + "cpu": { + Type: schema.TypeInt, + Computed: true, + }, + "disksize": { + Type: schema.TypeInt, + Computed: true, + }, + "extips": { + Type: schema.TypeInt, + Computed: true, + }, + "exttraffic": { + Type: schema.TypeInt, + Computed: true, + }, + "gpu": { + Type: schema.TypeInt, + Computed: true, + }, + "ram": { + Type: schema.TypeInt, + Computed: true, + }, + }, + }, + }, + "reserved": { + Type: schema.TypeList, + Computed: true, + Elem: &schema.Resource{ + Schema: map[string]*schema.Schema{ + "cpu": { + Type: schema.TypeInt, + Computed: true, + }, + "disksize": { + Type: schema.TypeInt, + Computed: true, + }, + "extips": { + Type: schema.TypeInt, + Computed: true, + }, + "exttraffic": { + Type: schema.TypeInt, + Computed: true, + }, + "gpu": { + Type: schema.TypeInt, + Computed: true, + }, + "ram": { + Type: schema.TypeInt, + Computed: true, + }, + }, + }, + }, + }, + }, + }, + + "created_by": { + Type: schema.TypeString, + Computed: true, + }, + "created_time": { + Type: schema.TypeInt, + Computed: true, + }, + "deleted_by": { + Type: schema.TypeString, + Computed: true, + }, + "deleted_time": { + Type: schema.TypeInt, + Computed: true, + }, + "rg_id": { + Type: schema.TypeInt, + Computed: true, + }, + "milestones": { + Type: schema.TypeInt, + Computed: true, + }, + "rg_name": { + Type: schema.TypeString, + Computed: true, + }, + "status": { + Type: schema.TypeString, + Computed: true, + }, + "updated_by": { + Type: schema.TypeString, + Computed: true, + }, + "updated_time": { + Type: schema.TypeInt, + Computed: true, + }, + "vinses": { + Type: schema.TypeInt, + Computed: true, + }, + }, + }, + }, + "entry_count": { + Type: schema.TypeInt, + Computed: true, + }, + } + return res +} + +func DataSourceAccountRGList() *schema.Resource { + return &schema.Resource{ + SchemaVersion: 1, + + ReadContext: dataSourceAccountRGListRead, + + Timeouts: &schema.ResourceTimeout{ + Read: &constants.Timeout30s, + Default: &constants.Timeout60s, + }, + + Schema: dataSourceAccountRGListSchemaMake(), + } +} diff --git a/internal/service/cloudapi/account/data_source_account_templates_list.go b/internal/service/cloudapi/account/data_source_account_templates_list.go index a9120bf..2607a30 100644 --- a/internal/service/cloudapi/account/data_source_account_templates_list.go +++ b/internal/service/cloudapi/account/data_source_account_templates_list.go @@ -1,185 +1,186 @@ -/* -Copyright (c) 2019-2022 Digital Energy Cloud Solutions LLC. All Rights Reserved. -Authors: -Petr Krutov, -Stanislav Solovev, -Kasim Baybikov, - -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 - -import ( - "context" - - "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 *account.ListTemplates) []map[string]interface{} { - res := make([]map[string]interface{}, 0, len(atl.Data)) - for _, at := range atl.Data { - temp := map[string]interface{}{ - "unc_path": at.UNCPath, - "account_id": at.AccountID, - "desc": at.Description, - "template_id": at.ID, - "template_name": at.Name, - "public": at.Public, - "size": at.Size, - "status": at.Status, - "type": at.Type, - "username": at.Username, - } - res = append(res, temp) - } - return res - -} - -func dataSourceAccountTemplatesListRead(ctx context.Context, d *schema.ResourceData, m interface{}) diag.Diagnostics { - accountTemplatesList, err := utilityAccountTemplatesListCheckPresence(ctx, d, m) - if err != nil { - return diag.FromErr(err) - } - - id := uuid.New() - d.SetId(id.String()) - d.Set("items", flattenAccountTemplatesList(accountTemplatesList)) - d.Set("entry_count", accountTemplatesList.EntryCount) - return nil -} - -func dataSourceAccountTemplatesListSchemaMake() map[string]*schema.Schema { - res := map[string]*schema.Schema{ - "account_id": { - Type: schema.TypeInt, - Required: true, - Description: "ID of the account", - }, - "include_deleted": { - Type: schema.TypeBool, - Optional: true, - }, - "image_id": { - Type: schema.TypeInt, - Optional: true, - Description: "Find by image id", - }, - "name": { - Type: schema.TypeString, - Optional: true, - Description: "Filter by name", - }, - "type": { - Type: schema.TypeString, - Optional: true, - Description: "Filter by type", - }, - "page": { - Type: schema.TypeInt, - Optional: true, - Description: "Page number", - }, - "size": { - Type: schema.TypeInt, - Optional: true, - Description: "Page size", - }, - "items": { - Type: schema.TypeList, - Computed: true, - Description: "Search Result", - Elem: &schema.Resource{ - Schema: map[string]*schema.Schema{ - "unc_path": { - Type: schema.TypeString, - Computed: true, - }, - "account_id": { - Type: schema.TypeInt, - Computed: true, - }, - "desc": { - Type: schema.TypeString, - Computed: true, - }, - "template_id": { - Type: schema.TypeInt, - Computed: true, - }, - "template_name": { - Type: schema.TypeString, - Computed: true, - }, - "public": { - Type: schema.TypeBool, - Computed: true, - }, - "size": { - Type: schema.TypeInt, - Computed: true, - }, - "status": { - Type: schema.TypeString, - Computed: true, - }, - "type": { - Type: schema.TypeString, - Computed: true, - }, - "username": { - Type: schema.TypeString, - Computed: true, - }, - }, - }, - }, - "entry_count": { - Type: schema.TypeInt, - Computed: true, - }, - } - return res -} - -func DataSourceAccountTemplatessList() *schema.Resource { - return &schema.Resource{ - SchemaVersion: 1, - - ReadContext: dataSourceAccountTemplatesListRead, - - Timeouts: &schema.ResourceTimeout{ - Read: &constants.Timeout30s, - Default: &constants.Timeout60s, - }, - - Schema: dataSourceAccountTemplatesListSchemaMake(), - } -} +/* +Copyright (c) 2019-2022 Digital Energy Cloud Solutions LLC. All Rights Reserved. +Authors: +Petr Krutov, +Stanislav Solovev, +Kasim Baybikov, + +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 + +import ( + "context" + + "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 *account.ListTemplates) []map[string]interface{} { + res := make([]map[string]interface{}, 0, len(atl.Data)) + for _, at := range atl.Data { + temp := map[string]interface{}{ + "unc_path": at.UNCPath, + "account_id": at.AccountID, + "desc": at.Description, + "template_id": at.ID, + "template_name": at.Name, + "public": at.Public, + "size": at.Size, + "status": at.Status, + "type": at.Type, + "username": at.Username, + } + res = append(res, temp) + } + return res + +} + +func dataSourceAccountTemplatesListRead(ctx context.Context, d *schema.ResourceData, m interface{}) diag.Diagnostics { + accountTemplatesList, err := utilityAccountTemplatesListCheckPresence(ctx, d, m) + if err != nil { + d.SetId("") + return diag.FromErr(err) + } + + id := uuid.New() + d.SetId(id.String()) + d.Set("items", flattenAccountTemplatesList(accountTemplatesList)) + d.Set("entry_count", accountTemplatesList.EntryCount) + return nil +} + +func dataSourceAccountTemplatesListSchemaMake() map[string]*schema.Schema { + res := map[string]*schema.Schema{ + "account_id": { + Type: schema.TypeInt, + Required: true, + Description: "ID of the account", + }, + "include_deleted": { + Type: schema.TypeBool, + Optional: true, + }, + "image_id": { + Type: schema.TypeInt, + Optional: true, + Description: "Find by image id", + }, + "name": { + Type: schema.TypeString, + Optional: true, + Description: "Filter by name", + }, + "type": { + Type: schema.TypeString, + Optional: true, + Description: "Filter by type", + }, + "page": { + Type: schema.TypeInt, + Optional: true, + Description: "Page number", + }, + "size": { + Type: schema.TypeInt, + Optional: true, + Description: "Page size", + }, + "items": { + Type: schema.TypeList, + Computed: true, + Description: "Search Result", + Elem: &schema.Resource{ + Schema: map[string]*schema.Schema{ + "unc_path": { + Type: schema.TypeString, + Computed: true, + }, + "account_id": { + Type: schema.TypeInt, + Computed: true, + }, + "desc": { + Type: schema.TypeString, + Computed: true, + }, + "template_id": { + Type: schema.TypeInt, + Computed: true, + }, + "template_name": { + Type: schema.TypeString, + Computed: true, + }, + "public": { + Type: schema.TypeBool, + Computed: true, + }, + "size": { + Type: schema.TypeInt, + Computed: true, + }, + "status": { + Type: schema.TypeString, + Computed: true, + }, + "type": { + Type: schema.TypeString, + Computed: true, + }, + "username": { + Type: schema.TypeString, + Computed: true, + }, + }, + }, + }, + "entry_count": { + Type: schema.TypeInt, + Computed: true, + }, + } + return res +} + +func DataSourceAccountTemplatessList() *schema.Resource { + return &schema.Resource{ + SchemaVersion: 1, + + ReadContext: dataSourceAccountTemplatesListRead, + + Timeouts: &schema.ResourceTimeout{ + Read: &constants.Timeout30s, + Default: &constants.Timeout60s, + }, + + Schema: dataSourceAccountTemplatesListSchemaMake(), + } +} diff --git a/internal/service/cloudapi/account/data_source_account_vins_list.go b/internal/service/cloudapi/account/data_source_account_vins_list.go index 81f9857..6451cae 100644 --- a/internal/service/cloudapi/account/data_source_account_vins_list.go +++ b/internal/service/cloudapi/account/data_source_account_vins_list.go @@ -1,222 +1,223 @@ -/* -Copyright (c) 2019-2022 Digital Energy Cloud Solutions LLC. All Rights Reserved. -Authors: -Petr Krutov, -Stanislav Solovev, -Kasim Baybikov, - -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 - -import ( - "context" - - "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 *account.ListVINS) []map[string]interface{} { - res := make([]map[string]interface{}, 0) - for _, av := range avl.Data { - temp := map[string]interface{}{ - "account_id": av.AccountID, - "account_name": av.AccountName, - "computes": av.Computes, - "created_by": av.CreatedBy, - "created_time": av.CreatedTime, - "deleted_by": av.DeletedBy, - "deleted_time": av.DeletedTime, - "external_ip": av.ExternalIP, - "vin_id": av.ID, - "vin_name": av.Name, - "network": av.Network, - "pri_vnf_dev_id": av.PriVNFDevID, - "rg_id": av.RGID, - "rg_name": av.RGName, - "status": av.Status, - "updated_by": av.UpdatedBy, - "updated_time": av.UpdatedTime, - } - res = append(res, temp) - } - return res - -} - -func dataSourceAccountVinsListRead(ctx context.Context, d *schema.ResourceData, m interface{}) diag.Diagnostics { - accountVinsList, err := utilityAccountVinsListCheckPresence(ctx, d, m) - if err != nil { - return diag.FromErr(err) - } - - id := uuid.New() - d.SetId(id.String()) - d.Set("items", flattenAccountVinsList(accountVinsList)) - d.Set("entry_count", accountVinsList.EntryCount) - - return nil -} - -func dataSourceAccountVinsListSchemaMake() map[string]*schema.Schema { - res := map[string]*schema.Schema{ - "account_id": { - Type: schema.TypeInt, - Required: true, - Description: "ID of the account", - }, - "vins_id": { - Type: schema.TypeInt, - Optional: true, - Description: "Filter by ViNS ID", - }, - "name": { - Type: schema.TypeString, - Optional: true, - Description: "Filter by name", - }, - "rg_id": { - Type: schema.TypeInt, - Optional: true, - Description: "Filter by RG ID", - }, - "ext_ip": { - Type: schema.TypeString, - Optional: true, - Description: "Filter by external IP", - }, - "page": { - Type: schema.TypeInt, - Optional: true, - Description: "Page number", - }, - "size": { - Type: schema.TypeInt, - Optional: true, - Description: "Page size", - }, - "items": { - Type: schema.TypeList, - Computed: true, - Description: "Search Result", - Elem: &schema.Resource{ - Schema: map[string]*schema.Schema{ - "account_id": { - Type: schema.TypeInt, - Computed: true, - }, - "account_name": { - Type: schema.TypeString, - Computed: true, - }, - "computes": { - Type: schema.TypeInt, - Computed: true, - }, - "created_by": { - Type: schema.TypeString, - Computed: true, - }, - "created_time": { - Type: schema.TypeInt, - Computed: true, - }, - "deleted_by": { - Type: schema.TypeString, - Computed: true, - }, - "deleted_time": { - Type: schema.TypeInt, - Computed: true, - }, - "external_ip": { - Type: schema.TypeString, - Computed: true, - }, - "vin_id": { - Type: schema.TypeInt, - Computed: true, - }, - "vin_name": { - Type: schema.TypeString, - Computed: true, - }, - "network": { - Type: schema.TypeString, - Computed: true, - }, - "pri_vnf_dev_id": { - Type: schema.TypeInt, - Computed: true, - }, - "rg_id": { - Type: schema.TypeInt, - Computed: true, - }, - "rg_name": { - Type: schema.TypeString, - Computed: true, - }, - "status": { - Type: schema.TypeString, - Computed: true, - }, - "updated_by": { - Type: schema.TypeString, - Computed: true, - }, - "updated_time": { - Type: schema.TypeInt, - Computed: true, - }, - }, - }, - }, - "entry_count": { - Type: schema.TypeInt, - Computed: true, - }, - } - return res -} - -func DataSourceAccountVinsList() *schema.Resource { - return &schema.Resource{ - SchemaVersion: 1, - - ReadContext: dataSourceAccountVinsListRead, - - Timeouts: &schema.ResourceTimeout{ - Read: &constants.Timeout30s, - Default: &constants.Timeout60s, - }, - - Schema: dataSourceAccountVinsListSchemaMake(), - } -} +/* +Copyright (c) 2019-2022 Digital Energy Cloud Solutions LLC. All Rights Reserved. +Authors: +Petr Krutov, +Stanislav Solovev, +Kasim Baybikov, + +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 + +import ( + "context" + + "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 *account.ListVINS) []map[string]interface{} { + res := make([]map[string]interface{}, 0) + for _, av := range avl.Data { + temp := map[string]interface{}{ + "account_id": av.AccountID, + "account_name": av.AccountName, + "computes": av.Computes, + "created_by": av.CreatedBy, + "created_time": av.CreatedTime, + "deleted_by": av.DeletedBy, + "deleted_time": av.DeletedTime, + "external_ip": av.ExternalIP, + "vin_id": av.ID, + "vin_name": av.Name, + "network": av.Network, + "pri_vnf_dev_id": av.PriVNFDevID, + "rg_id": av.RGID, + "rg_name": av.RGName, + "status": av.Status, + "updated_by": av.UpdatedBy, + "updated_time": av.UpdatedTime, + } + res = append(res, temp) + } + return res + +} + +func dataSourceAccountVinsListRead(ctx context.Context, d *schema.ResourceData, m interface{}) diag.Diagnostics { + accountVinsList, err := utilityAccountVinsListCheckPresence(ctx, d, m) + if err != nil { + d.SetId("") + return diag.FromErr(err) + } + + id := uuid.New() + d.SetId(id.String()) + d.Set("items", flattenAccountVinsList(accountVinsList)) + d.Set("entry_count", accountVinsList.EntryCount) + + return nil +} + +func dataSourceAccountVinsListSchemaMake() map[string]*schema.Schema { + res := map[string]*schema.Schema{ + "account_id": { + Type: schema.TypeInt, + Required: true, + Description: "ID of the account", + }, + "vins_id": { + Type: schema.TypeInt, + Optional: true, + Description: "Filter by ViNS ID", + }, + "name": { + Type: schema.TypeString, + Optional: true, + Description: "Filter by name", + }, + "rg_id": { + Type: schema.TypeInt, + Optional: true, + Description: "Filter by RG ID", + }, + "ext_ip": { + Type: schema.TypeString, + Optional: true, + Description: "Filter by external IP", + }, + "page": { + Type: schema.TypeInt, + Optional: true, + Description: "Page number", + }, + "size": { + Type: schema.TypeInt, + Optional: true, + Description: "Page size", + }, + "items": { + Type: schema.TypeList, + Computed: true, + Description: "Search Result", + Elem: &schema.Resource{ + Schema: map[string]*schema.Schema{ + "account_id": { + Type: schema.TypeInt, + Computed: true, + }, + "account_name": { + Type: schema.TypeString, + Computed: true, + }, + "computes": { + Type: schema.TypeInt, + Computed: true, + }, + "created_by": { + Type: schema.TypeString, + Computed: true, + }, + "created_time": { + Type: schema.TypeInt, + Computed: true, + }, + "deleted_by": { + Type: schema.TypeString, + Computed: true, + }, + "deleted_time": { + Type: schema.TypeInt, + Computed: true, + }, + "external_ip": { + Type: schema.TypeString, + Computed: true, + }, + "vin_id": { + Type: schema.TypeInt, + Computed: true, + }, + "vin_name": { + Type: schema.TypeString, + Computed: true, + }, + "network": { + Type: schema.TypeString, + Computed: true, + }, + "pri_vnf_dev_id": { + Type: schema.TypeInt, + Computed: true, + }, + "rg_id": { + Type: schema.TypeInt, + Computed: true, + }, + "rg_name": { + Type: schema.TypeString, + Computed: true, + }, + "status": { + Type: schema.TypeString, + Computed: true, + }, + "updated_by": { + Type: schema.TypeString, + Computed: true, + }, + "updated_time": { + Type: schema.TypeInt, + Computed: true, + }, + }, + }, + }, + "entry_count": { + Type: schema.TypeInt, + Computed: true, + }, + } + return res +} + +func DataSourceAccountVinsList() *schema.Resource { + return &schema.Resource{ + SchemaVersion: 1, + + ReadContext: dataSourceAccountVinsListRead, + + Timeouts: &schema.ResourceTimeout{ + Read: &constants.Timeout30s, + Default: &constants.Timeout60s, + }, + + Schema: dataSourceAccountVinsListSchemaMake(), + } +} diff --git a/internal/service/cloudapi/account/resource_account.go b/internal/service/cloudapi/account/resource_account.go index 6cc1c0b..ca27a2f 100644 --- a/internal/service/cloudapi/account/resource_account.go +++ b/internal/service/cloudapi/account/resource_account.go @@ -1,649 +1,648 @@ -/* -Copyright (c) 2019-2022 Digital Energy Cloud Solutions LLC. All Rights Reserved. -Authors: -Petr Krutov, -Stanislav Solovev, -Kasim Baybikov, - -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 - -import ( - "context" - "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" -) - -func resourceAccountCreate(ctx context.Context, d *schema.ResourceData, m interface{}) diag.Diagnostics { - return diag.Errorf( - "Only users with admin privileges are able to create accounts. Contact your platform administrator.\nUse 'terraform import decort_account. ' command to import existing account configuration") -} - -func resourceAccountRead(ctx context.Context, d *schema.ResourceData, m interface{}) diag.Diagnostics { - log.Debugf("resourceAccountRead: called for account with ID: %v", d.Id()) - - // c := m.(*controller.ControllerCfg) - - acc, err := utilityAccountCheckPresence(ctx, d, m) - if err != nil { - d.SetId("") - return diag.FromErr(err) - } - - hasChanged := false - - switch acc.Status { - case status.Destroyed: - d.SetId("") - return diag.Errorf("The resource cannot be updated because it has been destroyed") - // return resourceAccountCreate(ctx, d, m) - case status.Destroying: - return diag.Errorf("The account is in progress with status: %s", acc.Status) - case status.Deleted: - // id, _ := strconv.ParseUint(d.Id(), 10, 64) - - // req := account.RestoreRequest{ - // AccountID: id, - // } - - // _, err := c.CloudAPI().Account().Restore(ctx, req) - // if err != nil { - // return diag.FromErr(err) - // } - - // hasChanged = true - case status.Disabled: - log.Debugf("The account is in status: %s, troubles may occur with update. Please, enable account first.", acc.Status) - case status.Confirmed: - } - - if hasChanged { - acc, err = utilityAccountCheckPresence(ctx, d, m) - if err != nil { - d.SetId("") - return diag.FromErr(err) - } - } - - flattenAccount(d, *acc) - - return nil -} - -func resourceAccountDelete(ctx context.Context, d *schema.ResourceData, m interface{}) diag.Diagnostics { - log.Debugf("resourceAccountDelete") - c := m.(*controller.ControllerCfg) - - _, 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("resourceAccountUpdate") - c := m.(*controller.ControllerCfg) - - 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 { - case status.Destroyed: - d.SetId("") - return diag.Errorf("The resource cannot be updated because it has been destroyed") - // return resourceAccountCreate(ctx, d, m) - case status.Destroying: - return diag.Errorf("The account is in progress with status: %s", acc.Status) - case status.Deleted: - - req := account.RestoreRequest{ - AccountID: accountId, - } - - _, err := c.CloudAPI().Account().Restore(ctx, req) - if err != nil { - return diag.FromErr(err) - } - - hasChanged = true - case status.Disabled: - log.Debugf("The account is in status: %s, troubles may occur with update. Please, enable account first.", acc.Status) - case status.Confirmed: - } - - if hasChanged { - acc, err = utilityAccountCheckPresence(ctx, d, m) - if err != nil { - d.SetId("") - return diag.FromErr(err) - } - } - - if d.HasChange("enable") { - reqSwitch := account.DisableEnableRequest{ - AccountID: accountId, - } - enable := d.Get("enable").(bool) - - if enable { - - _, err := c.CloudAPI().Account().Enable(ctx, reqSwitch) - if err != nil { - return diag.FromErr(err) - - } 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") { - 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{}) - - if resLimitConv["cu_m"] != nil { - maxMemCap := int(resLimitConv["cu_m"].(float64)) - if maxMemCap == 0 { - req.MaxMemoryCapacity = -1 - } else { - req.MaxMemoryCapacity = int64(maxMemCap) - } - updated = true - } - if resLimitConv["cu_d"] != nil { - maxDiskCap := int(resLimitConv["cu_d"].(float64)) - if maxDiskCap == 0 { - req.MaxVDiskCapacity = -1 - } else { - req.MaxVDiskCapacity = int64(maxDiskCap) - } - updated = true - } - if resLimitConv["cu_c"] != nil { - maxCPUCap := int(resLimitConv["cu_c"].(float64)) - if maxCPUCap == 0 { - req.MaxCPUCapacity = -1 - } else { - req.MaxCPUCapacity = int64(maxCPUCap) - } - updated = true - } - if resLimitConv["cu_i"] != nil { - maxNumPublicIP := int(resLimitConv["cu_i"].(float64)) - if maxNumPublicIP == 0 { - req.MaxNumPublicIP = -1 - } else { - req.MaxNumPublicIP = int64(maxNumPublicIP) - } - updated = true - } - if resLimitConv["cu_np"] != nil { - maxNP := int(resLimitConv["cu_np"].(float64)) - if maxNP == 0 { - req.MaxNetworkPeerTransfer = -1 - } else { - req.MaxNetworkPeerTransfer = int64(maxNP) - } - updated = true - } - if resLimitConv["gpu_units"] != nil { - gpuUnits := int(resLimitConv["gpu_units"].(float64)) - if gpuUnits == 0 { - req.GPUUnits = -1 - } else { - req.GPUUnits = int64(gpuUnits) - } - updated = true - } - } - - if d.HasChange("send_access_emails") { - 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) - } - } - - if d.HasChange("restore") { - restore := d.Get("restore").(bool) - if restore { - if acc.Status == "DELETED" { - req := account.RestoreRequest{ - AccountID: accountId, - } - _, err := c.CloudAPI().Account().Restore(ctx, req) - if err != nil { - return diag.FromErr(err) - } - } - } - } - - if d.HasChange("users") { - deletedUsers := make([]interface{}, 0) - addedUsers := make([]interface{}, 0) - updatedUsers := make([]interface{}, 0) - - old, new_ := d.GetChange("users") - oldConv := old.([]interface{}) - newConv := new_.([]interface{}) - for _, el := range oldConv { - if !isContainsUser(newConv, el) { - deletedUsers = append(deletedUsers, el) - } - } - for _, el := range newConv { - if !isContainsUser(oldConv, el) { - 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) - } - } - } - - if len(deletedUsers) > 0 { - for _, user := range deletedUsers { - userConv := user.(map[string]interface{}) - - 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) - } - } - } - - if len(addedUsers) > 0 { - for _, user := range addedUsers { - userConv := user.(map[string]interface{}) - - 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) - } - } - } - - if len(updatedUsers) > 0 { - for _, user := range updatedUsers { - userConv := user.(map[string]interface{}) - - 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) - } - } - } - - } - - return resourceAccountRead(ctx, d, m) -} - -func isContainsUser(els []interface{}, el interface{}) bool { - for _, elOld := range els { - elOldConv := elOld.(map[string]interface{}) - elConv := el.(map[string]interface{}) - if elOldConv["user_id"].(string) == elConv["user_id"].(string) { - return true - } - } - return false -} - -func isChangedUser(els []interface{}, el interface{}) bool { - for _, elOld := range els { - elOldConv := elOld.(map[string]interface{}) - elConv := el.(map[string]interface{}) - if elOldConv["user_id"].(string) == elConv["user_id"].(string) && - (!strings.EqualFold(elOldConv["access_type"].(string), elConv["access_type"].(string)) || - elOldConv["recursive_delete"].(bool) != elConv["recursive_delete"].(bool)) { - return true - } - } - return false -} - -func resourceAccountSchemaMake() map[string]*schema.Schema { - return map[string]*schema.Schema{ - "account_name": { - Type: schema.TypeString, - Required: true, - Description: "account name", - }, - "username": { - Type: schema.TypeString, - Required: true, - Description: "username of owner the account", - }, - "emailaddress": { - Type: schema.TypeString, - Optional: true, - Description: "email", - }, - "send_access_emails": { - Type: schema.TypeBool, - Optional: true, - Description: "if true send emails when a user is granted access to resources", - }, - "users": { - Type: schema.TypeList, - Optional: true, - Elem: &schema.Resource{ - Schema: map[string]*schema.Schema{ - "user_id": { - Type: schema.TypeString, - Required: true, - }, - "access_type": { - Type: schema.TypeString, - Required: true, - }, - "recursive_delete": { - Type: schema.TypeBool, - Optional: true, - Default: false, - }, - }, - }, - }, - "restore": { - Type: schema.TypeBool, - Optional: true, - Description: "restore a deleted account", - }, - "permanently": { - Type: schema.TypeBool, - Optional: true, - Default: false, - Description: "whether to completely delete the account", - }, - "enable": { - Type: schema.TypeBool, - Optional: true, - Description: "enable/disable account", - }, - "resource_limits": { - Type: schema.TypeList, - Optional: true, - Computed: true, - MaxItems: 1, - Elem: &schema.Resource{ - Schema: map[string]*schema.Schema{ - "cu_c": { - Type: schema.TypeFloat, - Optional: true, - Computed: true, - }, - "cu_d": { - Type: schema.TypeFloat, - Optional: true, - Computed: true, - }, - "cu_i": { - Type: schema.TypeFloat, - Optional: true, - Computed: true, - }, - "cu_m": { - Type: schema.TypeFloat, - Optional: true, - Computed: true, - }, - "cu_np": { - Type: schema.TypeFloat, - Optional: true, - Computed: true, - }, - "gpu_units": { - Type: schema.TypeFloat, - Optional: true, - Computed: true, - }, - }, - }, - }, - "account_id": { - Type: schema.TypeInt, - Computed: true, - }, - "dc_location": { - Type: schema.TypeString, - Computed: true, - }, - // "resources": { - // Type: schema.TypeList, - // Computed: true, - // Elem: &schema.Resource{ - // Schema: resourcesSchemaMake(), - // }, - // }, - "ckey": { - Type: schema.TypeString, - Computed: true, - }, - // "meta": { - // Type: schema.TypeList, - // Computed: true, - // Elem: &schema.Schema{ - // Type: schema.TypeString, - // }, - // }, - "acl": { - Type: schema.TypeList, - Computed: true, - Elem: &schema.Resource{ - Schema: aclSchemaMake(), - }, - }, - "company": { - Type: schema.TypeString, - Computed: true, - }, - "companyurl": { - Type: schema.TypeString, - Computed: true, - }, - "created_by": { - Type: schema.TypeString, - Computed: true, - }, - "created_time": { - Type: schema.TypeInt, - Computed: true, - }, - "deactivation_time": { - Type: schema.TypeFloat, - Computed: true, - }, - "deleted_by": { - Type: schema.TypeString, - Computed: true, - }, - "deleted_time": { - Type: schema.TypeInt, - Computed: true, - }, - "displayname": { - Type: schema.TypeString, - Computed: true, - }, - "guid": { - Type: schema.TypeInt, - Computed: true, - }, - "service_account": { - Type: schema.TypeBool, - Computed: true, - }, - "status": { - Type: schema.TypeString, - Computed: true, - }, - "updated_time": { - Type: schema.TypeInt, - Computed: true, - }, - "version": { - Type: schema.TypeInt, - Computed: true, - }, - "vins": { - Type: schema.TypeList, - Computed: true, - Elem: &schema.Schema{ - Type: schema.TypeInt, - }, - }, - "computes": { - Type: schema.TypeList, - Computed: true, - Elem: &schema.Resource{ - Schema: computesSchemaMake(), - }, - }, - "machines": { - Type: schema.TypeList, - Computed: true, - Elem: &schema.Resource{ - Schema: machinesSchemaMake(), - }, - }, - "vinses": { - Type: schema.TypeInt, - Computed: true, - }, - "cpu_allocation_parameter": { - Type: schema.TypeString, - Computed: true, - }, - "cpu_allocation_ratio": { - Type: schema.TypeFloat, - Computed: true, - }, - } -} - -func ResourceAccount() *schema.Resource { - return &schema.Resource{ - SchemaVersion: 1, - - CreateContext: resourceAccountCreate, - ReadContext: resourceAccountRead, - UpdateContext: resourceAccountUpdate, - DeleteContext: resourceAccountDelete, - - Importer: &schema.ResourceImporter{ - StateContext: schema.ImportStatePassthroughContext, - }, - - Timeouts: &schema.ResourceTimeout{ - Create: &constants.Timeout600s, - Read: &constants.Timeout300s, - Update: &constants.Timeout300s, - Delete: &constants.Timeout300s, - Default: &constants.Timeout300s, - }, - - Schema: resourceAccountSchemaMake(), - } -} +/* +Copyright (c) 2019-2022 Digital Energy Cloud Solutions LLC. All Rights Reserved. +Authors: +Petr Krutov, +Stanislav Solovev, +Kasim Baybikov, + +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 + +import ( + "context" + "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" +) + +func resourceAccountCreate(ctx context.Context, d *schema.ResourceData, m interface{}) diag.Diagnostics { + return diag.Errorf( + "Only users with admin privileges are able to create accounts. Contact your platform administrator.\nUse 'terraform import decort_account. ' command to import existing account configuration") +} + +func resourceAccountRead(ctx context.Context, d *schema.ResourceData, m interface{}) diag.Diagnostics { + log.Debugf("resourceAccountRead: called for account with ID: %v", d.Id()) + + // c := m.(*controller.ControllerCfg) + + acc, err := utilityAccountCheckPresence(ctx, d, m) + if err != nil { + d.SetId("") + return diag.FromErr(err) + } + + hasChanged := false + + switch acc.Status { + case status.Destroyed: + d.SetId("") + return diag.Errorf("The resource cannot be updated because it has been destroyed") + // return resourceAccountCreate(ctx, d, m) + case status.Destroying: + return diag.Errorf("The account is in progress with status: %s", acc.Status) + case status.Deleted: + // id, _ := strconv.ParseUint(d.Id(), 10, 64) + + // req := account.RestoreRequest{ + // AccountID: id, + // } + + // _, err := c.CloudAPI().Account().Restore(ctx, req) + // if err != nil { + // return diag.FromErr(err) + // } + + // hasChanged = true + case status.Disabled: + log.Debugf("The account is in status: %s, troubles may occur with update. Please, enable account first.", acc.Status) + case status.Confirmed: + } + + if hasChanged { + acc, err = utilityAccountCheckPresence(ctx, d, m) + if err != nil { + d.SetId("") + return diag.FromErr(err) + } + } + + flattenAccount(d, *acc) + + return nil +} + +func resourceAccountDelete(ctx context.Context, d *schema.ResourceData, m interface{}) diag.Diagnostics { + log.Debugf("resourceAccountDelete") + c := m.(*controller.ControllerCfg) + + _, 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("resourceAccountUpdate") + c := m.(*controller.ControllerCfg) + + 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 { + case status.Destroyed: + d.SetId("") + return diag.Errorf("The resource cannot be updated because it has been destroyed") + // return resourceAccountCreate(ctx, d, m) + case status.Destroying: + return diag.Errorf("The account is in progress with status: %s", acc.Status) + case status.Deleted: + if d.Get("restore").(bool) { + req := account.RestoreRequest{ + AccountID: accountId, + } + + _, err := c.CloudAPI().Account().Restore(ctx, req) + if err != nil { + return diag.FromErr(err) + } + + hasChanged = true + } + case status.Disabled: + log.Debugf("The account is in status: %s, troubles may occur with update. Please, enable account first.", acc.Status) + case status.Confirmed: + } + + if hasChanged { + acc, err = utilityAccountCheckPresence(ctx, d, m) + if err != nil { + d.SetId("") + return diag.FromErr(err) + } + } + + if d.HasChange("enable") { + reqSwitch := account.DisableEnableRequest{ + AccountID: accountId, + } + enable := d.Get("enable").(bool) + + if enable { + + _, err := c.CloudAPI().Account().Enable(ctx, reqSwitch) + if err != nil { + return diag.FromErr(err) + + } + } 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") { + 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{}) + + if resLimitConv["cu_m"] != nil { + maxMemCap := int(resLimitConv["cu_m"].(float64)) + if maxMemCap == 0 { + req.MaxMemoryCapacity = -1 + } else { + req.MaxMemoryCapacity = int64(maxMemCap) + } + updated = true + } + if resLimitConv["cu_d"] != nil { + maxDiskCap := int(resLimitConv["cu_d"].(float64)) + if maxDiskCap == 0 { + req.MaxVDiskCapacity = -1 + } else { + req.MaxVDiskCapacity = int64(maxDiskCap) + } + updated = true + } + if resLimitConv["cu_c"] != nil { + maxCPUCap := int(resLimitConv["cu_c"].(float64)) + if maxCPUCap == 0 { + req.MaxCPUCapacity = -1 + } else { + req.MaxCPUCapacity = int64(maxCPUCap) + } + updated = true + } + if resLimitConv["cu_i"] != nil { + maxNumPublicIP := int(resLimitConv["cu_i"].(float64)) + if maxNumPublicIP == 0 { + req.MaxNumPublicIP = -1 + } else { + req.MaxNumPublicIP = int64(maxNumPublicIP) + } + updated = true + } + if resLimitConv["cu_np"] != nil { + maxNP := int(resLimitConv["cu_np"].(float64)) + if maxNP == 0 { + req.MaxNetworkPeerTransfer = -1 + } else { + req.MaxNetworkPeerTransfer = int64(maxNP) + } + updated = true + } + if resLimitConv["gpu_units"] != nil { + gpuUnits := int(resLimitConv["gpu_units"].(float64)) + if gpuUnits == 0 { + req.GPUUnits = -1 + } else { + req.GPUUnits = int64(gpuUnits) + } + updated = true + } + } + + if d.HasChange("send_access_emails") { + 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) + } + } + + if d.HasChange("restore") { + restore := d.Get("restore").(bool) + if restore && acc.Status == "DELETED" { + req := account.RestoreRequest{ + AccountID: accountId, + } + _, err := c.CloudAPI().Account().Restore(ctx, req) + if err != nil { + return diag.FromErr(err) + } + } + } + + if d.HasChange("users") { + deletedUsers := make([]interface{}, 0) + addedUsers := make([]interface{}, 0) + updatedUsers := make([]interface{}, 0) + + old, new_ := d.GetChange("users") + oldConv := old.([]interface{}) + newConv := new_.([]interface{}) + for _, el := range oldConv { + if !isContainsUser(newConv, el) { + deletedUsers = append(deletedUsers, el) + } + } + for _, el := range newConv { + if !isContainsUser(oldConv, el) { + 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) + } + } + } + + if len(deletedUsers) > 0 { + for _, user := range deletedUsers { + userConv := user.(map[string]interface{}) + + 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) + } + } + } + + if len(addedUsers) > 0 { + for _, user := range addedUsers { + userConv := user.(map[string]interface{}) + + 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) + } + } + } + + if len(updatedUsers) > 0 { + for _, user := range updatedUsers { + userConv := user.(map[string]interface{}) + + 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) + } + } + } + + } + + return resourceAccountRead(ctx, d, m) +} + +func isContainsUser(els []interface{}, el interface{}) bool { + for _, elOld := range els { + elOldConv := elOld.(map[string]interface{}) + elConv := el.(map[string]interface{}) + if elOldConv["user_id"].(string) == elConv["user_id"].(string) { + return true + } + } + return false +} + +func isChangedUser(els []interface{}, el interface{}) bool { + for _, elOld := range els { + elOldConv := elOld.(map[string]interface{}) + elConv := el.(map[string]interface{}) + if elOldConv["user_id"].(string) == elConv["user_id"].(string) && + (!strings.EqualFold(elOldConv["access_type"].(string), elConv["access_type"].(string)) || + elOldConv["recursive_delete"].(bool) != elConv["recursive_delete"].(bool)) { + return true + } + } + return false +} + +func resourceAccountSchemaMake() map[string]*schema.Schema { + return map[string]*schema.Schema{ + "account_name": { + Type: schema.TypeString, + Required: true, + Description: "account name", + }, + "username": { + Type: schema.TypeString, + Required: true, + Description: "username of owner the account", + }, + "emailaddress": { + Type: schema.TypeString, + Optional: true, + Description: "email", + }, + "send_access_emails": { + Type: schema.TypeBool, + Optional: true, + Description: "if true send emails when a user is granted access to resources", + }, + "users": { + Type: schema.TypeList, + Optional: true, + Elem: &schema.Resource{ + Schema: map[string]*schema.Schema{ + "user_id": { + Type: schema.TypeString, + Required: true, + }, + "access_type": { + Type: schema.TypeString, + Required: true, + }, + "recursive_delete": { + Type: schema.TypeBool, + Optional: true, + Default: false, + }, + }, + }, + }, + "restore": { + Type: schema.TypeBool, + Optional: true, + Description: "restore a deleted account", + }, + "permanently": { + Type: schema.TypeBool, + Optional: true, + Default: false, + Description: "whether to completely delete the account", + }, + "enable": { + Type: schema.TypeBool, + Optional: true, + Description: "enable/disable account", + }, + "resource_limits": { + Type: schema.TypeList, + Optional: true, + Computed: true, + MaxItems: 1, + Elem: &schema.Resource{ + Schema: map[string]*schema.Schema{ + "cu_c": { + Type: schema.TypeFloat, + Optional: true, + Computed: true, + }, + "cu_d": { + Type: schema.TypeFloat, + Optional: true, + Computed: true, + }, + "cu_i": { + Type: schema.TypeFloat, + Optional: true, + Computed: true, + }, + "cu_m": { + Type: schema.TypeFloat, + Optional: true, + Computed: true, + }, + "cu_np": { + Type: schema.TypeFloat, + Optional: true, + Computed: true, + }, + "gpu_units": { + Type: schema.TypeFloat, + Optional: true, + Computed: true, + }, + }, + }, + }, + "account_id": { + Type: schema.TypeInt, + Computed: true, + }, + "dc_location": { + Type: schema.TypeString, + Computed: true, + }, + // "resources": { + // Type: schema.TypeList, + // Computed: true, + // Elem: &schema.Resource{ + // Schema: resourcesSchemaMake(), + // }, + // }, + "ckey": { + Type: schema.TypeString, + Computed: true, + }, + // "meta": { + // Type: schema.TypeList, + // Computed: true, + // Elem: &schema.Schema{ + // Type: schema.TypeString, + // }, + // }, + "acl": { + Type: schema.TypeList, + Computed: true, + Elem: &schema.Resource{ + Schema: aclSchemaMake(), + }, + }, + "company": { + Type: schema.TypeString, + Computed: true, + }, + "companyurl": { + Type: schema.TypeString, + Computed: true, + }, + "created_by": { + Type: schema.TypeString, + Computed: true, + }, + "created_time": { + Type: schema.TypeInt, + Computed: true, + }, + "deactivation_time": { + Type: schema.TypeFloat, + Computed: true, + }, + "deleted_by": { + Type: schema.TypeString, + Computed: true, + }, + "deleted_time": { + Type: schema.TypeInt, + Computed: true, + }, + "displayname": { + Type: schema.TypeString, + Computed: true, + }, + "guid": { + Type: schema.TypeInt, + Computed: true, + }, + "service_account": { + Type: schema.TypeBool, + Computed: true, + }, + "status": { + Type: schema.TypeString, + Computed: true, + }, + "updated_time": { + Type: schema.TypeInt, + Computed: true, + }, + "version": { + Type: schema.TypeInt, + Computed: true, + }, + "vins": { + Type: schema.TypeList, + Computed: true, + Elem: &schema.Schema{ + Type: schema.TypeInt, + }, + }, + "computes": { + Type: schema.TypeList, + Computed: true, + Elem: &schema.Resource{ + Schema: computesSchemaMake(), + }, + }, + "machines": { + Type: schema.TypeList, + Computed: true, + Elem: &schema.Resource{ + Schema: machinesSchemaMake(), + }, + }, + "vinses": { + Type: schema.TypeInt, + Computed: true, + }, + "cpu_allocation_parameter": { + Type: schema.TypeString, + Computed: true, + }, + "cpu_allocation_ratio": { + Type: schema.TypeFloat, + Computed: true, + }, + } +} + +func ResourceAccount() *schema.Resource { + return &schema.Resource{ + SchemaVersion: 1, + + CreateContext: resourceAccountCreate, + ReadContext: resourceAccountRead, + UpdateContext: resourceAccountUpdate, + DeleteContext: resourceAccountDelete, + + Importer: &schema.ResourceImporter{ + StateContext: schema.ImportStatePassthroughContext, + }, + + Timeouts: &schema.ResourceTimeout{ + Create: &constants.Timeout600s, + Read: &constants.Timeout300s, + Update: &constants.Timeout300s, + Delete: &constants.Timeout300s, + Default: &constants.Timeout300s, + }, + + Schema: resourceAccountSchemaMake(), + } +} diff --git a/internal/service/cloudapi/bservice/data_source_bservice.go b/internal/service/cloudapi/bservice/data_source_bservice.go index 1d6fe32..9f5e42f 100644 --- a/internal/service/cloudapi/bservice/data_source_bservice.go +++ b/internal/service/cloudapi/bservice/data_source_bservice.go @@ -1,297 +1,298 @@ -/* -Copyright (c) 2019-2022 Digital Energy Cloud Solutions LLC. All Rights Reserved. -Authors: -Petr Krutov, -Stanislav Solovev, -Kasim Baybikov, - -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 - -import ( - "context" - "strconv" - - "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" -) - -func dataSourceBasicServiceRead(ctx context.Context, d *schema.ResourceData, m interface{}) diag.Diagnostics { - bs, err := utilityBasicServiceCheckPresence(ctx, d, m) - if err != nil { - return diag.FromErr(err) - } - - d.SetId(strconv.FormatUint(bs.ID, 10)) - - flattenService(d, bs) - - return nil -} - -func dataSourceBasicServiceSchemaMake() map[string]*schema.Schema { - res := map[string]*schema.Schema{ - "service_id": { - Type: schema.TypeInt, - Required: true, - }, - "account_id": { - Type: schema.TypeInt, - Computed: true, - }, - "account_name": { - Type: schema.TypeString, - Computed: true, - }, - "base_domain": { - Type: schema.TypeString, - Computed: true, - }, - "computes": { - Type: schema.TypeList, - Computed: true, - Elem: &schema.Resource{ - Schema: map[string]*schema.Schema{ - "account_id": { - Type: schema.TypeInt, - Computed: true, - }, - "architecture": { - Type: schema.TypeString, - Computed: true, - }, - "compgroup_id": { - Type: schema.TypeInt, - Computed: true, - }, - "compgroup_name": { - Type: schema.TypeString, - Computed: true, - }, - "compgroup_role": { - Type: schema.TypeString, - Computed: true, - }, - "id": { - Type: schema.TypeInt, - Computed: true, - }, - "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, - }, - "created_by": { - Type: schema.TypeString, - Computed: true, - }, - "created_time": { - Type: schema.TypeInt, - Computed: true, - }, - "deleted_by": { - Type: schema.TypeString, - Computed: true, - }, - "deleted_time": { - Type: schema.TypeInt, - Computed: true, - }, - "disk_total": { - Type: schema.TypeInt, - Computed: true, - }, - "gid": { - Type: schema.TypeInt, - Computed: true, - }, - "groups": { - Type: schema.TypeList, - Computed: true, - 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": { - // Type: schema.TypeList, - // Computed: true, - // Elem: &schema.Schema{ - // Type: schema.TypeString, - // }, - // }, - "guid": { - Type: schema.TypeInt, - Computed: true, - }, - "milestones": { - Type: schema.TypeInt, - Computed: true, - }, - "service_name": { - Type: schema.TypeString, - Computed: true, - }, - "parent_srv_id": { - Type: schema.TypeInt, - Computed: true, - }, - "parent_srv_type": { - Type: schema.TypeString, - Computed: true, - }, - "ram_total": { - Type: schema.TypeInt, - Computed: true, - }, - "rg_id": { - Type: schema.TypeInt, - Computed: true, - }, - "rg_name": { - Type: schema.TypeString, - Computed: true, - }, - "snapshots": { - Type: schema.TypeList, - Computed: true, - Elem: &schema.Resource{ - Schema: map[string]*schema.Schema{ - "guid": { - Type: schema.TypeString, - Computed: true, - }, - "label": { - Type: schema.TypeString, - Computed: true, - }, - "timestamp": { - Type: schema.TypeInt, - Computed: true, - }, - "valid": { - Type: schema.TypeBool, - Computed: true, - }, - }, - }, - }, - - "ssh_key": { - Type: schema.TypeString, - Computed: true, - }, - "ssh_user": { - Type: schema.TypeString, - Computed: true, - }, - "status": { - Type: schema.TypeString, - Computed: true, - }, - "tech_status": { - Type: schema.TypeString, - Computed: true, - }, - "updated_by": { - Type: schema.TypeString, - Computed: true, - }, - "updated_time": { - Type: schema.TypeInt, - Computed: true, - }, - "user_managed": { - Type: schema.TypeBool, - Computed: true, - }, - } - return res -} - -func DataSourceBasicService() *schema.Resource { - return &schema.Resource{ - SchemaVersion: 1, - - ReadContext: dataSourceBasicServiceRead, - - Timeouts: &schema.ResourceTimeout{ - Read: &constants.Timeout30s, - Default: &constants.Timeout60s, - }, - - Schema: dataSourceBasicServiceSchemaMake(), - } -} +/* +Copyright (c) 2019-2022 Digital Energy Cloud Solutions LLC. All Rights Reserved. +Authors: +Petr Krutov, +Stanislav Solovev, +Kasim Baybikov, + +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 + +import ( + "context" + "strconv" + + "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" +) + +func dataSourceBasicServiceRead(ctx context.Context, d *schema.ResourceData, m interface{}) diag.Diagnostics { + bs, err := utilityBasicServiceCheckPresence(ctx, d, m) + if err != nil { + d.SetId("") + return diag.FromErr(err) + } + + d.SetId(strconv.FormatUint(bs.ID, 10)) + + flattenService(d, bs) + + return nil +} + +func dataSourceBasicServiceSchemaMake() map[string]*schema.Schema { + res := map[string]*schema.Schema{ + "service_id": { + Type: schema.TypeInt, + Required: true, + }, + "account_id": { + Type: schema.TypeInt, + Computed: true, + }, + "account_name": { + Type: schema.TypeString, + Computed: true, + }, + "base_domain": { + Type: schema.TypeString, + Computed: true, + }, + "computes": { + Type: schema.TypeList, + Computed: true, + Elem: &schema.Resource{ + Schema: map[string]*schema.Schema{ + "account_id": { + Type: schema.TypeInt, + Computed: true, + }, + "architecture": { + Type: schema.TypeString, + Computed: true, + }, + "compgroup_id": { + Type: schema.TypeInt, + Computed: true, + }, + "compgroup_name": { + Type: schema.TypeString, + Computed: true, + }, + "compgroup_role": { + Type: schema.TypeString, + Computed: true, + }, + "id": { + Type: schema.TypeInt, + Computed: true, + }, + "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, + }, + "created_by": { + Type: schema.TypeString, + Computed: true, + }, + "created_time": { + Type: schema.TypeInt, + Computed: true, + }, + "deleted_by": { + Type: schema.TypeString, + Computed: true, + }, + "deleted_time": { + Type: schema.TypeInt, + Computed: true, + }, + "disk_total": { + Type: schema.TypeInt, + Computed: true, + }, + "gid": { + Type: schema.TypeInt, + Computed: true, + }, + "groups": { + Type: schema.TypeList, + Computed: true, + 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": { + // Type: schema.TypeList, + // Computed: true, + // Elem: &schema.Schema{ + // Type: schema.TypeString, + // }, + // }, + "guid": { + Type: schema.TypeInt, + Computed: true, + }, + "milestones": { + Type: schema.TypeInt, + Computed: true, + }, + "service_name": { + Type: schema.TypeString, + Computed: true, + }, + "parent_srv_id": { + Type: schema.TypeInt, + Computed: true, + }, + "parent_srv_type": { + Type: schema.TypeString, + Computed: true, + }, + "ram_total": { + Type: schema.TypeInt, + Computed: true, + }, + "rg_id": { + Type: schema.TypeInt, + Computed: true, + }, + "rg_name": { + Type: schema.TypeString, + Computed: true, + }, + "snapshots": { + Type: schema.TypeList, + Computed: true, + Elem: &schema.Resource{ + Schema: map[string]*schema.Schema{ + "guid": { + Type: schema.TypeString, + Computed: true, + }, + "label": { + Type: schema.TypeString, + Computed: true, + }, + "timestamp": { + Type: schema.TypeInt, + Computed: true, + }, + "valid": { + Type: schema.TypeBool, + Computed: true, + }, + }, + }, + }, + + "ssh_key": { + Type: schema.TypeString, + Computed: true, + }, + "ssh_user": { + Type: schema.TypeString, + Computed: true, + }, + "status": { + Type: schema.TypeString, + Computed: true, + }, + "tech_status": { + Type: schema.TypeString, + Computed: true, + }, + "updated_by": { + Type: schema.TypeString, + Computed: true, + }, + "updated_time": { + Type: schema.TypeInt, + Computed: true, + }, + "user_managed": { + Type: schema.TypeBool, + Computed: true, + }, + } + return res +} + +func DataSourceBasicService() *schema.Resource { + return &schema.Resource{ + SchemaVersion: 1, + + ReadContext: dataSourceBasicServiceRead, + + Timeouts: &schema.ResourceTimeout{ + Read: &constants.Timeout30s, + Default: &constants.Timeout60s, + }, + + Schema: dataSourceBasicServiceSchemaMake(), + } +} diff --git a/internal/service/cloudapi/bservice/data_source_bservice_deleted_list.go b/internal/service/cloudapi/bservice/data_source_bservice_deleted_list.go index ebedd71..31c51ae 100644 --- a/internal/service/cloudapi/bservice/data_source_bservice_deleted_list.go +++ b/internal/service/cloudapi/bservice/data_source_bservice_deleted_list.go @@ -1,84 +1,85 @@ -/* -Copyright (c) 2019-2022 Digital Energy Cloud Solutions LLC. All Rights Reserved. -Authors: -Petr Krutov, -Stanislav Solovev, -Kasim Baybikov, - -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 - -import ( - "context" - - "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" -) - -func dataSourceBasicServiceDeletedListRead(ctx context.Context, d *schema.ResourceData, m interface{}) diag.Diagnostics { - basicServiceDeletedList, err := utilityBasicServiceDeletedListCheckPresence(ctx, d, m) - if err != nil { - return diag.FromErr(err) - } - - id := uuid.New() - d.SetId(id.String()) - d.Set("items", flattenBasicServiceList(basicServiceDeletedList)) - d.Set("entry_count", basicServiceDeletedList.EntryCount) - - return nil -} - -func dataSourceBasicServiceDeletedListSchemaMake() map[string]*schema.Schema { - temp := dataSourceBasicServiceListSchemaMake() - - delete(temp, "by_id") - delete(temp, "name") - delete(temp, "rg_name") - delete(temp, "status") - delete(temp, "tech_status") - delete(temp, "account_name") - - return temp -} - -func DataSourceBasicServiceDeletedList() *schema.Resource { - return &schema.Resource{ - SchemaVersion: 1, - - ReadContext: dataSourceBasicServiceDeletedListRead, - - Timeouts: &schema.ResourceTimeout{ - Read: &constants.Timeout30s, - Default: &constants.Timeout60s, - }, - - Schema: dataSourceBasicServiceDeletedListSchemaMake(), - } -} +/* +Copyright (c) 2019-2022 Digital Energy Cloud Solutions LLC. All Rights Reserved. +Authors: +Petr Krutov, +Stanislav Solovev, +Kasim Baybikov, + +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 + +import ( + "context" + + "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" +) + +func dataSourceBasicServiceDeletedListRead(ctx context.Context, d *schema.ResourceData, m interface{}) diag.Diagnostics { + basicServiceDeletedList, err := utilityBasicServiceDeletedListCheckPresence(ctx, d, m) + if err != nil { + d.SetId("") + return diag.FromErr(err) + } + + id := uuid.New() + d.SetId(id.String()) + d.Set("items", flattenBasicServiceList(basicServiceDeletedList)) + d.Set("entry_count", basicServiceDeletedList.EntryCount) + + return nil +} + +func dataSourceBasicServiceDeletedListSchemaMake() map[string]*schema.Schema { + temp := dataSourceBasicServiceListSchemaMake() + + delete(temp, "by_id") + delete(temp, "name") + delete(temp, "rg_name") + delete(temp, "status") + delete(temp, "tech_status") + delete(temp, "account_name") + + return temp +} + +func DataSourceBasicServiceDeletedList() *schema.Resource { + return &schema.Resource{ + SchemaVersion: 1, + + ReadContext: dataSourceBasicServiceDeletedListRead, + + Timeouts: &schema.ResourceTimeout{ + Read: &constants.Timeout30s, + Default: &constants.Timeout60s, + }, + + Schema: dataSourceBasicServiceDeletedListSchemaMake(), + } +} diff --git a/internal/service/cloudapi/bservice/data_source_bservice_group.go b/internal/service/cloudapi/bservice/data_source_bservice_group.go index c08a443..1619c73 100644 --- a/internal/service/cloudapi/bservice/data_source_bservice_group.go +++ b/internal/service/cloudapi/bservice/data_source_bservice_group.go @@ -1,304 +1,305 @@ -/* -Copyright (c) 2019-2022 Digital Energy Cloud Solutions LLC. All Rights Reserved. -Authors: -Petr Krutov, -Stanislav Solovev, -Kasim Baybikov, - -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 - -import ( - "context" - - "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 dataSourceBasicServiceGroupRead(ctx context.Context, d *schema.ResourceData, m interface{}) diag.Diagnostics { - bsg, err := utilityBasicServiceGroupCheckPresence(ctx, d, m) - if err != nil { - return diag.FromErr(err) - } - - id := uuid.New() - d.SetId(id.String()) - d.Set("account_id", bsg.AccountID) - d.Set("account_name", bsg.AccountName) - d.Set("computes", flattenBSGroupComputes(bsg.Computes)) - d.Set("consistency", bsg.Consistency) - d.Set("cpu", bsg.CPU) - d.Set("created_by", bsg.CreatedBy) - d.Set("created_time", bsg.CreatedTime) - d.Set("deleted_by", bsg.DeletedBy) - d.Set("deleted_time", bsg.DeletedTime) - d.Set("disk", bsg.Disk) - d.Set("driver", bsg.Driver) - d.Set("extnets", bsg.ExtNets) - d.Set("gid", bsg.GID) - d.Set("guid", bsg.GUID) - d.Set("image_id", bsg.ImageID) - d.Set("milestones", bsg.Milestones) - d.Set("compgroup_name", bsg.Name) - d.Set("parents", bsg.Parents) - d.Set("ram", bsg.RAM) - d.Set("rg_id", bsg.RGID) - d.Set("rg_name", bsg.RGName) - d.Set("role", bsg.Role) - d.Set("sep_id", bsg.SEPID) - d.Set("seq_no", bsg.SeqNo) - d.Set("status", bsg.Status) - d.Set("tech_status", bsg.TechStatus) - d.Set("timeout_start", bsg.TimeoutStart) - d.Set("updated_by", bsg.UpdatedBy) - d.Set("updated_time", bsg.UpdatedTime) - d.Set("vinses", bsg.VINSes) - return nil -} - -func flattenBSGroupOSUsers(bsgosus bservice.ListOSUsers) []map[string]interface{} { - res := make([]map[string]interface{}, 0) - for _, bsgosu := range bsgosus { - temp := map[string]interface{}{ - "login": bsgosu.Login, - "password": bsgosu.Password, - } - res = append(res, temp) - } - - return res -} - -func flattenBSGroupComputes(bsgcs 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.IPAddresses, - "name": bsgc.Name, - "os_users": flattenBSGroupOSUsers(bsgc.OSUsers), - } - res = append(res, temp) - } - return res -} - -func dataSourceBasicServiceGroupSchemaMake() map[string]*schema.Schema { - res := map[string]*schema.Schema{ - "service_id": { - Type: schema.TypeInt, - Required: true, - }, - "compgroup_id": { - Type: schema.TypeInt, - Required: true, - }, - "account_id": { - Type: schema.TypeInt, - Computed: true, - }, - "account_name": { - Type: schema.TypeString, - Computed: true, - }, - "computes": { - Type: schema.TypeList, - Computed: true, - Elem: &schema.Resource{ - Schema: map[string]*schema.Schema{ - "id": { - Type: schema.TypeInt, - Computed: true, - }, - "ip_addresses": { - Type: schema.TypeList, - Computed: true, - Elem: &schema.Schema{ - Type: schema.TypeString, - }, - }, - "name": { - Type: schema.TypeString, - Computed: true, - }, - "os_users": { - Type: schema.TypeList, - Computed: true, - Elem: &schema.Resource{ - Schema: map[string]*schema.Schema{ - "login": { - Type: schema.TypeString, - Computed: true, - }, - "password": { - Type: schema.TypeString, - Computed: true, - }, - }, - }, - }, - }, - }, - }, - "consistency": { - Type: schema.TypeBool, - Computed: true, - }, - "cpu": { - Type: schema.TypeInt, - Computed: true, - }, - "created_by": { - Type: schema.TypeString, - Computed: true, - }, - "created_time": { - Type: schema.TypeInt, - Computed: true, - }, - "deleted_by": { - Type: schema.TypeString, - Computed: true, - }, - "deleted_time": { - Type: schema.TypeInt, - Computed: true, - }, - "disk": { - Type: schema.TypeInt, - Computed: true, - }, - "driver": { - Type: schema.TypeString, - Computed: true, - }, - "extnets": { - Type: schema.TypeList, - Computed: true, - Elem: &schema.Schema{ - Type: schema.TypeInt, - }, - }, - "gid": { - Type: schema.TypeInt, - Computed: true, - }, - "guid": { - Type: schema.TypeInt, - Computed: true, - }, - "image_id": { - Type: schema.TypeInt, - Computed: true, - }, - "milestones": { - Type: schema.TypeInt, - Computed: true, - }, - "compgroup_name": { - Type: schema.TypeString, - Computed: true, - }, - "parents": { - Type: schema.TypeList, - Computed: true, - Elem: &schema.Schema{ - Type: schema.TypeInt, - }, - }, - "ram": { - Type: schema.TypeInt, - Computed: true, - }, - "rg_id": { - Type: schema.TypeInt, - Computed: true, - }, - "rg_name": { - Type: schema.TypeString, - Computed: true, - }, - "role": { - Type: schema.TypeString, - Computed: true, - }, - "sep_id": { - Type: schema.TypeInt, - Computed: true, - }, - "seq_no": { - Type: schema.TypeInt, - Computed: true, - }, - "status": { - Type: schema.TypeString, - Computed: true, - }, - "tech_status": { - Type: schema.TypeString, - Computed: true, - }, - "timeout_start": { - Type: schema.TypeInt, - Computed: true, - }, - "updated_by": { - Type: schema.TypeString, - Computed: true, - }, - "updated_time": { - Type: schema.TypeInt, - Computed: true, - }, - "vinses": { - Type: schema.TypeList, - Computed: true, - Elem: &schema.Schema{ - Type: schema.TypeInt, - }, - }, - } - return res -} - -func DataSourceBasicServiceGroup() *schema.Resource { - return &schema.Resource{ - SchemaVersion: 1, - - ReadContext: dataSourceBasicServiceGroupRead, - - Timeouts: &schema.ResourceTimeout{ - Read: &constants.Timeout30s, - Default: &constants.Timeout60s, - }, - - Schema: dataSourceBasicServiceGroupSchemaMake(), - } -} +/* +Copyright (c) 2019-2022 Digital Energy Cloud Solutions LLC. All Rights Reserved. +Authors: +Petr Krutov, +Stanislav Solovev, +Kasim Baybikov, + +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 + +import ( + "context" + + "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 dataSourceBasicServiceGroupRead(ctx context.Context, d *schema.ResourceData, m interface{}) diag.Diagnostics { + bsg, err := utilityBasicServiceGroupCheckPresence(ctx, d, m) + if err != nil { + d.SetId("") + return diag.FromErr(err) + } + + id := uuid.New() + d.SetId(id.String()) + d.Set("account_id", bsg.AccountID) + d.Set("account_name", bsg.AccountName) + d.Set("computes", flattenBSGroupComputes(bsg.Computes)) + d.Set("consistency", bsg.Consistency) + d.Set("cpu", bsg.CPU) + d.Set("created_by", bsg.CreatedBy) + d.Set("created_time", bsg.CreatedTime) + d.Set("deleted_by", bsg.DeletedBy) + d.Set("deleted_time", bsg.DeletedTime) + d.Set("disk", bsg.Disk) + d.Set("driver", bsg.Driver) + d.Set("extnets", bsg.ExtNets) + d.Set("gid", bsg.GID) + d.Set("guid", bsg.GUID) + d.Set("image_id", bsg.ImageID) + d.Set("milestones", bsg.Milestones) + d.Set("compgroup_name", bsg.Name) + d.Set("parents", bsg.Parents) + d.Set("ram", bsg.RAM) + d.Set("rg_id", bsg.RGID) + d.Set("rg_name", bsg.RGName) + d.Set("role", bsg.Role) + d.Set("sep_id", bsg.SEPID) + d.Set("seq_no", bsg.SeqNo) + d.Set("status", bsg.Status) + d.Set("tech_status", bsg.TechStatus) + d.Set("timeout_start", bsg.TimeoutStart) + d.Set("updated_by", bsg.UpdatedBy) + d.Set("updated_time", bsg.UpdatedTime) + d.Set("vinses", bsg.VINSes) + return nil +} + +func flattenBSGroupOSUsers(bsgosus bservice.ListOSUsers) []map[string]interface{} { + res := make([]map[string]interface{}, 0) + for _, bsgosu := range bsgosus { + temp := map[string]interface{}{ + "login": bsgosu.Login, + "password": bsgosu.Password, + } + res = append(res, temp) + } + + return res +} + +func flattenBSGroupComputes(bsgcs 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.IPAddresses, + "name": bsgc.Name, + "os_users": flattenBSGroupOSUsers(bsgc.OSUsers), + } + res = append(res, temp) + } + return res +} + +func dataSourceBasicServiceGroupSchemaMake() map[string]*schema.Schema { + res := map[string]*schema.Schema{ + "service_id": { + Type: schema.TypeInt, + Required: true, + }, + "compgroup_id": { + Type: schema.TypeInt, + Required: true, + }, + "account_id": { + Type: schema.TypeInt, + Computed: true, + }, + "account_name": { + Type: schema.TypeString, + Computed: true, + }, + "computes": { + Type: schema.TypeList, + Computed: true, + Elem: &schema.Resource{ + Schema: map[string]*schema.Schema{ + "id": { + Type: schema.TypeInt, + Computed: true, + }, + "ip_addresses": { + Type: schema.TypeList, + Computed: true, + Elem: &schema.Schema{ + Type: schema.TypeString, + }, + }, + "name": { + Type: schema.TypeString, + Computed: true, + }, + "os_users": { + Type: schema.TypeList, + Computed: true, + Elem: &schema.Resource{ + Schema: map[string]*schema.Schema{ + "login": { + Type: schema.TypeString, + Computed: true, + }, + "password": { + Type: schema.TypeString, + Computed: true, + }, + }, + }, + }, + }, + }, + }, + "consistency": { + Type: schema.TypeBool, + Computed: true, + }, + "cpu": { + Type: schema.TypeInt, + Computed: true, + }, + "created_by": { + Type: schema.TypeString, + Computed: true, + }, + "created_time": { + Type: schema.TypeInt, + Computed: true, + }, + "deleted_by": { + Type: schema.TypeString, + Computed: true, + }, + "deleted_time": { + Type: schema.TypeInt, + Computed: true, + }, + "disk": { + Type: schema.TypeInt, + Computed: true, + }, + "driver": { + Type: schema.TypeString, + Computed: true, + }, + "extnets": { + Type: schema.TypeList, + Computed: true, + Elem: &schema.Schema{ + Type: schema.TypeInt, + }, + }, + "gid": { + Type: schema.TypeInt, + Computed: true, + }, + "guid": { + Type: schema.TypeInt, + Computed: true, + }, + "image_id": { + Type: schema.TypeInt, + Computed: true, + }, + "milestones": { + Type: schema.TypeInt, + Computed: true, + }, + "compgroup_name": { + Type: schema.TypeString, + Computed: true, + }, + "parents": { + Type: schema.TypeList, + Computed: true, + Elem: &schema.Schema{ + Type: schema.TypeInt, + }, + }, + "ram": { + Type: schema.TypeInt, + Computed: true, + }, + "rg_id": { + Type: schema.TypeInt, + Computed: true, + }, + "rg_name": { + Type: schema.TypeString, + Computed: true, + }, + "role": { + Type: schema.TypeString, + Computed: true, + }, + "sep_id": { + Type: schema.TypeInt, + Computed: true, + }, + "seq_no": { + Type: schema.TypeInt, + Computed: true, + }, + "status": { + Type: schema.TypeString, + Computed: true, + }, + "tech_status": { + Type: schema.TypeString, + Computed: true, + }, + "timeout_start": { + Type: schema.TypeInt, + Computed: true, + }, + "updated_by": { + Type: schema.TypeString, + Computed: true, + }, + "updated_time": { + Type: schema.TypeInt, + Computed: true, + }, + "vinses": { + Type: schema.TypeList, + Computed: true, + Elem: &schema.Schema{ + Type: schema.TypeInt, + }, + }, + } + return res +} + +func DataSourceBasicServiceGroup() *schema.Resource { + return &schema.Resource{ + SchemaVersion: 1, + + ReadContext: dataSourceBasicServiceGroupRead, + + Timeouts: &schema.ResourceTimeout{ + Read: &constants.Timeout30s, + Default: &constants.Timeout60s, + }, + + Schema: dataSourceBasicServiceGroupSchemaMake(), + } +} diff --git a/internal/service/cloudapi/bservice/data_source_bservice_list.go b/internal/service/cloudapi/bservice/data_source_bservice_list.go index 225d74f..94be8d3 100644 --- a/internal/service/cloudapi/bservice/data_source_bservice_list.go +++ b/internal/service/cloudapi/bservice/data_source_bservice_list.go @@ -1,263 +1,264 @@ -/* -Copyright (c) 2019-2022 Digital Energy Cloud Solutions LLC. All Rights Reserved. -Authors: -Petr Krutov, -Stanislav Solovev, -Kasim Baybikov, - -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 - -import ( - "context" - - "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 *bservice.ListBasicServices) []map[string]interface{} { - res := make([]map[string]interface{}, 0) - for _, bs := range bsl.Data { - temp := map[string]interface{}{ - "account_id": bs.AccountID, - "account_name": bs.AccountName, - "base_domain": bs.BaseDomain, - "created_by": bs.CreatedBy, - "created_time": bs.CreatedTime, - "deleted_by": bs.DeletedBy, - "deleted_time": bs.DeletedTime, - "gid": bs.GID, - "groups": bs.Groups, - "guid": bs.GUID, - "service_id": bs.ID, - "service_name": bs.Name, - "parent_srv_id": bs.ParentSrvID, - "parent_srv_type": bs.ParentSrvType, - "rg_id": bs.RGID, - "rg_name": bs.RGName, - "ssh_user": bs.SSHUser, - "status": bs.Status, - "tech_status": bs.TechStatus, - "updated_by": bs.UpdatedBy, - "updated_time": bs.UpdatedTime, - "user_managed": bs.UserManaged, - } - res = append(res, temp) - } - return res -} - -func dataSourceBasicServiceListRead(ctx context.Context, d *schema.ResourceData, m interface{}) diag.Diagnostics { - basicServiceList, err := utilityBasicServiceListCheckPresence(ctx, d, m) - if err != nil { - return diag.FromErr(err) - } - - id := uuid.New() - d.SetId(id.String()) - d.Set("items", flattenBasicServiceList(basicServiceList)) - d.Set("entry_count", basicServiceList.EntryCount) - - return nil -} - -func dataSourceBasicServiceListSchemaMake() map[string]*schema.Schema { - res := map[string]*schema.Schema{ - "by_id": { - Type: schema.TypeInt, - Optional: true, - Description: "Filter by ID", - }, - "name": { - Type: schema.TypeString, - Optional: true, - Description: "Filter by bservice name", - }, - "rg_name": { - Type: schema.TypeString, - Optional: true, - Description: "Filter by resource group name", - }, - "status": { - Type: schema.TypeString, - Optional: true, - Description: "Filter by status", - }, - "tech_status": { - Type: schema.TypeString, - Optional: true, - Description: "Filter by tech status", - }, - "account_name": { - Type: schema.TypeString, - Optional: true, - Description: "Filter by account name", - }, - "account_id": { - Type: schema.TypeInt, - Optional: true, - Description: "ID of the account to query for BasicService instances", - }, - "rg_id": { - Type: schema.TypeInt, - Optional: true, - Description: "ID of the resource group to query for BasicService instances", - }, - "page": { - Type: schema.TypeInt, - Optional: true, - Description: "Page number", - }, - "size": { - Type: schema.TypeInt, - Optional: true, - Description: "Page size", - }, - "items": { - Type: schema.TypeList, - Computed: true, - Elem: &schema.Resource{ - Schema: map[string]*schema.Schema{ - "account_id": { - Type: schema.TypeInt, - Computed: true, - }, - "account_name": { - Type: schema.TypeString, - Computed: true, - }, - "base_domain": { - Type: schema.TypeString, - Computed: true, - }, - "created_by": { - Type: schema.TypeString, - Computed: true, - }, - "created_time": { - Type: schema.TypeInt, - Computed: true, - }, - "deleted_by": { - Type: schema.TypeString, - Computed: true, - }, - "deleted_time": { - Type: schema.TypeInt, - Computed: true, - }, - "gid": { - Type: schema.TypeInt, - Computed: true, - }, - "groups": { - Type: schema.TypeList, - Computed: true, - Elem: &schema.Schema{ - Type: schema.TypeInt, - }, - }, - "guid": { - Type: schema.TypeInt, - Computed: true, - }, - "service_id": { - Type: schema.TypeInt, - Computed: true, - }, - "service_name": { - Type: schema.TypeString, - Computed: true, - }, - "parent_srv_id": { - Type: schema.TypeInt, - Computed: true, - }, - "parent_srv_type": { - Type: schema.TypeString, - Computed: true, - }, - "rg_id": { - Type: schema.TypeInt, - Computed: true, - }, - "rg_name": { - Type: schema.TypeString, - Computed: true, - }, - "ssh_user": { - Type: schema.TypeString, - Computed: true, - }, - "status": { - Type: schema.TypeString, - Computed: true, - }, - "tech_status": { - Type: schema.TypeString, - Computed: true, - }, - "updated_by": { - Type: schema.TypeString, - Computed: true, - }, - "updated_time": { - Type: schema.TypeInt, - Computed: true, - }, - "user_managed": { - Type: schema.TypeBool, - Computed: true, - }, - }, - }, - }, - "entry_count": { - Type: schema.TypeInt, - Computed: true, - }, - } - return res -} - -func DataSourceBasicServiceList() *schema.Resource { - return &schema.Resource{ - SchemaVersion: 1, - - ReadContext: dataSourceBasicServiceListRead, - - Timeouts: &schema.ResourceTimeout{ - Read: &constants.Timeout30s, - Default: &constants.Timeout60s, - }, - - Schema: dataSourceBasicServiceListSchemaMake(), - } -} +/* +Copyright (c) 2019-2022 Digital Energy Cloud Solutions LLC. All Rights Reserved. +Authors: +Petr Krutov, +Stanislav Solovev, +Kasim Baybikov, + +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 + +import ( + "context" + + "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 *bservice.ListBasicServices) []map[string]interface{} { + res := make([]map[string]interface{}, 0) + for _, bs := range bsl.Data { + temp := map[string]interface{}{ + "account_id": bs.AccountID, + "account_name": bs.AccountName, + "base_domain": bs.BaseDomain, + "created_by": bs.CreatedBy, + "created_time": bs.CreatedTime, + "deleted_by": bs.DeletedBy, + "deleted_time": bs.DeletedTime, + "gid": bs.GID, + "groups": bs.Groups, + "guid": bs.GUID, + "service_id": bs.ID, + "service_name": bs.Name, + "parent_srv_id": bs.ParentSrvID, + "parent_srv_type": bs.ParentSrvType, + "rg_id": bs.RGID, + "rg_name": bs.RGName, + "ssh_user": bs.SSHUser, + "status": bs.Status, + "tech_status": bs.TechStatus, + "updated_by": bs.UpdatedBy, + "updated_time": bs.UpdatedTime, + "user_managed": bs.UserManaged, + } + res = append(res, temp) + } + return res +} + +func dataSourceBasicServiceListRead(ctx context.Context, d *schema.ResourceData, m interface{}) diag.Diagnostics { + basicServiceList, err := utilityBasicServiceListCheckPresence(ctx, d, m) + if err != nil { + d.SetId("") + return diag.FromErr(err) + } + + id := uuid.New() + d.SetId(id.String()) + d.Set("items", flattenBasicServiceList(basicServiceList)) + d.Set("entry_count", basicServiceList.EntryCount) + + return nil +} + +func dataSourceBasicServiceListSchemaMake() map[string]*schema.Schema { + res := map[string]*schema.Schema{ + "by_id": { + Type: schema.TypeInt, + Optional: true, + Description: "Filter by ID", + }, + "name": { + Type: schema.TypeString, + Optional: true, + Description: "Filter by bservice name", + }, + "rg_name": { + Type: schema.TypeString, + Optional: true, + Description: "Filter by resource group name", + }, + "status": { + Type: schema.TypeString, + Optional: true, + Description: "Filter by status", + }, + "tech_status": { + Type: schema.TypeString, + Optional: true, + Description: "Filter by tech status", + }, + "account_name": { + Type: schema.TypeString, + Optional: true, + Description: "Filter by account name", + }, + "account_id": { + Type: schema.TypeInt, + Optional: true, + Description: "ID of the account to query for BasicService instances", + }, + "rg_id": { + Type: schema.TypeInt, + Optional: true, + Description: "ID of the resource group to query for BasicService instances", + }, + "page": { + Type: schema.TypeInt, + Optional: true, + Description: "Page number", + }, + "size": { + Type: schema.TypeInt, + Optional: true, + Description: "Page size", + }, + "items": { + Type: schema.TypeList, + Computed: true, + Elem: &schema.Resource{ + Schema: map[string]*schema.Schema{ + "account_id": { + Type: schema.TypeInt, + Computed: true, + }, + "account_name": { + Type: schema.TypeString, + Computed: true, + }, + "base_domain": { + Type: schema.TypeString, + Computed: true, + }, + "created_by": { + Type: schema.TypeString, + Computed: true, + }, + "created_time": { + Type: schema.TypeInt, + Computed: true, + }, + "deleted_by": { + Type: schema.TypeString, + Computed: true, + }, + "deleted_time": { + Type: schema.TypeInt, + Computed: true, + }, + "gid": { + Type: schema.TypeInt, + Computed: true, + }, + "groups": { + Type: schema.TypeList, + Computed: true, + Elem: &schema.Schema{ + Type: schema.TypeInt, + }, + }, + "guid": { + Type: schema.TypeInt, + Computed: true, + }, + "service_id": { + Type: schema.TypeInt, + Computed: true, + }, + "service_name": { + Type: schema.TypeString, + Computed: true, + }, + "parent_srv_id": { + Type: schema.TypeInt, + Computed: true, + }, + "parent_srv_type": { + Type: schema.TypeString, + Computed: true, + }, + "rg_id": { + Type: schema.TypeInt, + Computed: true, + }, + "rg_name": { + Type: schema.TypeString, + Computed: true, + }, + "ssh_user": { + Type: schema.TypeString, + Computed: true, + }, + "status": { + Type: schema.TypeString, + Computed: true, + }, + "tech_status": { + Type: schema.TypeString, + Computed: true, + }, + "updated_by": { + Type: schema.TypeString, + Computed: true, + }, + "updated_time": { + Type: schema.TypeInt, + Computed: true, + }, + "user_managed": { + Type: schema.TypeBool, + Computed: true, + }, + }, + }, + }, + "entry_count": { + Type: schema.TypeInt, + Computed: true, + }, + } + return res +} + +func DataSourceBasicServiceList() *schema.Resource { + return &schema.Resource{ + SchemaVersion: 1, + + ReadContext: dataSourceBasicServiceListRead, + + Timeouts: &schema.ResourceTimeout{ + Read: &constants.Timeout30s, + Default: &constants.Timeout60s, + }, + + Schema: dataSourceBasicServiceListSchemaMake(), + } +} diff --git a/internal/service/cloudapi/bservice/data_source_bservice_snapshot_list.go b/internal/service/cloudapi/bservice/data_source_bservice_snapshot_list.go index 3d075b8..0df055f 100644 --- a/internal/service/cloudapi/bservice/data_source_bservice_snapshot_list.go +++ b/internal/service/cloudapi/bservice/data_source_bservice_snapshot_list.go @@ -1,105 +1,110 @@ -/* -Copyright (c) 2019-2022 Digital Energy Cloud Solutions LLC. All Rights Reserved. -Authors: -Petr Krutov, -Stanislav Solovev, -Kasim Baybikov, - -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 - -import ( - "context" - - "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" -) - -func dataSourceBasicServiceSnapshotListRead(ctx context.Context, d *schema.ResourceData, m interface{}) diag.Diagnostics { - basicServiceSnapshotList, err := utilityBasicServiceSnapshotListCheckPresence(ctx, d, m) - if err != nil { - return diag.FromErr(err) - } - - id := uuid.New() - d.SetId(id.String()) - d.Set("items", flattenBasicServiceSnapshotsList(basicServiceSnapshotList)) - d.Set("entry_count", basicServiceSnapshotList.EntryCount) - return nil -} - -func dataSourceBasicServiceSnapshotListSchemaMake() map[string]*schema.Schema { - res := map[string]*schema.Schema{ - "service_id": { - Type: schema.TypeInt, - Required: true, - Description: "ID of the BasicService instance", - }, - "items": { - Type: schema.TypeList, - Computed: true, - Elem: &schema.Resource{ - Schema: map[string]*schema.Schema{ - "guid": { - Type: schema.TypeString, - Computed: true, - }, - "label": { - Type: schema.TypeString, - Computed: true, - }, - "timestamp": { - Type: schema.TypeInt, - Computed: true, - }, - "valid": { - Type: schema.TypeBool, - Computed: true, - }, - }, - }, - }, - } - return res -} - -func DataSourceBasicServiceSnapshotList() *schema.Resource { - return &schema.Resource{ - SchemaVersion: 1, - - ReadContext: dataSourceBasicServiceSnapshotListRead, - - Timeouts: &schema.ResourceTimeout{ - Read: &constants.Timeout30s, - Default: &constants.Timeout60s, - }, - - Schema: dataSourceBasicServiceSnapshotListSchemaMake(), - } -} +/* +Copyright (c) 2019-2022 Digital Energy Cloud Solutions LLC. All Rights Reserved. +Authors: +Petr Krutov, +Stanislav Solovev, +Kasim Baybikov, + +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 + +import ( + "context" + + "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" +) + +func dataSourceBasicServiceSnapshotListRead(ctx context.Context, d *schema.ResourceData, m interface{}) diag.Diagnostics { + basicServiceSnapshotList, err := utilityBasicServiceSnapshotListCheckPresence(ctx, d, m) + if err != nil { + d.SetId("") + return diag.FromErr(err) + } + + id := uuid.New() + d.SetId(id.String()) + d.Set("items", flattenBasicServiceSnapshotsList(basicServiceSnapshotList)) + d.Set("entry_count", basicServiceSnapshotList.EntryCount) + return nil +} + +func dataSourceBasicServiceSnapshotListSchemaMake() map[string]*schema.Schema { + res := map[string]*schema.Schema{ + "service_id": { + Type: schema.TypeInt, + Required: true, + Description: "ID of the BasicService instance", + }, + "items": { + Type: schema.TypeList, + Computed: true, + Elem: &schema.Resource{ + Schema: map[string]*schema.Schema{ + "guid": { + Type: schema.TypeString, + Computed: true, + }, + "label": { + Type: schema.TypeString, + Computed: true, + }, + "timestamp": { + Type: schema.TypeInt, + Computed: true, + }, + "valid": { + Type: schema.TypeBool, + Computed: true, + }, + }, + }, + }, + "entry_count": { + Type: schema.TypeInt, + Computed: true, + }, + } + return res +} + +func DataSourceBasicServiceSnapshotList() *schema.Resource { + return &schema.Resource{ + SchemaVersion: 1, + + ReadContext: dataSourceBasicServiceSnapshotListRead, + + Timeouts: &schema.ResourceTimeout{ + Read: &constants.Timeout30s, + Default: &constants.Timeout60s, + }, + + Schema: dataSourceBasicServiceSnapshotListSchemaMake(), + } +} diff --git a/internal/service/cloudapi/bservice/resource_bservice.go b/internal/service/cloudapi/bservice/resource_bservice.go index 7930f2c..5e4b905 100644 --- a/internal/service/cloudapi/bservice/resource_bservice.go +++ b/internal/service/cloudapi/bservice/resource_bservice.go @@ -1,705 +1,721 @@ -/* -Copyright (c) 2019-2022 Digital Energy Cloud Solutions LLC. All Rights Reserved. -Authors: -Petr Krutov, -Stanislav Solovev, -Kasim Baybikov, - -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 - -import ( - "context" - "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" -) - -func resourceBasicServiceCreate(ctx context.Context, d *schema.ResourceData, m interface{}) diag.Diagnostics { - log.Debugf("resourceBasicServiceCreate") - c := m.(*controller.ControllerCfg) - req := bservice.CreateRequest{} - - haveRGID, err := existRGID(ctx, d, m) - if err != nil { - return diag.FromErr(err) - } - - if !haveRGID { - return diag.Errorf("resourceBasicServiceCreate: can't create basic service because RGID %d is not allowed or does not exist", 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 { - req.SSHKey = sshKey.(string) - } - if sshUser, ok := d.GetOk("ssh_user"); ok { - req.SSHUser = sshUser.(string) - } - - serviceId, err := c.CloudAPI().BService().Create(ctx, req) - if err != nil { - return diag.FromErr(err) - } - - d.SetId(strconv.FormatUint(serviceId, 10)) - d.Set("service_id", serviceId) - - service, err := utilityBasicServiceCheckPresence(ctx, d, m) - if err != nil { - d.SetId("") - return diag.FromErr(err) - } - - if d.Get("enable").(bool) && (service.Status == status.Disabled || service.Status == status.Created) { - log.Debugf("trying to enable bservice %v", serviceId) - _, err := c.CloudAPI().BService().Enable(ctx, bservice.EnableRequest{ - ServiceID: serviceId, - }) - - if err != nil { - return diag.FromErr(err) - } - } - if d.Get("start").(bool) && d.Get("enable").(bool) { - log.Debugf("trying to start bservice %v", serviceId) - _, err := c.CloudAPI().BService().Enable(ctx, bservice.EnableRequest{ - ServiceID: serviceId, - }) - - if err != nil { - return diag.FromErr(err) - } - } - - return resourceBasicServiceRead(ctx, d, m) -} - -func resourceBasicServiceRead(ctx context.Context, d *schema.ResourceData, m interface{}) diag.Diagnostics { - log.Debugf("resourceBasicServiceRead") - - // c := m.(*controller.ControllerCfg) - - bs, err := utilityBasicServiceCheckPresence(ctx, d, m) - if err != nil { - d.SetId("") - return diag.FromErr(err) - } - - hasChanged := false - - switch bs.Status { - case status.Modeled: - return diag.Errorf("The basic service is in status: %s, please, contact support for more information", bs.Status) - case status.Created: - case status.Enabled: - case status.Enabling: - case status.Disabled: - log.Debugf("The basic service is in status: %s, troubles can occur with the update. Please, enable bservice first.", bs.Status) - case status.Disabling: - log.Debugf("The basic service is in status: %s, troubles can occur with the update.", bs.Status) - case status.Deleted: - // id, _ := strconv.ParseUint(d.Id(), 10, 64) - // restoreReq := bservice.RestoreRequest{ - // ServiceID: id, - // } - // enableReq := bservice.EnableRequest{ - // ServiceID: id, - // } - - // _, 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) - // } - - // hasChanged = true - case status.Deleting: - case status.Destroyed: - d.SetId("") - return diag.Errorf("The resource cannot be updated because it has been destroyed") - // return resourceBasicServiceCreate(ctx, d, m) - case status.Destroying: - return diag.Errorf("The basic service is in progress with status: %s", bs.Status) - case status.Restoring: - case status.Reconfiguring: - } - - if hasChanged { - bs, err = utilityBasicServiceCheckPresence(ctx, d, m) - if err != nil { - d.SetId("") - return diag.FromErr(err) - } - } - - flattenService(d, bs) - - return nil -} - -func resourceBasicServiceDelete(ctx context.Context, d *schema.ResourceData, m interface{}) diag.Diagnostics { - log.Debugf("resourceBasicServiceDelete") - c := m.(*controller.ControllerCfg) - - _, 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("resourceBasicServiceUpdate") - c := m.(*controller.ControllerCfg) - - haveRGID, err := existRGID(ctx, d, m) - if err != nil { - return diag.FromErr(err) - } - - if !haveRGID { - return diag.Errorf("resourceBasicServiceUpdate: can't create basic service because RGID %d is not allowed or does not exist", d.Get("rg_id").(int)) - } - - bs, err := utilityBasicServiceCheckPresence(ctx, d, m) - if err != nil { - d.SetId("") - return diag.FromErr(err) - } - - hasChanged := false - - switch bs.Status { - case status.Modeled: - return diag.Errorf("The basic service is in status: %s, please, contact support for more information", bs.Status) - case status.Created: - case status.Enabled: - case status.Enabling: - case status.Disabled: - log.Debugf("The basic service is in status: %s, troubles can occur with the update. Please, enable bservice first.", bs.Status) - case status.Disabling: - log.Debugf("The basic service is in status: %s, troubles can occur with the update.", bs.Status) - case status.Deleted: - id, _ := strconv.ParseUint(d.Id(), 10, 64) - restoreReq := bservice.RestoreRequest{ - ServiceID: id, - } - enableReq := bservice.EnableRequest{ - ServiceID: id, - } - - _, 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) - } - - hasChanged = true - case status.Deleting: - case status.Destroyed: - d.SetId("") - return diag.Errorf("The resource cannot be updated because it has been destroyed") - // return resourceBasicServiceCreate(ctx, d, m) - case status.Destroying: - return diag.Errorf("The basic service is in progress with status: %s", bs.Status) - case status.Restoring: - case status.Reconfiguring: - } - - if hasChanged { - bs, err = utilityBasicServiceCheckPresence(ctx, d, m) - if err != nil { - d.SetId("") - return diag.FromErr(err) - } - } - - if d.HasChange("enable") { - enable := d.Get("enable").(bool) - if enable { - req := bservice.EnableRequest{ - ServiceID: uint64(d.Get("service_id").(int)), - } - - _, 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)), - } - - _, 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 { - req := bservice.RestoreRequest{ - ServiceID: uint64(d.Get("service_id").(int)), - } - _, err := c.CloudAPI().BService().Restore(ctx, req) - if err != nil { - return diag.FromErr(err) - } - } - } - - if d.HasChange("start") { - start := d.Get("start").(bool) - if start { - req := bservice.StartRequest{ - ServiceID: uint64(d.Get("service_id").(int)), - } - - _, 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)), - } - - _, err := c.CloudAPI().BService().Stop(ctx, req) - if err != nil { - return diag.FromErr(err) - } - } - } - - if d.HasChange("snapshots") { - deletedSnapshots := make([]interface{}, 0) - addedSnapshots := make([]interface{}, 0) - updatedSnapshots := make([]interface{}, 0) - - old, new := d.GetChange("snapshots") - oldConv := old.([]interface{}) - newConv := new.([]interface{}) - for _, el := range oldConv { - if !isContainsSnapshot(newConv, el) { - deletedSnapshots = append(deletedSnapshots, el) - } - } - for _, el := range newConv { - if !isContainsSnapshot(oldConv, el) { - addedSnapshots = append(addedSnapshots, el) - } else { - if isRollback(oldConv, el) { - updatedSnapshots = append(updatedSnapshots, el) - } - } - } - - if len(deletedSnapshots) > 0 { - for _, snapshot := range deletedSnapshots { - snapshotConv := snapshot.(map[string]interface{}) - 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) - } - } - } - - if len(addedSnapshots) > 0 { - for _, snapshot := range addedSnapshots { - snapshotConv := snapshot.(map[string]interface{}) - 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) - } - } - } - - if len(updatedSnapshots) > 0 { - for _, snapshot := range updatedSnapshots { - snapshotConv := snapshot.(map[string]interface{}) - 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) - } - } - } - - } - - return nil -} - -func isContainsSnapshot(els []interface{}, el interface{}) bool { - for _, elOld := range els { - elOldConv := elOld.(map[string]interface{}) - elConv := el.(map[string]interface{}) - if elOldConv["guid"].(string) == elConv["guid"].(string) { - return true - } - } - return false -} - -func isRollback(els []interface{}, el interface{}) bool { - for _, elOld := range els { - elOldConv := elOld.(map[string]interface{}) - elConv := el.(map[string]interface{}) - if elOldConv["guid"].(string) == elConv["guid"].(string) && - elOldConv["rollback"].(bool) != elConv["rollback"].(bool) && - elConv["rollback"].(bool) { - return true - } - } - return false -} - -func resourceBasicServiceSchemaMake() map[string]*schema.Schema { - return map[string]*schema.Schema{ - "service_name": { - Type: schema.TypeString, - Required: true, - Description: "Name of the service", - }, - "rg_id": { - Type: schema.TypeInt, - Required: true, - Description: "ID of the Resource Group where this service will be placed", - }, - "ssh_key": { - Type: schema.TypeString, - Optional: true, - Computed: true, - Description: "SSH key to deploy for the specified user. Same key will be deployed to all computes of the service.", - }, - "ssh_user": { - Type: schema.TypeString, - Optional: true, - Computed: true, - Description: "name of the user to deploy SSH key for. Pass empty string if no SSH key deployment is required", - }, - "permanently": { - Type: schema.TypeBool, - Optional: true, - Default: false, - Description: "if set to False, Basic service will be deleted to recycle bin. Otherwise destroyed immediately", - }, - "enable": { - Type: schema.TypeBool, - Optional: true, - Default: false, - Description: "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, - Optional: true, - Default: false, - Description: "Restores BasicService instance", - }, - "start": { - Type: schema.TypeBool, - Optional: true, - Default: false, - Description: "Start service. Starting a service technically means starting computes from all service groups according to group relations", - }, - "service_id": { - Type: schema.TypeInt, - Optional: true, - Computed: true, - }, - "account_id": { - Type: schema.TypeInt, - Computed: true, - }, - "account_name": { - Type: schema.TypeString, - Computed: true, - }, - "base_domain": { - Type: schema.TypeString, - Computed: true, - }, - "computes": { - Type: schema.TypeList, - Computed: true, - Elem: &schema.Resource{ - Schema: map[string]*schema.Schema{ - "account_id": { - Type: schema.TypeInt, - Computed: true, - }, - "architecture": { - Type: schema.TypeString, - Computed: true, - }, - "compgroup_id": { - Type: schema.TypeInt, - Computed: true, - }, - "compgroup_name": { - Type: schema.TypeString, - Computed: true, - }, - "compgroup_role": { - Type: schema.TypeString, - Computed: true, - }, - "id": { - Type: schema.TypeInt, - Computed: true, - }, - "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, - }, - "created_by": { - Type: schema.TypeString, - Computed: true, - }, - "created_time": { - Type: schema.TypeInt, - Computed: true, - }, - "deleted_by": { - Type: schema.TypeString, - Computed: true, - }, - "deleted_time": { - Type: schema.TypeInt, - Computed: true, - }, - "disk_total": { - Type: schema.TypeInt, - Computed: true, - }, - "gid": { - Type: schema.TypeInt, - Computed: true, - }, - "groups": { - Type: schema.TypeList, - Computed: true, - 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": { - Type: schema.TypeInt, - Computed: true, - }, - "milestones": { - Type: schema.TypeInt, - Computed: true, - }, - "parent_srv_id": { - Type: schema.TypeInt, - Computed: true, - }, - "parent_srv_type": { - Type: schema.TypeString, - Computed: true, - }, - "ram_total": { - Type: schema.TypeInt, - Computed: true, - }, - "rg_name": { - Type: schema.TypeString, - Computed: true, - }, - "snapshots": { - Type: schema.TypeList, - Computed: true, - Optional: true, - Elem: &schema.Resource{ - Schema: map[string]*schema.Schema{ - "guid": { - Type: schema.TypeString, - Computed: true, - }, - "label": { - Type: schema.TypeString, - Optional: true, - Computed: true, - }, - "rollback": { - Type: schema.TypeBool, - Optional: true, - Default: false, - }, - "timestamp": { - Type: schema.TypeInt, - Computed: true, - }, - "valid": { - Type: schema.TypeBool, - Computed: true, - }, - }, - }, - }, - "status": { - Type: schema.TypeString, - Computed: true, - }, - "tech_status": { - Type: schema.TypeString, - Computed: true, - }, - "updated_by": { - Type: schema.TypeString, - Computed: true, - }, - "updated_time": { - Type: schema.TypeInt, - Computed: true, - }, - "user_managed": { - Type: schema.TypeBool, - Computed: true, - }, - } -} - -func ResourceBasicService() *schema.Resource { - return &schema.Resource{ - SchemaVersion: 1, - - CreateContext: resourceBasicServiceCreate, - ReadContext: resourceBasicServiceRead, - UpdateContext: resourceBasicServiceUpdate, - DeleteContext: resourceBasicServiceDelete, - - Importer: &schema.ResourceImporter{ - StateContext: schema.ImportStatePassthroughContext, - }, - - Timeouts: &schema.ResourceTimeout{ - Create: &constants.Timeout600s, - Read: &constants.Timeout300s, - Update: &constants.Timeout300s, - Delete: &constants.Timeout300s, - Default: &constants.Timeout300s, - }, - - Schema: resourceBasicServiceSchemaMake(), - } -} +/* +Copyright (c) 2019-2022 Digital Energy Cloud Solutions LLC. All Rights Reserved. +Authors: +Petr Krutov, +Stanislav Solovev, +Kasim Baybikov, + +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 + +import ( + "context" + "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" +) + +func resourceBasicServiceCreate(ctx context.Context, d *schema.ResourceData, m interface{}) diag.Diagnostics { + log.Debugf("resourceBasicServiceCreate") + c := m.(*controller.ControllerCfg) + req := bservice.CreateRequest{} + + haveRGID, err := existRGID(ctx, d, m) + if err != nil { + return diag.FromErr(err) + } + + if !haveRGID { + return diag.Errorf("resourceBasicServiceCreate: can't create basic service because RGID %d is not allowed or does not exist", 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 { + req.SSHKey = sshKey.(string) + } + if sshUser, ok := d.GetOk("ssh_user"); ok { + req.SSHUser = sshUser.(string) + } + + serviceId, err := c.CloudAPI().BService().Create(ctx, req) + if err != nil { + return diag.FromErr(err) + } + + d.SetId(strconv.FormatUint(serviceId, 10)) + d.Set("service_id", serviceId) + + service, err := utilityBasicServiceCheckPresence(ctx, d, m) + if err != nil { + d.SetId("") + return diag.FromErr(err) + } + + if d.Get("enable").(bool) && (service.Status == status.Disabled || service.Status == status.Created) { + log.Debugf("trying to enable bservice %v", serviceId) + _, err := c.CloudAPI().BService().Enable(ctx, bservice.EnableRequest{ + ServiceID: serviceId, + }) + + if err != nil { + return diag.FromErr(err) + } + } + if d.Get("start").(bool) && d.Get("enable").(bool) { + log.Debugf("trying to enable bservice %v", serviceId) + _, err := c.CloudAPI().BService().Enable(ctx, bservice.EnableRequest{ + ServiceID: serviceId, + }) + + if err != nil { + return diag.FromErr(err) + } + + log.Debugf("trying to start bservice %v", serviceId) + _, err = c.CloudAPI().BService().Start(ctx, bservice.StartRequest{ + ServiceID: serviceId, + }) + + if err != nil { + return diag.FromErr(err) + } + } + + return resourceBasicServiceRead(ctx, d, m) +} + +func resourceBasicServiceRead(ctx context.Context, d *schema.ResourceData, m interface{}) diag.Diagnostics { + log.Debugf("resourceBasicServiceRead") + + // c := m.(*controller.ControllerCfg) + + bs, err := utilityBasicServiceCheckPresence(ctx, d, m) + if err != nil { + d.SetId("") + return diag.FromErr(err) + } + + hasChanged := false + + switch bs.Status { + case status.Modeled: + return diag.Errorf("The basic service is in status: %s, please, contact support for more information", bs.Status) + case status.Created: + case status.Enabled: + case status.Enabling: + case status.Disabled: + log.Debugf("The basic service is in status: %s, troubles can occur with the update. Please, enable bservice first.", bs.Status) + case status.Disabling: + log.Debugf("The basic service is in status: %s, troubles can occur with the update.", bs.Status) + case status.Deleted: + // id, _ := strconv.ParseUint(d.Id(), 10, 64) + // restoreReq := bservice.RestoreRequest{ + // ServiceID: id, + // } + // enableReq := bservice.EnableRequest{ + // ServiceID: id, + // } + + // _, 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) + // } + + // hasChanged = true + case status.Deleting: + case status.Destroyed: + d.SetId("") + return diag.Errorf("The resource cannot be updated because it has been destroyed") + // return resourceBasicServiceCreate(ctx, d, m) + case status.Destroying: + return diag.Errorf("The basic service is in progress with status: %s", bs.Status) + case status.Restoring: + case status.Reconfiguring: + } + + if hasChanged { + bs, err = utilityBasicServiceCheckPresence(ctx, d, m) + if err != nil { + d.SetId("") + return diag.FromErr(err) + } + } + + flattenService(d, bs) + + return nil +} + +func resourceBasicServiceDelete(ctx context.Context, d *schema.ResourceData, m interface{}) diag.Diagnostics { + log.Debugf("resourceBasicServiceDelete") + c := m.(*controller.ControllerCfg) + + _, 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("resourceBasicServiceUpdate") + c := m.(*controller.ControllerCfg) + + haveRGID, err := existRGID(ctx, d, m) + if err != nil { + return diag.FromErr(err) + } + + if !haveRGID { + return diag.Errorf("resourceBasicServiceUpdate: can't create basic service because RGID %d is not allowed or does not exist", d.Get("rg_id").(int)) + } + + bs, err := utilityBasicServiceCheckPresence(ctx, d, m) + if err != nil { + d.SetId("") + return diag.FromErr(err) + } + + hasChanged := false + + switch bs.Status { + case status.Modeled: + return diag.Errorf("The basic service is in status: %s, please, contact support for more information", bs.Status) + case status.Created: + case status.Enabled: + case status.Enabling: + case status.Disabled: + log.Debugf("The basic service is in status: %s, troubles can occur with the update. Please, enable bservice first.", bs.Status) + case status.Disabling: + log.Debugf("The basic service is in status: %s, troubles can occur with the update.", bs.Status) + case status.Deleted: + id, _ := strconv.ParseUint(d.Id(), 10, 64) + + if restore, ok := d.GetOk("restore"); ok { + if restore.(bool) { + restoreReq := bservice.RestoreRequest{ + ServiceID: id, + } + _, err := c.CloudAPI().BService().Restore(ctx, restoreReq) + if err != nil { + return diag.FromErr(err) + } + } + hasChanged = true + } + + if enable, ok := d.GetOk("enable"); ok { + if enable.(bool) { + enableReq := bservice.EnableRequest{ + ServiceID: id, + } + _, err = c.CloudAPI().BService().Enable(ctx, enableReq) + if err != nil { + return diag.FromErr(err) + } + hasChanged = true + } + } + + if start, ok := d.GetOk("start"); ok { + if start.(bool) { + startReq := bservice.StartRequest{ + ServiceID: id, + } + _, err = c.CloudAPI().BService().Start(ctx, startReq) + if err != nil { + return diag.FromErr(err) + } + hasChanged = true + } + } + case status.Deleting: + case status.Destroyed: + d.SetId("") + return diag.Errorf("The resource cannot be updated because it has been destroyed") + // return resourceBasicServiceCreate(ctx, d, m) + case status.Destroying: + return diag.Errorf("The basic service is in progress with status: %s", bs.Status) + case status.Restoring: + case status.Reconfiguring: + } + + if hasChanged { + bs, err = utilityBasicServiceCheckPresence(ctx, d, m) + if err != nil { + d.SetId("") + return diag.FromErr(err) + } + } + + if d.HasChange("enable") { + enable := d.Get("enable").(bool) + if enable { + req := bservice.EnableRequest{ + ServiceID: uint64(d.Get("service_id").(int)), + } + + _, 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)), + } + + _, err := c.CloudAPI().BService().Disable(ctx, req) + if err != nil { + return diag.FromErr(err) + } + } + } + + if d.HasChange("start") { + start := d.Get("start").(bool) + if start { + req := bservice.StartRequest{ + ServiceID: uint64(d.Get("service_id").(int)), + } + + _, 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)), + } + + _, err := c.CloudAPI().BService().Stop(ctx, req) + if err != nil { + return diag.FromErr(err) + } + } + } + + if d.HasChange("snapshots") { + deletedSnapshots := make([]interface{}, 0) + addedSnapshots := make([]interface{}, 0) + updatedSnapshots := make([]interface{}, 0) + + old, new := d.GetChange("snapshots") + oldConv := old.([]interface{}) + newConv := new.([]interface{}) + for _, el := range oldConv { + if !isContainsSnapshot(newConv, el) { + deletedSnapshots = append(deletedSnapshots, el) + } + } + for _, el := range newConv { + if !isContainsSnapshot(oldConv, el) { + addedSnapshots = append(addedSnapshots, el) + } else { + if isRollback(oldConv, el) { + updatedSnapshots = append(updatedSnapshots, el) + } + } + } + + if len(deletedSnapshots) > 0 { + for _, snapshot := range deletedSnapshots { + snapshotConv := snapshot.(map[string]interface{}) + 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) + } + } + } + + if len(addedSnapshots) > 0 { + for _, snapshot := range addedSnapshots { + snapshotConv := snapshot.(map[string]interface{}) + 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) + } + } + } + + if len(updatedSnapshots) > 0 { + for _, snapshot := range updatedSnapshots { + snapshotConv := snapshot.(map[string]interface{}) + 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) + } + } + } + } + + return resourceBasicServiceRead(ctx, d, m) +} + +func isContainsSnapshot(els []interface{}, el interface{}) bool { + for _, elOld := range els { + elOldConv := elOld.(map[string]interface{}) + elConv := el.(map[string]interface{}) + if elOldConv["guid"].(string) == elConv["guid"].(string) { + return true + } + } + return false +} + +func isRollback(els []interface{}, el interface{}) bool { + for _, elOld := range els { + elOldConv := elOld.(map[string]interface{}) + elConv := el.(map[string]interface{}) + if elOldConv["guid"].(string) == elConv["guid"].(string) && + elOldConv["rollback"].(bool) != elConv["rollback"].(bool) && + elConv["rollback"].(bool) { + return true + } + } + return false +} + +func resourceBasicServiceSchemaMake() map[string]*schema.Schema { + return map[string]*schema.Schema{ + "service_name": { + Type: schema.TypeString, + Required: true, + Description: "Name of the service", + }, + "rg_id": { + Type: schema.TypeInt, + Required: true, + Description: "ID of the Resource Group where this service will be placed", + }, + "ssh_key": { + Type: schema.TypeString, + Optional: true, + Computed: true, + Description: "SSH key to deploy for the specified user. Same key will be deployed to all computes of the service.", + }, + "ssh_user": { + Type: schema.TypeString, + Optional: true, + Computed: true, + Description: "name of the user to deploy SSH key for. Pass empty string if no SSH key deployment is required", + }, + "permanently": { + Type: schema.TypeBool, + Optional: true, + Default: false, + Description: "if set to False, Basic service will be deleted to recycle bin. Otherwise destroyed immediately", + }, + "enable": { + Type: schema.TypeBool, + Optional: true, + Default: false, + Description: "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, + Optional: true, + Default: false, + Description: "Restores BasicService instance", + }, + "start": { + Type: schema.TypeBool, + Optional: true, + Default: false, + Description: "Start service. Starting a service technically means starting computes from all service groups according to group relations", + }, + "service_id": { + Type: schema.TypeInt, + Optional: true, + Computed: true, + }, + "account_id": { + Type: schema.TypeInt, + Computed: true, + }, + "account_name": { + Type: schema.TypeString, + Computed: true, + }, + "base_domain": { + Type: schema.TypeString, + Computed: true, + }, + "computes": { + Type: schema.TypeList, + Computed: true, + Elem: &schema.Resource{ + Schema: map[string]*schema.Schema{ + "account_id": { + Type: schema.TypeInt, + Computed: true, + }, + "architecture": { + Type: schema.TypeString, + Computed: true, + }, + "compgroup_id": { + Type: schema.TypeInt, + Computed: true, + }, + "compgroup_name": { + Type: schema.TypeString, + Computed: true, + }, + "compgroup_role": { + Type: schema.TypeString, + Computed: true, + }, + "id": { + Type: schema.TypeInt, + Computed: true, + }, + "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, + }, + "created_by": { + Type: schema.TypeString, + Computed: true, + }, + "created_time": { + Type: schema.TypeInt, + Computed: true, + }, + "deleted_by": { + Type: schema.TypeString, + Computed: true, + }, + "deleted_time": { + Type: schema.TypeInt, + Computed: true, + }, + "disk_total": { + Type: schema.TypeInt, + Computed: true, + }, + "gid": { + Type: schema.TypeInt, + Computed: true, + }, + "groups": { + Type: schema.TypeList, + Computed: true, + 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": { + Type: schema.TypeInt, + Computed: true, + }, + "milestones": { + Type: schema.TypeInt, + Computed: true, + }, + "parent_srv_id": { + Type: schema.TypeInt, + Computed: true, + }, + "parent_srv_type": { + Type: schema.TypeString, + Computed: true, + }, + "ram_total": { + Type: schema.TypeInt, + Computed: true, + }, + "rg_name": { + Type: schema.TypeString, + Computed: true, + }, + "snapshots": { + Type: schema.TypeList, + Computed: true, + Optional: true, + Elem: &schema.Resource{ + Schema: map[string]*schema.Schema{ + "guid": { + Type: schema.TypeString, + Computed: true, + }, + "label": { + Type: schema.TypeString, + Optional: true, + Computed: true, + }, + "rollback": { + Type: schema.TypeBool, + Optional: true, + Default: false, + }, + "timestamp": { + Type: schema.TypeInt, + Computed: true, + }, + "valid": { + Type: schema.TypeBool, + Computed: true, + }, + }, + }, + }, + "status": { + Type: schema.TypeString, + Computed: true, + }, + "tech_status": { + Type: schema.TypeString, + Computed: true, + }, + "updated_by": { + Type: schema.TypeString, + Computed: true, + }, + "updated_time": { + Type: schema.TypeInt, + Computed: true, + }, + "user_managed": { + Type: schema.TypeBool, + Computed: true, + }, + } +} + +func ResourceBasicService() *schema.Resource { + return &schema.Resource{ + SchemaVersion: 1, + + CreateContext: resourceBasicServiceCreate, + ReadContext: resourceBasicServiceRead, + UpdateContext: resourceBasicServiceUpdate, + DeleteContext: resourceBasicServiceDelete, + + Importer: &schema.ResourceImporter{ + StateContext: schema.ImportStatePassthroughContext, + }, + + Timeouts: &schema.ResourceTimeout{ + Create: &constants.Timeout600s, + Read: &constants.Timeout300s, + Update: &constants.Timeout300s, + Delete: &constants.Timeout300s, + Default: &constants.Timeout300s, + }, + + Schema: resourceBasicServiceSchemaMake(), + } +} diff --git a/internal/service/cloudapi/bservice/resource_bservice_group.go b/internal/service/cloudapi/bservice/resource_bservice_group.go index 117ed4d..b6e0b18 100644 --- a/internal/service/cloudapi/bservice/resource_bservice_group.go +++ b/internal/service/cloudapi/bservice/resource_bservice_group.go @@ -1,620 +1,621 @@ -/* -Copyright (c) 2019-2022 Digital Energy Cloud Solutions LLC. All Rights Reserved. -Authors: -Petr Krutov, -Stanislav Solovev, -Kasim Baybikov, - -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 - -import ( - "context" - "strconv" - - "github.com/hashicorp/terraform-plugin-sdk/v2/diag" - "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" - "github.com/hashicorp/terraform-plugin-sdk/v2/helper/validation" - 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" -) - -func resourceBasicServiceGroupCreate(ctx context.Context, d *schema.ResourceData, m interface{}) diag.Diagnostics { - log.Debugf("resourceBasicServiceGroupCreate") - - c := m.(*controller.ControllerCfg) - 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 { - req.Role = role.(string) - } - - if timeoutStart, ok := d.GetOk("timeout_start"); ok { - req.TimeoutStart = uint64(timeoutStart.(int)) - } - - ///4.4.0 - if sepId, ok := d.GetOk("sep_id"); ok { - req.SEPID = uint64(sepId.(int)) - } - - if sepPool, ok := d.GetOk("sep_pool"); ok { - req.SEPPool = sepPool.(string) - } - - if cloudInit, ok := d.GetOk("cloud_init"); ok { - req.UserData = cloudInit.(string) - } - /// - - if vinses, ok := d.GetOk("vinses"); ok { - res := []uint64{} - for _, vins := range vinses.([]interface{}) { - res = append(res, uint64(vins.(int))) - } - - req.VINSes = res - } - if extnets, ok := d.GetOk("extnets"); ok { - res := []uint64{} - for _, enet := range extnets.([]interface{}) { - res = append(res, uint64(enet.(int))) - } - - req.ExtNets = res - } - - compgroupId, err := c.CloudAPI().BService().GroupAdd(ctx, req) - if err != nil { - return diag.FromErr(err) - } - - d.SetId(strconv.FormatUint(compgroupId, 10)) - d.Set("compgroup_id", compgroupId) - - serviceId:= uint64(d.Get("service_id").(int)) - - if d.Get("start").(bool) { - log.Debugf("trying to start bservice group %v", compgroupId) - _, err := c.CloudAPI().BService().GroupStart(ctx, bservice.GroupStartRequest{ - ServiceID: serviceId, - CompGroupID: compgroupId, - }) - - if err != nil { - return diag.FromErr(err) - } - } - - 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 err != nil { - d.SetId("") - return diag.FromErr(err) - } - - flattenResourceBasicServiceGroup(d, bsg) - - return nil -} - -func resourceBasicServiceGroupDelete(ctx context.Context, d *schema.ResourceData, m interface{}) diag.Diagnostics { - log.Debugf("resourceBasicServiceGroupDelete") - - bsg, err := utilityBasicServiceGroupCheckPresence(ctx, d, m) - if err != nil { - return diag.FromErr(err) - } - - c := m.(*controller.ControllerCfg) - req := bservice.GroupRemoveRequest{ - ServiceID: bsg.ServiceID, - CompGroupID: bsg.ID, - } - - _, err = c.CloudAPI().BService().GroupRemove(ctx, req) - if err != nil { - return diag.FromErr(err) - } - d.SetId("") - - return nil -} - -func resourceBasicServiceGroupUpdate(ctx context.Context, d *schema.ResourceData, m interface{}) diag.Diagnostics { - log.Debugf("resourceBasicServiceGroupEdit") - c := m.(*controller.ControllerCfg) - - if d.HasChange("comp_count") { - 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) - } - } - - if d.HasChange("start") { - start := d.Get("start").(bool) - if start { - 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 { - 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.CloudAPI().BService().GroupStop(ctx, req) - if err != nil { - return diag.FromErr(err) - } - } - } - - if d.HasChanges("compgroup_name", "ram", "cpu", "disk", "role") { - 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), - } - - _, err := c.CloudAPI().BService().GroupUpdate(ctx, req) - if err != nil { - return diag.FromErr(err) - } - } - - if d.HasChange("extnets") { - extnets := d.Get("extnets").([]interface{}) - - 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) - } - } - - if d.HasChange("vinses") { - vinses := d.Get("vinses").([]interface{}) - - 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) - } - } - - if d.HasChange("parents") { - deletedParents := make([]interface{}, 0) - addedParents := make([]interface{}, 0) - - old, new := d.GetChange("parents") - oldConv := old.([]interface{}) - newConv := new.([]interface{}) - for _, el := range oldConv { - if !isContainsParent(newConv, el) { - deletedParents = append(deletedParents, el) - } - } - for _, el := range newConv { - if !isContainsParent(oldConv, el) { - addedParents = append(addedParents, el) - } - } - - if len(deletedParents) > 0 { - for _, parent := range deletedParents { - parentConv := parent.(int) - - req := bservice.GroupParentRemoveRequest{ - ServiceID: uint64(d.Get("service_id").(int)), - CompGroupID: uint64(d.Get("compgroup_id").(int)), - ParentID: uint64(parentConv), - } - - _, err := c.CloudAPI().BService().GroupParentRemove(ctx, req) - if err != nil { - return diag.FromErr(err) - } - } - } - - if len(addedParents) > 0 { - for _, parent := range addedParents { - parentConv := parent.(int) - - 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) - } - } - } - } - - if d.HasChange("remove_computes") { - rcs := d.Get("remove_computes").([]interface{}) - if len(rcs) > 0 { - for _, rc := range rcs { - req := bservice.GroupComputeRemoveRequest{ - ServiceID: uint64(d.Get("service_id").(int)), - CompGroupID: uint64(d.Get("compgroup_id").(int)), - ComputeID: uint64(rc.(int)), - } - - _, err := c.CloudAPI().BService().GroupComputeRemove(ctx, req) - if err != nil { - return diag.FromErr(err) - } - } - } - } - - return nil -} - -func isContainsParent(els []interface{}, el interface{}) bool { - for _, elOld := range els { - elOldConv := elOld.(int) - elConv := el.(int) - if elOldConv == elConv { - return true - } - } - return false -} - -func resourceBasicServiceGroupSchemaMake() map[string]*schema.Schema { - return map[string]*schema.Schema{ - "service_id": { - Type: schema.TypeInt, - Required: true, - Description: "ID of the Basic Service to add a group to", - }, - "compgroup_name": { - Type: schema.TypeString, - Required: true, - Description: "name of the Compute Group to add", - }, - "comp_count": { - Type: schema.TypeInt, - Required: true, - Description: "computes number. Defines how many computes must be there in the group", - }, - "cpu": { - Type: schema.TypeInt, - Required: true, - Description: "compute CPU number. All computes in the group have the same CPU count", - }, - "ram": { - Type: schema.TypeInt, - Required: true, - Description: "compute RAM volume in MB. All computes in the group have the same RAM volume", - }, - "disk": { - Type: schema.TypeInt, - Required: true, - Description: "compute boot disk size in GB", - }, - "image_id": { - Type: schema.TypeInt, - Required: true, - Description: "OS image ID to create computes from", - }, - "driver": { - Type: schema.TypeString, - Required: true, - Description: "compute driver like a KVM_X86, KVM_PPC, etc.", - }, - ///4.4.0 - "sep_id": { - Type: schema.TypeInt, - Optional: true, - Computed: true, - Description: "storage endpoint provider ID", - }, - "sep_pool": { - Type: schema.TypeString, - Optional: true, - Computed: true, - Description: "pool to use if sepId is set, can be also empty if needed to be chosen by system", - }, - "cloud_init": { - Type: schema.TypeString, - Optional: true, - Description: "Optional cloud_init parameters. Applied when creating new compute instance only, ignored in all other cases.", - }, - /// - "role": { - Type: schema.TypeString, - Optional: true, - Computed: true, - Description: "group role tag. Can be empty string, does not have to be unique", - }, - "timeout_start": { - Type: schema.TypeInt, - Optional: true, - Computed: true, - Description: "time of Compute Group readiness", - }, - "extnets": { - Type: schema.TypeList, - Optional: true, - Computed: true, - Elem: &schema.Schema{ - Type: schema.TypeInt, - }, - Description: "list of external networks to connect computes to", - }, - "vinses": { - Type: schema.TypeList, - Optional: true, - Computed: true, - Elem: &schema.Schema{ - Type: schema.TypeInt, - }, - Description: "list of ViNSes to connect computes to", - }, - "mode": { - Type: schema.TypeString, - Optional: true, - Default: "RELATIVE", - ValidateFunc: validation.StringInSlice([]string{"RELATIVE", "ABSOLUTE"}, false), - Description: "(RELATIVE;ABSOLUTE) either delta or absolute value of computes", - }, - "start": { - Type: schema.TypeBool, - Optional: true, - Default: false, - Description: "Start the specified Compute Group within BasicService", - }, - "force_stop": { - Type: schema.TypeBool, - Optional: true, - Default: false, - Description: "force stop Compute Group", - }, - "force_update": { - Type: schema.TypeBool, - Optional: true, - Default: false, - Description: "force resize Compute Group", - }, - "parents": { - Type: schema.TypeList, - Optional: true, - Computed: true, - Elem: &schema.Schema{ - Type: schema.TypeInt, - }, - }, - "remove_computes": { - Type: schema.TypeList, - Optional: true, - Elem: &schema.Schema{ - Type: schema.TypeInt, - }, - }, - "compgroup_id": { - Type: schema.TypeInt, - Optional: true, - Computed: true, - }, - "account_id": { - Type: schema.TypeInt, - Computed: true, - }, - "account_name": { - Type: schema.TypeString, - Computed: true, - }, - "computes": { - Type: schema.TypeList, - Computed: true, - Elem: &schema.Resource{ - Schema: map[string]*schema.Schema{ - "id": { - Type: schema.TypeInt, - Computed: true, - }, - "ip_addresses": { - Type: schema.TypeList, - Computed: true, - Elem: &schema.Schema{ - Type: schema.TypeString, - }, - }, - "name": { - Type: schema.TypeString, - Computed: true, - }, - "os_users": { - Type: schema.TypeList, - Computed: true, - Elem: &schema.Resource{ - Schema: map[string]*schema.Schema{ - "login": { - Type: schema.TypeString, - Computed: true, - }, - "password": { - Type: schema.TypeString, - Computed: true, - }, - }, - }, - }, - }, - }, - }, - "consistency": { - Type: schema.TypeBool, - Computed: true, - }, - "created_by": { - Type: schema.TypeString, - Computed: true, - }, - "created_time": { - Type: schema.TypeInt, - Computed: true, - }, - "deleted_by": { - Type: schema.TypeString, - Computed: true, - }, - "deleted_time": { - Type: schema.TypeInt, - Computed: true, - }, - "gid": { - Type: schema.TypeInt, - Computed: true, - }, - "guid": { - Type: schema.TypeInt, - Computed: true, - }, - "milestones": { - Type: schema.TypeInt, - Computed: true, - }, - "rg_id": { - Type: schema.TypeInt, - Computed: true, - }, - "rg_name": { - Type: schema.TypeString, - Computed: true, - }, - "seq_no": { - Type: schema.TypeInt, - Computed: true, - }, - "status": { - Type: schema.TypeString, - Computed: true, - }, - "tech_status": { - Type: schema.TypeString, - Computed: true, - }, - "updated_by": { - Type: schema.TypeString, - Computed: true, - }, - "updated_time": { - Type: schema.TypeInt, - Computed: true, - }, - } -} - -func ResourceBasicServiceGroup() *schema.Resource { - return &schema.Resource{ - SchemaVersion: 1, - - CreateContext: resourceBasicServiceGroupCreate, - ReadContext: resourceBasicServiceGroupRead, - UpdateContext: resourceBasicServiceGroupUpdate, - DeleteContext: resourceBasicServiceGroupDelete, - - Importer: &schema.ResourceImporter{ - StateContext: schema.ImportStatePassthroughContext, - }, - - Timeouts: &schema.ResourceTimeout{ - Create: &constants.Timeout600s, - Read: &constants.Timeout300s, - Update: &constants.Timeout300s, - Delete: &constants.Timeout300s, - Default: &constants.Timeout300s, - }, - - Schema: resourceBasicServiceGroupSchemaMake(), - } -} +/* +Copyright (c) 2019-2022 Digital Energy Cloud Solutions LLC. All Rights Reserved. +Authors: +Petr Krutov, +Stanislav Solovev, +Kasim Baybikov, + +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 + +import ( + "context" + "strconv" + + "github.com/hashicorp/terraform-plugin-sdk/v2/diag" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/validation" + 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" +) + +func resourceBasicServiceGroupCreate(ctx context.Context, d *schema.ResourceData, m interface{}) diag.Diagnostics { + log.Debugf("resourceBasicServiceGroupCreate") + + c := m.(*controller.ControllerCfg) + 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 { + req.Role = role.(string) + } + + if timeoutStart, ok := d.GetOk("timeout_start"); ok { + req.TimeoutStart = uint64(timeoutStart.(int)) + } + + ///4.4.0 + if sepId, ok := d.GetOk("sep_id"); ok { + req.SEPID = uint64(sepId.(int)) + } + + if sepPool, ok := d.GetOk("sep_pool"); ok { + req.SEPPool = sepPool.(string) + } + + if cloudInit, ok := d.GetOk("cloud_init"); ok { + req.UserData = cloudInit.(string) + } + /// + + if vinses, ok := d.GetOk("vinses"); ok { + res := []uint64{} + for _, vins := range vinses.([]interface{}) { + res = append(res, uint64(vins.(int))) + } + + req.VINSes = res + } + if extnets, ok := d.GetOk("extnets"); ok { + res := []uint64{} + for _, enet := range extnets.([]interface{}) { + res = append(res, uint64(enet.(int))) + } + + req.ExtNets = res + } + + compgroupId, err := c.CloudAPI().BService().GroupAdd(ctx, req) + if err != nil { + return diag.FromErr(err) + } + + d.SetId(strconv.FormatUint(compgroupId, 10)) + d.Set("compgroup_id", compgroupId) + + serviceId := uint64(d.Get("service_id").(int)) + + if d.Get("start").(bool) { + log.Debugf("trying to start bservice group %v", compgroupId) + _, err := c.CloudAPI().BService().GroupStart(ctx, bservice.GroupStartRequest{ + ServiceID: serviceId, + CompGroupID: compgroupId, + }) + + if err != nil { + return diag.FromErr(err) + } + } + + 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 err != nil { + d.SetId("") + return diag.FromErr(err) + } + + flattenResourceBasicServiceGroup(d, bsg) + + return nil +} + +func resourceBasicServiceGroupDelete(ctx context.Context, d *schema.ResourceData, m interface{}) diag.Diagnostics { + log.Debugf("resourceBasicServiceGroupDelete") + + bsg, err := utilityBasicServiceGroupCheckPresence(ctx, d, m) + if err != nil { + d.SetId("") + return diag.FromErr(err) + } + + c := m.(*controller.ControllerCfg) + req := bservice.GroupRemoveRequest{ + ServiceID: bsg.ServiceID, + CompGroupID: bsg.ID, + } + + _, err = c.CloudAPI().BService().GroupRemove(ctx, req) + if err != nil { + return diag.FromErr(err) + } + d.SetId("") + + return nil +} + +func resourceBasicServiceGroupUpdate(ctx context.Context, d *schema.ResourceData, m interface{}) diag.Diagnostics { + log.Debugf("resourceBasicServiceGroupEdit") + c := m.(*controller.ControllerCfg) + + if d.HasChange("comp_count") { + 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) + } + } + + if d.HasChange("start") { + start := d.Get("start").(bool) + if start { + 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 { + 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.CloudAPI().BService().GroupStop(ctx, req) + if err != nil { + return diag.FromErr(err) + } + } + } + + if d.HasChanges("compgroup_name", "ram", "cpu", "disk", "role") { + 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), + } + + _, err := c.CloudAPI().BService().GroupUpdate(ctx, req) + if err != nil { + return diag.FromErr(err) + } + } + + if d.HasChange("extnets") { + extnets := d.Get("extnets").([]interface{}) + + 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) + } + } + + if d.HasChange("vinses") { + vinses := d.Get("vinses").([]interface{}) + + 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) + } + } + + if d.HasChange("parents") { + deletedParents := make([]interface{}, 0) + addedParents := make([]interface{}, 0) + + old, new := d.GetChange("parents") + oldConv := old.([]interface{}) + newConv := new.([]interface{}) + for _, el := range oldConv { + if !isContainsParent(newConv, el) { + deletedParents = append(deletedParents, el) + } + } + for _, el := range newConv { + if !isContainsParent(oldConv, el) { + addedParents = append(addedParents, el) + } + } + + if len(deletedParents) > 0 { + for _, parent := range deletedParents { + parentConv := parent.(int) + + req := bservice.GroupParentRemoveRequest{ + ServiceID: uint64(d.Get("service_id").(int)), + CompGroupID: uint64(d.Get("compgroup_id").(int)), + ParentID: uint64(parentConv), + } + + _, err := c.CloudAPI().BService().GroupParentRemove(ctx, req) + if err != nil { + return diag.FromErr(err) + } + } + } + + if len(addedParents) > 0 { + for _, parent := range addedParents { + parentConv := parent.(int) + + 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) + } + } + } + } + + if d.HasChange("remove_computes") { + rcs := d.Get("remove_computes").([]interface{}) + if len(rcs) > 0 { + for _, rc := range rcs { + req := bservice.GroupComputeRemoveRequest{ + ServiceID: uint64(d.Get("service_id").(int)), + CompGroupID: uint64(d.Get("compgroup_id").(int)), + ComputeID: uint64(rc.(int)), + } + + _, err := c.CloudAPI().BService().GroupComputeRemove(ctx, req) + if err != nil { + return diag.FromErr(err) + } + } + } + } + + return resourceBasicServiceGroupRead(ctx, d, m) +} + +func isContainsParent(els []interface{}, el interface{}) bool { + for _, elOld := range els { + elOldConv := elOld.(int) + elConv := el.(int) + if elOldConv == elConv { + return true + } + } + return false +} + +func resourceBasicServiceGroupSchemaMake() map[string]*schema.Schema { + return map[string]*schema.Schema{ + "service_id": { + Type: schema.TypeInt, + Required: true, + Description: "ID of the Basic Service to add a group to", + }, + "compgroup_name": { + Type: schema.TypeString, + Required: true, + Description: "name of the Compute Group to add", + }, + "comp_count": { + Type: schema.TypeInt, + Required: true, + Description: "computes number. Defines how many computes must be there in the group", + }, + "cpu": { + Type: schema.TypeInt, + Required: true, + Description: "compute CPU number. All computes in the group have the same CPU count", + }, + "ram": { + Type: schema.TypeInt, + Required: true, + Description: "compute RAM volume in MB. All computes in the group have the same RAM volume", + }, + "disk": { + Type: schema.TypeInt, + Required: true, + Description: "compute boot disk size in GB", + }, + "image_id": { + Type: schema.TypeInt, + Required: true, + Description: "OS image ID to create computes from", + }, + "driver": { + Type: schema.TypeString, + Required: true, + Description: "compute driver like a KVM_X86, KVM_PPC, etc.", + }, + ///4.4.0 + "sep_id": { + Type: schema.TypeInt, + Optional: true, + Computed: true, + Description: "storage endpoint provider ID", + }, + "sep_pool": { + Type: schema.TypeString, + Optional: true, + Computed: true, + Description: "pool to use if sepId is set, can be also empty if needed to be chosen by system", + }, + "cloud_init": { + Type: schema.TypeString, + Optional: true, + Description: "Optional cloud_init parameters. Applied when creating new compute instance only, ignored in all other cases.", + }, + /// + "role": { + Type: schema.TypeString, + Optional: true, + Computed: true, + Description: "group role tag. Can be empty string, does not have to be unique", + }, + "timeout_start": { + Type: schema.TypeInt, + Optional: true, + Computed: true, + Description: "time of Compute Group readiness", + }, + "extnets": { + Type: schema.TypeList, + Optional: true, + Computed: true, + Elem: &schema.Schema{ + Type: schema.TypeInt, + }, + Description: "list of external networks to connect computes to", + }, + "vinses": { + Type: schema.TypeList, + Optional: true, + Computed: true, + Elem: &schema.Schema{ + Type: schema.TypeInt, + }, + Description: "list of ViNSes to connect computes to", + }, + "mode": { + Type: schema.TypeString, + Optional: true, + Default: "RELATIVE", + ValidateFunc: validation.StringInSlice([]string{"RELATIVE", "ABSOLUTE"}, false), + Description: "(RELATIVE;ABSOLUTE) either delta or absolute value of computes", + }, + "start": { + Type: schema.TypeBool, + Optional: true, + Default: false, + Description: "Start the specified Compute Group within BasicService", + }, + "force_stop": { + Type: schema.TypeBool, + Optional: true, + Default: false, + Description: "force stop Compute Group", + }, + "force_update": { + Type: schema.TypeBool, + Optional: true, + Default: false, + Description: "force resize Compute Group", + }, + "parents": { + Type: schema.TypeList, + Optional: true, + Computed: true, + Elem: &schema.Schema{ + Type: schema.TypeInt, + }, + }, + "remove_computes": { + Type: schema.TypeList, + Optional: true, + Elem: &schema.Schema{ + Type: schema.TypeInt, + }, + }, + "compgroup_id": { + Type: schema.TypeInt, + Optional: true, + Computed: true, + }, + "account_id": { + Type: schema.TypeInt, + Computed: true, + }, + "account_name": { + Type: schema.TypeString, + Computed: true, + }, + "computes": { + Type: schema.TypeList, + Computed: true, + Elem: &schema.Resource{ + Schema: map[string]*schema.Schema{ + "id": { + Type: schema.TypeInt, + Computed: true, + }, + "ip_addresses": { + Type: schema.TypeList, + Computed: true, + Elem: &schema.Schema{ + Type: schema.TypeString, + }, + }, + "name": { + Type: schema.TypeString, + Computed: true, + }, + "os_users": { + Type: schema.TypeList, + Computed: true, + Elem: &schema.Resource{ + Schema: map[string]*schema.Schema{ + "login": { + Type: schema.TypeString, + Computed: true, + }, + "password": { + Type: schema.TypeString, + Computed: true, + }, + }, + }, + }, + }, + }, + }, + "consistency": { + Type: schema.TypeBool, + Computed: true, + }, + "created_by": { + Type: schema.TypeString, + Computed: true, + }, + "created_time": { + Type: schema.TypeInt, + Computed: true, + }, + "deleted_by": { + Type: schema.TypeString, + Computed: true, + }, + "deleted_time": { + Type: schema.TypeInt, + Computed: true, + }, + "gid": { + Type: schema.TypeInt, + Computed: true, + }, + "guid": { + Type: schema.TypeInt, + Computed: true, + }, + "milestones": { + Type: schema.TypeInt, + Computed: true, + }, + "rg_id": { + Type: schema.TypeInt, + Computed: true, + }, + "rg_name": { + Type: schema.TypeString, + Computed: true, + }, + "seq_no": { + Type: schema.TypeInt, + Computed: true, + }, + "status": { + Type: schema.TypeString, + Computed: true, + }, + "tech_status": { + Type: schema.TypeString, + Computed: true, + }, + "updated_by": { + Type: schema.TypeString, + Computed: true, + }, + "updated_time": { + Type: schema.TypeInt, + Computed: true, + }, + } +} + +func ResourceBasicServiceGroup() *schema.Resource { + return &schema.Resource{ + SchemaVersion: 1, + + CreateContext: resourceBasicServiceGroupCreate, + ReadContext: resourceBasicServiceGroupRead, + UpdateContext: resourceBasicServiceGroupUpdate, + DeleteContext: resourceBasicServiceGroupDelete, + + Importer: &schema.ResourceImporter{ + StateContext: schema.ImportStatePassthroughContext, + }, + + Timeouts: &schema.ResourceTimeout{ + Create: &constants.Timeout600s, + Read: &constants.Timeout300s, + Update: &constants.Timeout300s, + Delete: &constants.Timeout300s, + Default: &constants.Timeout300s, + }, + + Schema: resourceBasicServiceGroupSchemaMake(), + } +} diff --git a/internal/service/cloudapi/disks/data_source_disk.go b/internal/service/cloudapi/disks/data_source_disk.go index 780e4f2..369286e 100644 --- a/internal/service/cloudapi/disks/data_source_disk.go +++ b/internal/service/cloudapi/disks/data_source_disk.go @@ -47,6 +47,7 @@ import ( func dataSourceDiskRead(ctx context.Context, d *schema.ResourceData, m interface{}) diag.Diagnostics { disk, err := utilityDiskCheckPresence(ctx, d, m) if err != nil { + d.SetId("") return diag.FromErr(err) } diff --git a/internal/service/cloudapi/disks/data_source_disk_list.go b/internal/service/cloudapi/disks/data_source_disk_list.go index 36ba04d..c484b6c 100644 --- a/internal/service/cloudapi/disks/data_source_disk_list.go +++ b/internal/service/cloudapi/disks/data_source_disk_list.go @@ -1,499 +1,500 @@ -/* -Copyright (c) 2019-2022 Digital Energy Cloud Solutions LLC. All Rights Reserved. -Authors: -Petr Krutov, -Stanislav Solovev, -Kasim Baybikov, - -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 - -import ( - "context" - - "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" -) - -func dataSourceDiskListRead(ctx context.Context, d *schema.ResourceData, m interface{}) diag.Diagnostics { - diskList, err := utilityDiskListCheckPresence(ctx, d, m) - if err != nil { - return diag.FromErr(err) - } - - id := uuid.New() - d.SetId(id.String()) - d.Set("items", flattenDiskList(diskList)) - d.Set("entry_count", diskList.EntryCount) - - return nil -} - -func dataSourceDiskListSchemaMake() map[string]*schema.Schema { - res := map[string]*schema.Schema{ - "by_id": { - Type: schema.TypeInt, - Optional: true, - Description: "Find by ID", - }, - "name": { - Type: schema.TypeString, - Optional: true, - Description: "Find by name", - }, - "account_name": { - Type: schema.TypeString, - Optional: true, - Description: "Find by account name", - }, - "disk_max_size": { - Type: schema.TypeInt, - Optional: true, - Description: "Find by max disk size", - }, - "status": { - Type: schema.TypeString, - Optional: true, - Description: "Find by status", - }, - "shared": { - Type: schema.TypeBool, - Optional: true, - Description: "Find by shared field", - }, - "account_id": { - Type: schema.TypeInt, - Optional: true, - Description: "ID of the account the disks belong to", - }, - "type": { - Type: schema.TypeString, - Optional: true, - Description: "type of the disks", - }, - "sep_id": { - Type: schema.TypeInt, - Optional: true, - Description: "find by sep ID", - }, - "pool_name": { - Type: schema.TypeString, - Optional: true, - Description: "find by pool name", - }, - "page": { - Type: schema.TypeInt, - Optional: true, - Description: "Page number", - }, - "size": { - Type: schema.TypeInt, - Optional: true, - Description: "Page size", - }, - "items": { - Type: schema.TypeList, - Computed: true, - Elem: &schema.Resource{ - Schema: map[string]*schema.Schema{ - "account_id": { - Type: schema.TypeInt, - Computed: true, - Description: "The unique ID of the subscriber-owner of the disk", - }, - "account_name": { - Type: schema.TypeString, - Computed: true, - Description: "The name of the subscriber '(account') to whom this disk belongs", - }, - "acl": { - Type: schema.TypeString, - Computed: true, - }, - // "boot_partition": { - // Type: schema.TypeInt, - // Computed: true, - // Description: "Number of disk partitions", - // }, - "computes": { - Type: schema.TypeList, - Computed: true, - Elem: &schema.Resource{ - Schema: map[string]*schema.Schema{ - "compute_id": { - Type: schema.TypeString, - Computed: true, - }, - "compute_name": { - Type: schema.TypeString, - Computed: true, - }, - }, - }, - }, - "created_time": { - Type: schema.TypeInt, - Computed: true, - Description: "Created time", - }, - "deleted_time": { - Type: schema.TypeInt, - Computed: true, - Description: "Deleted time", - }, - "desc": { - Type: schema.TypeString, - Computed: true, - Description: "Description of disk", - }, - "destruction_time": { - Type: schema.TypeInt, - Computed: true, - Description: "Time of final deletion", - }, - "devicename": { - Type: schema.TypeString, - Computed: true, - Description: "Name of the device", - }, - // "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", - // }, - "disk_id": { - Type: schema.TypeInt, - Computed: true, - Description: "The unique ID of the subscriber-owner of the disk", - }, - "image_id": { - Type: schema.TypeInt, - Computed: true, - Description: "Image ID", - }, - "images": { - Type: schema.TypeList, - Computed: true, - Elem: &schema.Schema{ - Type: schema.TypeString, - }, - Description: "IDs of images using the disk", - }, - "iotune": { - Type: schema.TypeList, - Computed: true, - Elem: &schema.Resource{ - Schema: map[string]*schema.Schema{ - "read_bytes_sec": { - Type: schema.TypeInt, - Computed: true, - Description: "Number of bytes to read per second", - }, - "read_bytes_sec_max": { - Type: schema.TypeInt, - Computed: true, - Description: "Maximum number of bytes to read", - }, - "read_iops_sec": { - Type: schema.TypeInt, - Computed: true, - Description: "Number of io read operations per second", - }, - "read_iops_sec_max": { - Type: schema.TypeInt, - Computed: true, - Description: "Maximum number of io read operations", - }, - "size_iops_sec": { - Type: schema.TypeInt, - Computed: true, - Description: "Size of io operations", - }, - "total_bytes_sec": { - Type: schema.TypeInt, - Computed: true, - Description: "Total size bytes per second", - }, - "total_bytes_sec_max": { - Type: schema.TypeInt, - Computed: true, - Description: "Maximum total size of bytes per second", - }, - "total_iops_sec": { - Type: schema.TypeInt, - Computed: true, - Description: "Total number of io operations per second", - }, - "total_iops_sec_max": { - Type: schema.TypeInt, - Computed: true, - Description: "Maximum total number of io operations per second", - }, - "write_bytes_sec": { - Type: schema.TypeInt, - Computed: true, - Description: "Number of bytes to write per second", - }, - "write_bytes_sec_max": { - Type: schema.TypeInt, - Computed: true, - Description: "Maximum number of bytes to write per second", - }, - "write_iops_sec": { - Type: schema.TypeInt, - Computed: true, - Description: "Number of write operations per second", - }, - "write_iops_sec_max": { - Type: schema.TypeInt, - Computed: true, - Description: "Maximum number of write operations per second", - }, - }, - }, - }, - // "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, - Description: "Machine ID", - }, - "machine_name": { - Type: schema.TypeString, - Computed: true, - Description: "Machine name", - }, - // "milestones": { - // Type: schema.TypeInt, - // Computed: true, - // Description: "Milestones", - // }, - "disk_name": { - Type: schema.TypeString, - Computed: true, - Description: "Name of disk", - }, - "order": { - Type: schema.TypeInt, - Computed: true, - Description: "Disk order", - }, - "params": { - Type: schema.TypeString, - Computed: true, - Description: "Disk params", - }, - "parent_id": { - Type: schema.TypeInt, - Computed: true, - Description: "ID of the parent 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", - }, - "pool": { - Type: schema.TypeString, - Computed: true, - Description: "Pool for disk location", - }, - "present_to": { - Type: schema.TypeList, - Computed: true, - Elem: &schema.Schema{ - Type: schema.TypeInt, - }, - }, - // "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", - // }, - "res_id": { - Type: schema.TypeString, - Computed: true, - Description: "Resource ID", - }, - "res_name": { - Type: schema.TypeString, - Computed: true, - Description: "Name of the resource", - }, - "role": { - Type: schema.TypeString, - Computed: true, - Description: "Disk role", - }, - "sep_id": { - Type: schema.TypeInt, - Computed: true, - Description: "Storage endpoint provider ID to create disk", - }, - "sep_type": { - Type: schema.TypeString, - Computed: true, - Description: "Type SEP. Defines the type of storage system and contains one of the values set in the cloud platform", - }, - "shareable": { - Type: schema.TypeBool, - Computed: true, - }, - "size_max": { - Type: schema.TypeInt, - Computed: true, - Description: "Size in GB", - }, - "size_used": { - Type: schema.TypeFloat, - Computed: true, - Description: "Number of used space, in GB", - }, - "snapshots": { - Type: schema.TypeList, - Computed: true, - Elem: &schema.Resource{ - Schema: map[string]*schema.Schema{ - "guid": { - Type: schema.TypeString, - Computed: true, - Description: "ID of the snapshot", - }, - "label": { - Type: schema.TypeString, - Computed: true, - Description: "Name of the snapshot", - }, - "res_id": { - Type: schema.TypeString, - Computed: true, - Description: "Reference to the snapshot", - }, - "snap_set_guid": { - Type: schema.TypeString, - Computed: true, - Description: "The set snapshot ID", - }, - "snap_set_time": { - Type: schema.TypeInt, - Computed: true, - Description: "The set time of the snapshot", - }, - "timestamp": { - Type: schema.TypeInt, - Computed: true, - Description: "Snapshot time", - }, - }, - }, - }, - "status": { - Type: schema.TypeString, - Computed: true, - Description: "Disk status", - }, - "tech_status": { - Type: schema.TypeString, - Computed: true, - Description: "Technical status of the disk", - }, - "type": { - Type: schema.TypeString, - Computed: true, - Description: "The type of disk in terms of its role in compute: 'B=Boot, D=Data, T=Temp'", - }, - "vmid": { - Type: schema.TypeInt, - Computed: true, - Description: "Virtual Machine ID (Deprecated)", - }, - }, - }, - }, - "entry_count": { - Type: schema.TypeInt, - Computed: true, - }, - } - return res -} - -func DataSourceDiskList() *schema.Resource { - return &schema.Resource{ - SchemaVersion: 1, - - ReadContext: dataSourceDiskListRead, - - Timeouts: &schema.ResourceTimeout{ - Read: &constants.Timeout30s, - Default: &constants.Timeout60s, - }, - - Schema: dataSourceDiskListSchemaMake(), - } -} +/* +Copyright (c) 2019-2022 Digital Energy Cloud Solutions LLC. All Rights Reserved. +Authors: +Petr Krutov, +Stanislav Solovev, +Kasim Baybikov, + +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 + +import ( + "context" + + "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" +) + +func dataSourceDiskListRead(ctx context.Context, d *schema.ResourceData, m interface{}) diag.Diagnostics { + diskList, err := utilityDiskListCheckPresence(ctx, d, m) + if err != nil { + d.SetId("") + return diag.FromErr(err) + } + + id := uuid.New() + d.SetId(id.String()) + d.Set("items", flattenDiskList(diskList)) + d.Set("entry_count", diskList.EntryCount) + + return nil +} + +func dataSourceDiskListSchemaMake() map[string]*schema.Schema { + res := map[string]*schema.Schema{ + "by_id": { + Type: schema.TypeInt, + Optional: true, + Description: "Find by ID", + }, + "name": { + Type: schema.TypeString, + Optional: true, + Description: "Find by name", + }, + "account_name": { + Type: schema.TypeString, + Optional: true, + Description: "Find by account name", + }, + "disk_max_size": { + Type: schema.TypeInt, + Optional: true, + Description: "Find by max disk size", + }, + "status": { + Type: schema.TypeString, + Optional: true, + Description: "Find by status", + }, + "shared": { + Type: schema.TypeBool, + Optional: true, + Description: "Find by shared field", + }, + "account_id": { + Type: schema.TypeInt, + Optional: true, + Description: "ID of the account the disks belong to", + }, + "type": { + Type: schema.TypeString, + Optional: true, + Description: "type of the disks", + }, + "sep_id": { + Type: schema.TypeInt, + Optional: true, + Description: "find by sep ID", + }, + "pool_name": { + Type: schema.TypeString, + Optional: true, + Description: "find by pool name", + }, + "page": { + Type: schema.TypeInt, + Optional: true, + Description: "Page number", + }, + "size": { + Type: schema.TypeInt, + Optional: true, + Description: "Page size", + }, + "items": { + Type: schema.TypeList, + Computed: true, + Elem: &schema.Resource{ + Schema: map[string]*schema.Schema{ + "account_id": { + Type: schema.TypeInt, + Computed: true, + Description: "The unique ID of the subscriber-owner of the disk", + }, + "account_name": { + Type: schema.TypeString, + Computed: true, + Description: "The name of the subscriber '(account') to whom this disk belongs", + }, + "acl": { + Type: schema.TypeString, + Computed: true, + }, + // "boot_partition": { + // Type: schema.TypeInt, + // Computed: true, + // Description: "Number of disk partitions", + // }, + "computes": { + Type: schema.TypeList, + Computed: true, + Elem: &schema.Resource{ + Schema: map[string]*schema.Schema{ + "compute_id": { + Type: schema.TypeString, + Computed: true, + }, + "compute_name": { + Type: schema.TypeString, + Computed: true, + }, + }, + }, + }, + "created_time": { + Type: schema.TypeInt, + Computed: true, + Description: "Created time", + }, + "deleted_time": { + Type: schema.TypeInt, + Computed: true, + Description: "Deleted time", + }, + "desc": { + Type: schema.TypeString, + Computed: true, + Description: "Description of disk", + }, + "destruction_time": { + Type: schema.TypeInt, + Computed: true, + Description: "Time of final deletion", + }, + "devicename": { + Type: schema.TypeString, + Computed: true, + Description: "Name of the device", + }, + // "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", + // }, + "disk_id": { + Type: schema.TypeInt, + Computed: true, + Description: "The unique ID of the subscriber-owner of the disk", + }, + "image_id": { + Type: schema.TypeInt, + Computed: true, + Description: "Image ID", + }, + "images": { + Type: schema.TypeList, + Computed: true, + Elem: &schema.Schema{ + Type: schema.TypeString, + }, + Description: "IDs of images using the disk", + }, + "iotune": { + Type: schema.TypeList, + Computed: true, + Elem: &schema.Resource{ + Schema: map[string]*schema.Schema{ + "read_bytes_sec": { + Type: schema.TypeInt, + Computed: true, + Description: "Number of bytes to read per second", + }, + "read_bytes_sec_max": { + Type: schema.TypeInt, + Computed: true, + Description: "Maximum number of bytes to read", + }, + "read_iops_sec": { + Type: schema.TypeInt, + Computed: true, + Description: "Number of io read operations per second", + }, + "read_iops_sec_max": { + Type: schema.TypeInt, + Computed: true, + Description: "Maximum number of io read operations", + }, + "size_iops_sec": { + Type: schema.TypeInt, + Computed: true, + Description: "Size of io operations", + }, + "total_bytes_sec": { + Type: schema.TypeInt, + Computed: true, + Description: "Total size bytes per second", + }, + "total_bytes_sec_max": { + Type: schema.TypeInt, + Computed: true, + Description: "Maximum total size of bytes per second", + }, + "total_iops_sec": { + Type: schema.TypeInt, + Computed: true, + Description: "Total number of io operations per second", + }, + "total_iops_sec_max": { + Type: schema.TypeInt, + Computed: true, + Description: "Maximum total number of io operations per second", + }, + "write_bytes_sec": { + Type: schema.TypeInt, + Computed: true, + Description: "Number of bytes to write per second", + }, + "write_bytes_sec_max": { + Type: schema.TypeInt, + Computed: true, + Description: "Maximum number of bytes to write per second", + }, + "write_iops_sec": { + Type: schema.TypeInt, + Computed: true, + Description: "Number of write operations per second", + }, + "write_iops_sec_max": { + Type: schema.TypeInt, + Computed: true, + Description: "Maximum number of write operations per second", + }, + }, + }, + }, + // "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, + Description: "Machine ID", + }, + "machine_name": { + Type: schema.TypeString, + Computed: true, + Description: "Machine name", + }, + // "milestones": { + // Type: schema.TypeInt, + // Computed: true, + // Description: "Milestones", + // }, + "disk_name": { + Type: schema.TypeString, + Computed: true, + Description: "Name of disk", + }, + "order": { + Type: schema.TypeInt, + Computed: true, + Description: "Disk order", + }, + "params": { + Type: schema.TypeString, + Computed: true, + Description: "Disk params", + }, + "parent_id": { + Type: schema.TypeInt, + Computed: true, + Description: "ID of the parent 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", + }, + "pool": { + Type: schema.TypeString, + Computed: true, + Description: "Pool for disk location", + }, + "present_to": { + Type: schema.TypeList, + Computed: true, + Elem: &schema.Schema{ + Type: schema.TypeInt, + }, + }, + // "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", + // }, + "res_id": { + Type: schema.TypeString, + Computed: true, + Description: "Resource ID", + }, + "res_name": { + Type: schema.TypeString, + Computed: true, + Description: "Name of the resource", + }, + "role": { + Type: schema.TypeString, + Computed: true, + Description: "Disk role", + }, + "sep_id": { + Type: schema.TypeInt, + Computed: true, + Description: "Storage endpoint provider ID to create disk", + }, + "sep_type": { + Type: schema.TypeString, + Computed: true, + Description: "Type SEP. Defines the type of storage system and contains one of the values set in the cloud platform", + }, + "shareable": { + Type: schema.TypeBool, + Computed: true, + }, + "size_max": { + Type: schema.TypeInt, + Computed: true, + Description: "Size in GB", + }, + "size_used": { + Type: schema.TypeFloat, + Computed: true, + Description: "Number of used space, in GB", + }, + "snapshots": { + Type: schema.TypeList, + Computed: true, + Elem: &schema.Resource{ + Schema: map[string]*schema.Schema{ + "guid": { + Type: schema.TypeString, + Computed: true, + Description: "ID of the snapshot", + }, + "label": { + Type: schema.TypeString, + Computed: true, + Description: "Name of the snapshot", + }, + "res_id": { + Type: schema.TypeString, + Computed: true, + Description: "Reference to the snapshot", + }, + "snap_set_guid": { + Type: schema.TypeString, + Computed: true, + Description: "The set snapshot ID", + }, + "snap_set_time": { + Type: schema.TypeInt, + Computed: true, + Description: "The set time of the snapshot", + }, + "timestamp": { + Type: schema.TypeInt, + Computed: true, + Description: "Snapshot time", + }, + }, + }, + }, + "status": { + Type: schema.TypeString, + Computed: true, + Description: "Disk status", + }, + "tech_status": { + Type: schema.TypeString, + Computed: true, + Description: "Technical status of the disk", + }, + "type": { + Type: schema.TypeString, + Computed: true, + Description: "The type of disk in terms of its role in compute: 'B=Boot, D=Data, T=Temp'", + }, + "vmid": { + Type: schema.TypeInt, + Computed: true, + Description: "Virtual Machine ID (Deprecated)", + }, + }, + }, + }, + "entry_count": { + Type: schema.TypeInt, + Computed: true, + }, + } + return res +} + +func DataSourceDiskList() *schema.Resource { + return &schema.Resource{ + SchemaVersion: 1, + + ReadContext: dataSourceDiskListRead, + + Timeouts: &schema.ResourceTimeout{ + Read: &constants.Timeout30s, + Default: &constants.Timeout60s, + }, + + Schema: dataSourceDiskListSchemaMake(), + } +} diff --git a/internal/service/cloudapi/disks/data_source_disk_list_types.go b/internal/service/cloudapi/disks/data_source_disk_list_types.go index 33f06d9..97255fa 100644 --- a/internal/service/cloudapi/disks/data_source_disk_list_types.go +++ b/internal/service/cloudapi/disks/data_source_disk_list_types.go @@ -44,6 +44,7 @@ import ( func dataSourceDiskListTypesRead(ctx context.Context, d *schema.ResourceData, m interface{}) diag.Diagnostics { listTypes, err := utilityDiskListTypesCheckPresence(ctx, d, m) if err != nil { + d.SetId("") return diag.FromErr(err) } diff --git a/internal/service/cloudapi/disks/data_source_disk_list_types_detailed.go b/internal/service/cloudapi/disks/data_source_disk_list_types_detailed.go index e3b7b47..61d7a38 100644 --- a/internal/service/cloudapi/disks/data_source_disk_list_types_detailed.go +++ b/internal/service/cloudapi/disks/data_source_disk_list_types_detailed.go @@ -47,8 +47,8 @@ func flattenDiskListTypesDetailed(tld *disks.ListTypes) []map[string]interface{} for _, typeListDetailed := range tld.Data { toMap := typeListDetailed.(map[string]interface{}) temp := map[string]interface{}{ - "pools": flattenListTypesDetailedPools(toMap["pools"].([]interface{})), - "sep_id": toMap["sepId"].(float64), + "pools": flattenListTypesDetailedPools(toMap["pools"].([]interface{})), + "sep_id": toMap["sepId"].(float64), "sep_name": toMap["sepName"].(string), } res = append(res, temp) @@ -61,9 +61,9 @@ func flattenListTypesDetailedPools(pools []interface{}) []interface{} { for _, pool := range pools { toMap := pool.(map[string]interface{}) temp := map[string]interface{}{ - "name": toMap["name"].(string), + "name": toMap["name"].(string), "system": toMap["system"].(string), - "types": toMap["types"].([]interface{}), + "types": toMap["types"].([]interface{}), } res = append(res, temp) } @@ -74,6 +74,7 @@ func flattenListTypesDetailedPools(pools []interface{}) []interface{} { func dataSourceDiskListTypesDetailedRead(ctx context.Context, d *schema.ResourceData, m interface{}) diag.Diagnostics { listTypesDetailed, err := utilityDiskListTypesDetailedCheckPresence(ctx, d, m) if err != nil { + d.SetId("") return diag.FromErr(err) } @@ -112,8 +113,8 @@ func dataSourceDiskListTypesDetailedSchemaMake() map[string]*schema.Schema { Description: "Pool name", }, "system": { - Type: schema.TypeString, - Computed: true, + Type: schema.TypeString, + Computed: true, }, "types": { Type: schema.TypeList, @@ -132,8 +133,8 @@ func dataSourceDiskListTypesDetailedSchemaMake() map[string]*schema.Schema { Description: "Storage endpoint provider ID to create disk", }, "sep_name": { - Type: schema.TypeString, - Computed: true, + Type: schema.TypeString, + Computed: true, }, }, }, diff --git a/internal/service/cloudapi/disks/data_source_disk_list_unattached.go b/internal/service/cloudapi/disks/data_source_disk_list_unattached.go index 5ad0e7f..001af64 100644 --- a/internal/service/cloudapi/disks/data_source_disk_list_unattached.go +++ b/internal/service/cloudapi/disks/data_source_disk_list_unattached.go @@ -44,6 +44,7 @@ import ( func dataSourceDiskListUnattachedRead(ctx context.Context, d *schema.ResourceData, m interface{}) diag.Diagnostics { diskListUnattached, err := utilityDiskListUnattachedCheckPresence(ctx, d, m) if err != nil { + d.SetId("") return diag.FromErr(err) } @@ -375,6 +376,11 @@ func dataSourceDiskListUnattachedSchemaMake() map[string]*schema.Schema { Computed: true, Description: "Storage endpoint provider ID to create disk", }, + "shareable": { + Type: schema.TypeBool, + Computed: true, + Description: "shareable", + }, "size_max": { Type: schema.TypeInt, Computed: true, diff --git a/internal/service/cloudapi/disks/data_source_disk_snapshot.go b/internal/service/cloudapi/disks/data_source_disk_snapshot.go index 4140009..736fa1e 100644 --- a/internal/service/cloudapi/disks/data_source_disk_snapshot.go +++ b/internal/service/cloudapi/disks/data_source_disk_snapshot.go @@ -45,6 +45,7 @@ import ( func dataSourceDiskSnapshotRead(ctx context.Context, d *schema.ResourceData, m interface{}) diag.Diagnostics { disk, err := utilityDiskCheckPresence(ctx, d, m) if err != nil { + d.SetId("") return diag.FromErr(err) } diff --git a/internal/service/cloudapi/disks/data_source_disk_snapshot_list.go b/internal/service/cloudapi/disks/data_source_disk_snapshot_list.go index d1dbe06..3799303 100644 --- a/internal/service/cloudapi/disks/data_source_disk_snapshot_list.go +++ b/internal/service/cloudapi/disks/data_source_disk_snapshot_list.go @@ -44,6 +44,7 @@ import ( func dataSourceDiskSnapshotListRead(ctx context.Context, d *schema.ResourceData, m interface{}) diag.Diagnostics { disk, err := utilityDiskCheckPresence(ctx, d, m) if err != nil { + d.SetId("") return diag.FromErr(err) } diff --git a/internal/service/cloudapi/disks/data_source_list_deleted.go b/internal/service/cloudapi/disks/data_source_list_deleted.go index f9527e0..33ab9e4 100644 --- a/internal/service/cloudapi/disks/data_source_list_deleted.go +++ b/internal/service/cloudapi/disks/data_source_list_deleted.go @@ -45,6 +45,7 @@ import ( func dataSourceDiskListDeletedRead(ctx context.Context, d *schema.ResourceData, m interface{}) diag.Diagnostics { diskList, err := utilityDiskListDeletedCheckPresence(ctx, d, m) if err != nil { + d.SetId("") return diag.FromErr(err) } diff --git a/internal/service/cloudapi/disks/flattens.go b/internal/service/cloudapi/disks/flattens.go index 52b8c10..aa9f283 100644 --- a/internal/service/cloudapi/disks/flattens.go +++ b/internal/service/cloudapi/disks/flattens.go @@ -56,6 +56,7 @@ func flattenDiskListUnattached(ul *disks.ListDisksUnattached) []map[string]inter "res_name": unattachedDisk.ResName, "role": unattachedDisk.Role, "sep_id": unattachedDisk.SEPID, + "shareable": unattachedDisk.Shareable, "size_max": unattachedDisk.SizeMax, "size_used": unattachedDisk.SizeUsed, "snapshots": flattenDiskSnapshotList(unattachedDisk.Snapshots), diff --git a/internal/service/cloudapi/disks/resource_disk.go b/internal/service/cloudapi/disks/resource_disk.go index 22e3bf1..1607917 100644 --- a/internal/service/cloudapi/disks/resource_disk.go +++ b/internal/service/cloudapi/disks/resource_disk.go @@ -95,6 +95,7 @@ func resourceDiskCreate(ctx context.Context, d *schema.ResourceData, m interface diskId, err := c.CloudAPI().Disks().Create(ctx, req) if err != nil { + d.SetId("") return diag.FromErr(err) } @@ -219,6 +220,7 @@ func resourceDiskUpdate(ctx context.Context, d *schema.ResourceData, m interface disk, err := utilityDiskCheckPresence(ctx, d, m) if err != nil { + d.SetId("") return diag.FromErr(err) } @@ -377,9 +379,9 @@ func resourceDiskDelete(ctx context.Context, d *schema.ResourceData, m interface func resourceDiskSchemaMake() map[string]*schema.Schema { rets := map[string]*schema.Schema{ "account_id": { - Type: schema.TypeInt, - Required: true, - ForceNew: true, + Type: schema.TypeInt, + Required: true, + //ForceNew: true, Description: "The unique ID of the subscriber-owner of the disk", }, "disk_name": { @@ -393,9 +395,9 @@ func resourceDiskSchemaMake() map[string]*schema.Schema { Description: "Size in GB", }, "gid": { - Type: schema.TypeInt, - Required: true, - ForceNew: true, + Type: schema.TypeInt, + Required: true, + //ForceNew: true, Description: "ID of the grid (platform)", }, "pool": { diff --git a/internal/service/cloudapi/disks/resource_disk_snapshot.go b/internal/service/cloudapi/disks/resource_disk_snapshot.go index 4e30066..0ddd732 100644 --- a/internal/service/cloudapi/disks/resource_disk_snapshot.go +++ b/internal/service/cloudapi/disks/resource_disk_snapshot.go @@ -83,6 +83,7 @@ func resourceDiskSnapshotCreate(ctx context.Context, d *schema.ResourceData, m i func resourceDiskSnapshotRead(ctx context.Context, d *schema.ResourceData, m interface{}) diag.Diagnostics { disk, err := utilityDiskCheckPresence(ctx, d, m) if err != nil { + d.SetId("") return diag.FromErr(err) } @@ -169,15 +170,15 @@ func resourceDiskSnapshotDelete(ctx context.Context, d *schema.ResourceData, m i func resourceDiskSnapshotSchemaMake() map[string]*schema.Schema { rets := map[string]*schema.Schema{ "disk_id": { - Type: schema.TypeInt, - Required: true, - ForceNew: true, + Type: schema.TypeInt, + Required: true, + //ForceNew: true, Description: "The unique ID of the subscriber-owner of the disk", }, "label": { - Type: schema.TypeString, - Required: true, - ForceNew: true, + Type: schema.TypeString, + Required: true, + //ForceNew: true, Description: "Name of the snapshot", }, "rollback": { diff --git a/internal/service/cloudapi/extnet/data_source_extnet.go b/internal/service/cloudapi/extnet/data_source_extnet.go index 1bb6d6a..5fa692e 100644 --- a/internal/service/cloudapi/extnet/data_source_extnet.go +++ b/internal/service/cloudapi/extnet/data_source_extnet.go @@ -1,285 +1,286 @@ -/* -Copyright (c) 2019-2022 Digital Energy Cloud Solutions LLC. All Rights Reserved. -Authors: -Petr Krutov, -Stanislav Solovev, -Kasim Baybikov, -Tim Tkachev, - -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 - -import ( - "context" - "strconv" - - "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" -) - -func dataSourceExtnetRead(ctx context.Context, d *schema.ResourceData, m interface{}) diag.Diagnostics { - e, err := utilityExtnetCheckPresence(ctx, d, m) - if err != nil { - return diag.FromErr(err) - } - - d.SetId(strconv.FormatUint(e.ID, 10)) - flattenExtnet(d, e) - - return nil -} - -func dataSourceExtnetSchemaMake() map[string]*schema.Schema { - res := map[string]*schema.Schema{ - "net_id": { - Type: schema.TypeInt, - Required: true, - }, - "ckey": { - Type: schema.TypeString, - Computed: true, - }, - "meta": { - Type: schema.TypeList, - Computed: true, - Elem: &schema.Schema{ - Type: schema.TypeString, - }, - Description: "meta", - }, - "check_ips": { - Type: schema.TypeList, - Computed: true, - Elem: &schema.Schema{ - Type: schema.TypeString, - }, - }, - "default": { - Type: schema.TypeBool, - Computed: true, - }, - "default_qos": { - Type: schema.TypeList, - Computed: true, - Elem: &schema.Resource{ - Schema: map[string]*schema.Schema{ - "e_rate": { - Type: schema.TypeInt, - Computed: true, - }, - "e_burst": { - Type: schema.TypeInt, - Computed: true, - }, - "guid": { - Type: schema.TypeString, - Computed: true, - }, - "in_burst": { - Type: schema.TypeInt, - Computed: true, - }, - "in_rate": { - Type: schema.TypeInt, - Computed: true, - }, - }, - }, - }, - "desc": { - Type: schema.TypeString, - Computed: true, - }, - "dns": { - Type: schema.TypeList, - Computed: true, - Elem: &schema.Schema{ - Type: schema.TypeString, - }, - }, - "excluded": { - Type: schema.TypeList, - Computed: true, - Elem: &schema.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": { - Type: schema.TypeInt, - Computed: true, - }, - "gateway": { - Type: schema.TypeString, - Computed: true, - }, - "gid": { - Type: schema.TypeInt, - Computed: true, - }, - "guid": { - Type: schema.TypeInt, - Computed: true, - }, - "ipcidr": { - Type: schema.TypeString, - Computed: true, - }, - "milestones": { - Type: schema.TypeInt, - Computed: true, - }, - "net_name": { - Type: schema.TypeString, - Computed: true, - }, - "network": { - Type: schema.TypeString, - Computed: true, - }, - "network_id": { - Type: schema.TypeInt, - Computed: true, - }, - "pre_reservations_num": { - Type: schema.TypeInt, - Computed: true, - }, - "prefix": { - Type: schema.TypeInt, - Computed: true, - }, - "pri_vnf_dev_id": { - Type: schema.TypeInt, - Computed: true, - }, - "reservations": { - Type: schema.TypeList, - Computed: true, - Elem: &schema.Resource{ - Schema: map[string]*schema.Schema{ - "client_type": { - Type: schema.TypeString, - Computed: true, - }, - "domainname": { - Type: schema.TypeString, - Computed: true, - }, - "hostname": { - Type: schema.TypeString, - Computed: true, - }, - "desc": { - Type: schema.TypeString, - Computed: true, - }, - "ip": { - Type: schema.TypeString, - Computed: true, - }, - "mac": { - Type: schema.TypeString, - Computed: true, - }, - "type": { - Type: schema.TypeString, - Computed: true, - }, - "vm_id": { - Type: schema.TypeInt, - Computed: true, - }, - }, - }, - }, - "shared_with": { - Type: schema.TypeList, - Computed: true, - Elem: &schema.Schema{ - Type: schema.TypeInt, - }, - }, - "status": { - Type: schema.TypeString, - Computed: true, - }, - "vlan_id": { - Type: schema.TypeInt, - Computed: true, - }, - "vnfs": { - Type: schema.TypeList, - Computed: true, - Elem: &schema.Resource{ - Schema: map[string]*schema.Schema{ - "dhcp": { - Type: schema.TypeInt, - Computed: true, - }, - }, - }, - }, - } - return res -} - -func DataSourceExtnet() *schema.Resource { - return &schema.Resource{ - SchemaVersion: 1, - - ReadContext: dataSourceExtnetRead, - - Timeouts: &schema.ResourceTimeout{ - Read: &constants.Timeout30s, - Default: &constants.Timeout60s, - }, - - Schema: dataSourceExtnetSchemaMake(), - } -} +/* +Copyright (c) 2019-2022 Digital Energy Cloud Solutions LLC. All Rights Reserved. +Authors: +Petr Krutov, +Stanislav Solovev, +Kasim Baybikov, +Tim Tkachev, + +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 + +import ( + "context" + "strconv" + + "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" +) + +func dataSourceExtnetRead(ctx context.Context, d *schema.ResourceData, m interface{}) diag.Diagnostics { + e, err := utilityExtnetCheckPresence(ctx, d, m) + if err != nil { + d.SetId("") + return diag.FromErr(err) + } + + d.SetId(strconv.FormatUint(e.ID, 10)) + flattenExtnet(d, e) + + return nil +} + +func dataSourceExtnetSchemaMake() map[string]*schema.Schema { + res := map[string]*schema.Schema{ + "net_id": { + Type: schema.TypeInt, + Required: true, + }, + "ckey": { + Type: schema.TypeString, + Computed: true, + }, + "meta": { + Type: schema.TypeList, + Computed: true, + Elem: &schema.Schema{ + Type: schema.TypeString, + }, + Description: "meta", + }, + "check_ips": { + Type: schema.TypeList, + Computed: true, + Elem: &schema.Schema{ + Type: schema.TypeString, + }, + }, + "default": { + Type: schema.TypeBool, + Computed: true, + }, + "default_qos": { + Type: schema.TypeList, + Computed: true, + Elem: &schema.Resource{ + Schema: map[string]*schema.Schema{ + "e_rate": { + Type: schema.TypeInt, + Computed: true, + }, + "e_burst": { + Type: schema.TypeInt, + Computed: true, + }, + "guid": { + Type: schema.TypeString, + Computed: true, + }, + "in_burst": { + Type: schema.TypeInt, + Computed: true, + }, + "in_rate": { + Type: schema.TypeInt, + Computed: true, + }, + }, + }, + }, + "desc": { + Type: schema.TypeString, + Computed: true, + }, + "dns": { + Type: schema.TypeList, + Computed: true, + Elem: &schema.Schema{ + Type: schema.TypeString, + }, + }, + "excluded": { + Type: schema.TypeList, + Computed: true, + Elem: &schema.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": { + Type: schema.TypeInt, + Computed: true, + }, + "gateway": { + Type: schema.TypeString, + Computed: true, + }, + "gid": { + Type: schema.TypeInt, + Computed: true, + }, + "guid": { + Type: schema.TypeInt, + Computed: true, + }, + "ipcidr": { + Type: schema.TypeString, + Computed: true, + }, + "milestones": { + Type: schema.TypeInt, + Computed: true, + }, + "net_name": { + Type: schema.TypeString, + Computed: true, + }, + "network": { + Type: schema.TypeString, + Computed: true, + }, + "network_id": { + Type: schema.TypeInt, + Computed: true, + }, + "pre_reservations_num": { + Type: schema.TypeInt, + Computed: true, + }, + "prefix": { + Type: schema.TypeInt, + Computed: true, + }, + "pri_vnf_dev_id": { + Type: schema.TypeInt, + Computed: true, + }, + "reservations": { + Type: schema.TypeList, + Computed: true, + Elem: &schema.Resource{ + Schema: map[string]*schema.Schema{ + "client_type": { + Type: schema.TypeString, + Computed: true, + }, + "domainname": { + Type: schema.TypeString, + Computed: true, + }, + "hostname": { + Type: schema.TypeString, + Computed: true, + }, + "desc": { + Type: schema.TypeString, + Computed: true, + }, + "ip": { + Type: schema.TypeString, + Computed: true, + }, + "mac": { + Type: schema.TypeString, + Computed: true, + }, + "type": { + Type: schema.TypeString, + Computed: true, + }, + "vm_id": { + Type: schema.TypeInt, + Computed: true, + }, + }, + }, + }, + "shared_with": { + Type: schema.TypeList, + Computed: true, + Elem: &schema.Schema{ + Type: schema.TypeInt, + }, + }, + "status": { + Type: schema.TypeString, + Computed: true, + }, + "vlan_id": { + Type: schema.TypeInt, + Computed: true, + }, + "vnfs": { + Type: schema.TypeList, + Computed: true, + Elem: &schema.Resource{ + Schema: map[string]*schema.Schema{ + "dhcp": { + Type: schema.TypeInt, + Computed: true, + }, + }, + }, + }, + } + return res +} + +func DataSourceExtnet() *schema.Resource { + return &schema.Resource{ + SchemaVersion: 1, + + ReadContext: dataSourceExtnetRead, + + Timeouts: &schema.ResourceTimeout{ + Read: &constants.Timeout30s, + Default: &constants.Timeout60s, + }, + + Schema: dataSourceExtnetSchemaMake(), + } +} diff --git a/internal/service/cloudapi/extnet/data_source_extnet_computes_list.go b/internal/service/cloudapi/extnet/data_source_extnet_computes_list.go index f8c05be..555ed10 100644 --- a/internal/service/cloudapi/extnet/data_source_extnet_computes_list.go +++ b/internal/service/cloudapi/extnet/data_source_extnet_computes_list.go @@ -1,161 +1,162 @@ -/* -Copyright (c) 2019-2022 Digital Energy Cloud Solutions LLC. All Rights Reserved. -Authors: -Petr Krutov, -Stanislav Solovev, -Kasim Baybikov, - -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 - -import ( - "context" - - "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" -) - -func dataSourceExtnetComputesListRead(ctx context.Context, d *schema.ResourceData, m interface{}) diag.Diagnostics { - extnetComputesList, err := utilityExtnetComputesListCheckPresence(ctx, d, m) - if err != nil { - return diag.FromErr(err) - } - - id := uuid.New() - d.SetId(id.String()) - d.Set("items", flattenExtnetComputesList(extnetComputesList)) - d.Set("entry_count", extnetComputesList.EntryCount) - return nil -} - -func dataSourceExtnetComputesListSchemaMake() map[string]*schema.Schema { - res := map[string]*schema.Schema{ - "account_id": { - Type: schema.TypeInt, - Required: true, - Description: "filter by account ID", - }, - "rg_id": { - Type: schema.TypeInt, - Optional: true, - Description: "Filter by RG ID", - }, - "compute_id": { - Type: schema.TypeInt, - Optional: true, - Description: "Filter by compute ID", - }, - "page": { - Type: schema.TypeInt, - Optional: true, - Description: "Page number", - }, - "size": { - Type: schema.TypeInt, - Optional: true, - Description: "Page size", - }, - "items": { - Type: schema.TypeList, - Computed: true, - Elem: &schema.Resource{ - Schema: map[string]*schema.Schema{ - "account_id": { - Type: schema.TypeInt, - Computed: true, - }, - "account_name": { - Type: schema.TypeString, - Computed: true, - }, - "extnets": { - Type: schema.TypeList, - Computed: true, - Elem: &schema.Resource{ - Schema: map[string]*schema.Schema{ - "net_id": { - Type: schema.TypeInt, - Computed: true, - }, - "ipaddr": { - Type: schema.TypeString, - Computed: true, - }, - "ipcidr": { - Type: schema.TypeString, - Computed: true, - }, - "name": { - Type: schema.TypeString, - Computed: true, - }, - }, - }, - }, - "id": { - Type: schema.TypeInt, - Computed: true, - }, - "name": { - Type: schema.TypeString, - Computed: true, - }, - "rg_id": { - Type: schema.TypeInt, - Computed: true, - }, - "rg_name": { - Type: schema.TypeString, - Computed: true, - }, - }, - }, - }, - "entry_count": { - Type: schema.TypeInt, - Computed: true, - }, - } - return res -} - -func DataSourceExtnetComputesList() *schema.Resource { - return &schema.Resource{ - SchemaVersion: 1, - - ReadContext: dataSourceExtnetComputesListRead, - - Timeouts: &schema.ResourceTimeout{ - Read: &constants.Timeout30s, - Default: &constants.Timeout60s, - }, - - Schema: dataSourceExtnetComputesListSchemaMake(), - } -} +/* +Copyright (c) 2019-2022 Digital Energy Cloud Solutions LLC. All Rights Reserved. +Authors: +Petr Krutov, +Stanislav Solovev, +Kasim Baybikov, + +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 + +import ( + "context" + + "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" +) + +func dataSourceExtnetComputesListRead(ctx context.Context, d *schema.ResourceData, m interface{}) diag.Diagnostics { + extnetComputesList, err := utilityExtnetComputesListCheckPresence(ctx, d, m) + if err != nil { + d.SetId("") + return diag.FromErr(err) + } + + id := uuid.New() + d.SetId(id.String()) + d.Set("items", flattenExtnetComputesList(extnetComputesList)) + d.Set("entry_count", extnetComputesList.EntryCount) + return nil +} + +func dataSourceExtnetComputesListSchemaMake() map[string]*schema.Schema { + res := map[string]*schema.Schema{ + "account_id": { + Type: schema.TypeInt, + Required: true, + Description: "filter by account ID", + }, + "rg_id": { + Type: schema.TypeInt, + Optional: true, + Description: "Filter by RG ID", + }, + "compute_id": { + Type: schema.TypeInt, + Optional: true, + Description: "Filter by compute ID", + }, + "page": { + Type: schema.TypeInt, + Optional: true, + Description: "Page number", + }, + "size": { + Type: schema.TypeInt, + Optional: true, + Description: "Page size", + }, + "items": { + Type: schema.TypeList, + Computed: true, + Elem: &schema.Resource{ + Schema: map[string]*schema.Schema{ + "account_id": { + Type: schema.TypeInt, + Computed: true, + }, + "account_name": { + Type: schema.TypeString, + Computed: true, + }, + "extnets": { + Type: schema.TypeList, + Computed: true, + Elem: &schema.Resource{ + Schema: map[string]*schema.Schema{ + "net_id": { + Type: schema.TypeInt, + Computed: true, + }, + "ipaddr": { + Type: schema.TypeString, + Computed: true, + }, + "ipcidr": { + Type: schema.TypeString, + Computed: true, + }, + "name": { + Type: schema.TypeString, + Computed: true, + }, + }, + }, + }, + "id": { + Type: schema.TypeInt, + Computed: true, + }, + "name": { + Type: schema.TypeString, + Computed: true, + }, + "rg_id": { + Type: schema.TypeInt, + Computed: true, + }, + "rg_name": { + Type: schema.TypeString, + Computed: true, + }, + }, + }, + }, + "entry_count": { + Type: schema.TypeInt, + Computed: true, + }, + } + return res +} + +func DataSourceExtnetComputesList() *schema.Resource { + return &schema.Resource{ + SchemaVersion: 1, + + ReadContext: dataSourceExtnetComputesListRead, + + Timeouts: &schema.ResourceTimeout{ + Read: &constants.Timeout30s, + Default: &constants.Timeout60s, + }, + + Schema: dataSourceExtnetComputesListSchemaMake(), + } +} diff --git a/internal/service/cloudapi/extnet/data_source_extnet_default.go b/internal/service/cloudapi/extnet/data_source_extnet_default.go index 8cef8b0..f9e05fd 100644 --- a/internal/service/cloudapi/extnet/data_source_extnet_default.go +++ b/internal/service/cloudapi/extnet/data_source_extnet_default.go @@ -1,85 +1,86 @@ -/* -Copyright (c) 2019-2022 Digital Energy Cloud Solutions LLC. All Rights Reserved. -Authors: -Petr Krutov, -Stanislav Solovev, -Kasim Baybikov, - -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 - -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" -) - -func dataSourceExtnetDefaultRead(ctx context.Context, d *schema.ResourceData, m interface{}) diag.Diagnostics { - extnetId, err := utilityExtnetDefaultCheckPresence(ctx, m) - if err != nil { - return diag.FromErr(err) - } - - id := uuid.New() - d.SetId(id.String()) - extnetIdInt, err := strconv.ParseInt(extnetId, 10, 32) - if err != nil { - return diag.FromErr(err) - } - d.Set("net_id", extnetIdInt) - - return nil -} - -func dataSourceExtnetDefaultSchemaMake() map[string]*schema.Schema { - res := map[string]*schema.Schema{ - "net_id": { - Type: schema.TypeInt, - Computed: true, - }, - } - return res -} - -func DataSourceExtnetDefault() *schema.Resource { - return &schema.Resource{ - SchemaVersion: 1, - - ReadContext: dataSourceExtnetDefaultRead, - - Timeouts: &schema.ResourceTimeout{ - Read: &constants.Timeout30s, - Default: &constants.Timeout60s, - }, - - Schema: dataSourceExtnetDefaultSchemaMake(), - } -} +/* +Copyright (c) 2019-2022 Digital Energy Cloud Solutions LLC. All Rights Reserved. +Authors: +Petr Krutov, +Stanislav Solovev, +Kasim Baybikov, + +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 + +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" +) + +func dataSourceExtnetDefaultRead(ctx context.Context, d *schema.ResourceData, m interface{}) diag.Diagnostics { + extnetId, err := utilityExtnetDefaultCheckPresence(ctx, m) + if err != nil { + d.SetId("") + return diag.FromErr(err) + } + + id := uuid.New() + d.SetId(id.String()) + extnetIdInt, err := strconv.ParseInt(extnetId, 10, 32) + if err != nil { + return diag.FromErr(err) + } + d.Set("net_id", extnetIdInt) + + return nil +} + +func dataSourceExtnetDefaultSchemaMake() map[string]*schema.Schema { + res := map[string]*schema.Schema{ + "net_id": { + Type: schema.TypeInt, + Computed: true, + }, + } + return res +} + +func DataSourceExtnetDefault() *schema.Resource { + return &schema.Resource{ + SchemaVersion: 1, + + ReadContext: dataSourceExtnetDefaultRead, + + Timeouts: &schema.ResourceTimeout{ + Read: &constants.Timeout30s, + Default: &constants.Timeout60s, + }, + + Schema: dataSourceExtnetDefaultSchemaMake(), + } +} diff --git a/internal/service/cloudapi/extnet/data_source_extnet_list.go b/internal/service/cloudapi/extnet/data_source_extnet_list.go index 5d877f8..3442382 100644 --- a/internal/service/cloudapi/extnet/data_source_extnet_list.go +++ b/internal/service/cloudapi/extnet/data_source_extnet_list.go @@ -1,145 +1,150 @@ -/* -Copyright (c) 2019-2022 Digital Energy Cloud Solutions LLC. All Rights Reserved. -Authors: -Petr Krutov, -Stanislav Solovev, -Kasim Baybikov, - -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 - -import ( - "context" - - "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" -) - -func dataSourceExtnetListRead(ctx context.Context, d *schema.ResourceData, m interface{}) diag.Diagnostics { - extnetList, err := utilityExtnetListCheckPresence(ctx, d, m) - if err != nil { - return diag.FromErr(err) - } - - id := uuid.New() - d.SetId(id.String()) - d.Set("items", flattenExtnetList(extnetList)) - d.Set("entry_count", extnetList.EntryCount) - - return nil -} - -func dataSourceExtnetListSchemaMake() map[string]*schema.Schema { - res := map[string]*schema.Schema{ - "account_id": { - Type: schema.TypeInt, - Optional: true, - Description: "Find by account ID", - }, - "by_id": { - Type: schema.TypeInt, - Optional: true, - Description: "Find by ID", - }, - "name": { - Type: schema.TypeString, - Optional: true, - Description: "Find by name", - }, - "network": { - Type: schema.TypeString, - Optional: true, - }, - "vlan_id": { - Type: schema.TypeInt, - Optional: true, - Description: "Find by VLAN ID", - }, - "vnfdev_id": { - Type: schema.TypeInt, - Optional: true, - Description: "Find by VnfDEV ID", - }, - "status": { - Type: schema.TypeString, - Optional: true, - Description: "Find by status", - }, - "page": { - Type: schema.TypeInt, - Optional: true, - Description: "Page number", - }, - "size": { - Type: schema.TypeInt, - Optional: true, - Description: "Page size", - }, - "items": { - Type: schema.TypeList, - Computed: true, - Elem: &schema.Resource{ - Schema: map[string]*schema.Schema{ - "net_id": { - Type: schema.TypeInt, - Computed: true, - }, - "ipcidr": { - Type: schema.TypeString, - Computed: true, - }, - "name": { - Type: schema.TypeString, - Computed: true, - }, - }, - }, - }, - "entry_count": { - Type: schema.TypeInt, - Computed: true, - }, - } - return res -} - -func DataSourceExtnetList() *schema.Resource { - return &schema.Resource{ - SchemaVersion: 1, - - ReadContext: dataSourceExtnetListRead, - - Timeouts: &schema.ResourceTimeout{ - Read: &constants.Timeout30s, - Default: &constants.Timeout60s, - }, - - Schema: dataSourceExtnetListSchemaMake(), - } -} +/* +Copyright (c) 2019-2022 Digital Energy Cloud Solutions LLC. All Rights Reserved. +Authors: +Petr Krutov, +Stanislav Solovev, +Kasim Baybikov, + +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 + +import ( + "context" + + "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" +) + +func dataSourceExtnetListRead(ctx context.Context, d *schema.ResourceData, m interface{}) diag.Diagnostics { + extnetList, err := utilityExtnetListCheckPresence(ctx, d, m) + if err != nil { + d.SetId("") + return diag.FromErr(err) + } + + id := uuid.New() + d.SetId(id.String()) + d.Set("items", flattenExtnetList(extnetList)) + d.Set("entry_count", extnetList.EntryCount) + + return nil +} + +func dataSourceExtnetListSchemaMake() map[string]*schema.Schema { + res := map[string]*schema.Schema{ + "account_id": { + Type: schema.TypeInt, + Optional: true, + Description: "Find by account ID", + }, + "by_id": { + Type: schema.TypeInt, + Optional: true, + Description: "Find by ID", + }, + "name": { + Type: schema.TypeString, + Optional: true, + Description: "Find by name", + }, + "network": { + Type: schema.TypeString, + Optional: true, + }, + "vlan_id": { + Type: schema.TypeInt, + Optional: true, + Description: "Find by VLAN ID", + }, + "vnfdev_id": { + Type: schema.TypeInt, + Optional: true, + Description: "Find by VnfDEV ID", + }, + "status": { + Type: schema.TypeString, + Optional: true, + Description: "Find by status", + }, + "page": { + Type: schema.TypeInt, + Optional: true, + Description: "Page number", + }, + "size": { + Type: schema.TypeInt, + Optional: true, + Description: "Page size", + }, + "items": { + Type: schema.TypeList, + Computed: true, + Elem: &schema.Resource{ + Schema: map[string]*schema.Schema{ + "net_id": { + Type: schema.TypeInt, + Computed: true, + }, + "ipcidr": { + Type: schema.TypeString, + Computed: true, + }, + "name": { + Type: schema.TypeString, + Computed: true, + }, + "status": { + Type: schema.TypeString, + Computed: true, + }, + }, + }, + }, + "entry_count": { + Type: schema.TypeInt, + Computed: true, + }, + } + return res +} + +func DataSourceExtnetList() *schema.Resource { + return &schema.Resource{ + SchemaVersion: 1, + + ReadContext: dataSourceExtnetListRead, + + Timeouts: &schema.ResourceTimeout{ + Read: &constants.Timeout30s, + Default: &constants.Timeout60s, + }, + + Schema: dataSourceExtnetListSchemaMake(), + } +} diff --git a/internal/service/cloudapi/extnet/flattens.go b/internal/service/cloudapi/extnet/flattens.go index a0377d9..d074bee 100644 --- a/internal/service/cloudapi/extnet/flattens.go +++ b/internal/service/cloudapi/extnet/flattens.go @@ -92,7 +92,7 @@ func flattenExtnetVNFS(evnfs extnet.VNFs) []map[string]interface{} { } func flattenExtnetsComputes(ecs extnet.ListExtNetExtends) []map[string]interface{} { - res := make([]map[string]interface{}, 0, len (ecs)) + res := make([]map[string]interface{}, 0, len(ecs)) for _, ec := range ecs { temp := map[string]interface{}{ "net_id": ec.ID, @@ -129,6 +129,7 @@ func flattenExtnetList(el *extnet.ListExtNets) []map[string]interface{} { "net_id": e.ID, "ipcidr": e.IPCIDR, "name": e.Name, + "status": e.Status, } res = append(res, temp) } diff --git a/internal/service/cloudapi/flipgroup/data_source_flipgroup.go b/internal/service/cloudapi/flipgroup/data_source_flipgroup.go index 8d93f60..759d554 100644 --- a/internal/service/cloudapi/flipgroup/data_source_flipgroup.go +++ b/internal/service/cloudapi/flipgroup/data_source_flipgroup.go @@ -66,6 +66,10 @@ func dataSourceFlipgroupSchemaMake() map[string]*schema.Schema { Type: schema.TypeInt, Computed: true, }, + "account_name": { + Type: schema.TypeString, + Computed: true, + }, "client_ids": { Type: schema.TypeList, Computed: true, @@ -85,10 +89,26 @@ func dataSourceFlipgroupSchemaMake() map[string]*schema.Schema { Type: schema.TypeString, Computed: true, }, + "created_by": { + Type: schema.TypeString, + Computed: true, + }, + "created_time": { + Type: schema.TypeInt, + Computed: true, + }, "default_gw": { Type: schema.TypeString, Computed: true, }, + "deleted_by": { + Type: schema.TypeString, + Computed: true, + }, + "deleted_time": { + Type: schema.TypeInt, + Computed: true, + }, "desc": { Type: schema.TypeString, Computed: true, @@ -121,18 +141,30 @@ func dataSourceFlipgroupSchemaMake() map[string]*schema.Schema { Type: schema.TypeString, Computed: true, }, - "status": { + "network": { Type: schema.TypeString, Computed: true, }, - "net_mask": { + "rg_id": { Type: schema.TypeInt, Computed: true, }, - "ckey": { + "rg_name": { + Type: schema.TypeString, + Computed: true, + }, + "status": { Type: schema.TypeString, Computed: true, }, + "updated_by": { + Type: schema.TypeString, + Computed: true, + }, + "updated_time": { + Type: schema.TypeInt, + Computed: true, + }, } } diff --git a/internal/service/cloudapi/flipgroup/data_source_flipgroup_list.go b/internal/service/cloudapi/flipgroup/data_source_flipgroup_list.go index b81ea25..fa0cde0 100644 --- a/internal/service/cloudapi/flipgroup/data_source_flipgroup_list.go +++ b/internal/service/cloudapi/flipgroup/data_source_flipgroup_list.go @@ -185,6 +185,13 @@ func dataSourceFlipgroupListSchemaMake() map[string]*schema.Schema { Type: schema.TypeString, Computed: true, }, + "meta": { + Type: schema.TypeList, + Computed: true, + Elem: &schema.Schema{ + Type: schema.TypeString, + }, + }, }, }, }, diff --git a/internal/service/cloudapi/flipgroup/flattens.go b/internal/service/cloudapi/flipgroup/flattens.go index a95ccfd..abe66f6 100644 --- a/internal/service/cloudapi/flipgroup/flattens.go +++ b/internal/service/cloudapi/flipgroup/flattens.go @@ -36,15 +36,21 @@ package flipgroup import ( "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" "repository.basistech.ru/BASIS/decort-golang-sdk/pkg/cloudapi/flipgroup" + "repository.basistech.ru/BASIS/terraform-provider-decort/internal/flattens" ) func flattenFlipgroup(d *schema.ResourceData, fg *flipgroup.RecordFLIPGroup) { d.Set("account_id", fg.AccountID) + d.Set("account_name", fg.AccountName) d.Set("client_ids", fg.ClientIDs) d.Set("client_type", fg.ClientType) d.Set("conn_id", fg.ConnID) d.Set("conn_type", fg.ConnType) + d.Set("created_by", fg.CreatedBy) + d.Set("created_time", fg.CreatedTime) d.Set("default_gw", fg.DefaultGW) + d.Set("deleted_by", fg.DeletedBy) + d.Set("deleted_time", fg.DeletedTime) d.Set("desc", fg.Description) d.Set("gid", fg.GID) d.Set("guid", fg.GUID) @@ -54,13 +60,20 @@ func flattenFlipgroup(d *schema.ResourceData, fg *flipgroup.RecordFLIPGroup) { d.Set("name", fg.Name) d.Set("net_id", fg.NetID) d.Set("net_type", fg.NetType) + d.Set("network", fg.Network) + d.Set("rg_id", fg.RGID) + d.Set("rg_name", fg.RGName) d.Set("status", fg.Status) + d.Set("updated_by", fg.UpdatedBy) + d.Set("updated_time", fg.UpdatedTime) } func flattenFlipgroupList(fg_list *flipgroup.ListFLIPGroups) []map[string]interface{} { res := make([]map[string]interface{}, 0) for _, fg := range fg_list.Data { temp := map[string]interface{}{ + "ckey": fg.CKey, + "meta": flattens.FlattenMeta(fg.Meta), "account_id": fg.AccountID, "client_ids": fg.ClientIDs, "client_type": fg.ClientType, @@ -76,6 +89,7 @@ func flattenFlipgroupList(fg_list *flipgroup.ListFLIPGroups) []map[string]interf "name": fg.Name, "net_id": fg.NetID, "net_type": fg.NetType, + "net_mask": fg.NetMask, "status": fg.Status, } res = append(res, temp) diff --git a/internal/service/cloudapi/flipgroup/resource_flipgroup.go b/internal/service/cloudapi/flipgroup/resource_flipgroup.go index 7add9b7..bc43028 100644 --- a/internal/service/cloudapi/flipgroup/resource_flipgroup.go +++ b/internal/service/cloudapi/flipgroup/resource_flipgroup.go @@ -64,6 +64,7 @@ func resourceFlipgroupCreate(ctx context.Context, d *schema.ResourceData, m inte resp, err := c.CloudAPI().FLIPGroup().Create(ctx, req) if err != nil { + d.SetId("") return diag.FromErr(err) } @@ -136,6 +137,7 @@ func resourceFlipgroupDelete(ctx context.Context, d *schema.ResourceData, m inte fg, err := utilityFlipgroupCheckPresence(ctx, d, m) if err != nil { + d.SetId("") return diag.FromErr(err) } @@ -148,6 +150,8 @@ func resourceFlipgroupDelete(ctx context.Context, d *schema.ResourceData, m inte return diag.FromErr(err) } + d.SetId("") + return nil } @@ -205,6 +209,10 @@ func resourceFlipgroupSchemaMake() map[string]*schema.Schema { Type: schema.TypeInt, Computed: true, }, + "account_name": { + Type: schema.TypeString, + Computed: true, + }, "conn_id": { Type: schema.TypeInt, Computed: true, @@ -213,10 +221,26 @@ func resourceFlipgroupSchemaMake() map[string]*schema.Schema { Type: schema.TypeString, Computed: true, }, + "created_by": { + Type: schema.TypeString, + Computed: true, + }, + "created_time": { + Type: schema.TypeInt, + Computed: true, + }, "default_gw": { Type: schema.TypeString, Computed: true, }, + "deleted_by": { + Type: schema.TypeString, + Computed: true, + }, + "deleted_time": { + Type: schema.TypeInt, + Computed: true, + }, "gid": { Type: schema.TypeInt, Computed: true, @@ -233,14 +257,26 @@ func resourceFlipgroupSchemaMake() map[string]*schema.Schema { Type: schema.TypeString, Computed: true, }, - "net_mask": { + "network": { + Type: schema.TypeString, + Computed: true, + }, + "rg_id": { Type: schema.TypeInt, Computed: true, }, - "ckey": { + "rg_name": { Type: schema.TypeString, Computed: true, }, + "updated_by": { + Type: schema.TypeString, + Computed: true, + }, + "updated_time": { + Type: schema.TypeInt, + Computed: true, + }, } } diff --git a/internal/service/cloudapi/image/data_source_image.go b/internal/service/cloudapi/image/data_source_image.go index 3fa6894..3a55ef4 100644 --- a/internal/service/cloudapi/image/data_source_image.go +++ b/internal/service/cloudapi/image/data_source_image.go @@ -34,8 +34,8 @@ package image 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" @@ -44,12 +44,11 @@ import ( func dataSourceImageRead(ctx context.Context, d *schema.ResourceData, m interface{}) diag.Diagnostics { image, err := utilityImageCheckPresence(ctx, d, m) if err != nil { - + d.SetId("") return diag.FromErr(err) } - id := uuid.New() - d.SetId(id.String()) + d.SetId(strconv.Itoa(int(image.ID))) flattenImage(d, image) diff --git a/internal/service/cloudapi/image/data_source_image_list.go b/internal/service/cloudapi/image/data_source_image_list.go index b1fea5c..58438c6 100644 --- a/internal/service/cloudapi/image/data_source_image_list.go +++ b/internal/service/cloudapi/image/data_source_image_list.go @@ -1,159 +1,160 @@ -/* -Copyright (c) 2019-2022 Digital Energy Cloud Solutions LLC. All Rights Reserved. -Authors: -Petr Krutov, -Stanislav Solovev, -Kasim Baybikov, - -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 - -import ( - "context" - - "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" -) - -func dataSourceImageListRead(ctx context.Context, d *schema.ResourceData, m interface{}) diag.Diagnostics { - imageList, err := utilityImageListCheckPresence(ctx, d, m) - if err != nil { - return diag.FromErr(err) - } - id := uuid.New() - d.SetId(id.String()) - d.Set("items", flattenImageList(imageList)) - d.Set("entry_count", imageList.EntryCount) - - return nil -} - -func dataSourceImageListSchemaMake() map[string]*schema.Schema { - rets := map[string]*schema.Schema{ - "sep_id": { - Type: schema.TypeInt, - Optional: true, - Description: "Filter by Storage Endpoint ID", - }, - "by_id": { - Type: schema.TypeInt, - Optional: true, - Description: "Filter by ID", - }, - "name": { - Type: schema.TypeString, - Optional: true, - Description: "Filter by name", - }, - "status": { - Type: schema.TypeString, - Optional: true, - Description: "Filter by status", - }, - "architecture": { - Type: schema.TypeString, - Optional: true, - Description: "Filter by architecture", - }, - "type_image": { - Type: schema.TypeString, - Optional: true, - Description: "Filter by image type", - }, - "image_size": { - Type: schema.TypeInt, - Optional: true, - Description: "Filter by image size", - }, - "sep_name": { - Type: schema.TypeString, - Optional: true, - Description: "Filter by SEP name", - }, - "pool": { - Type: schema.TypeString, - Optional: true, - Description: "Filter by pool", - }, - "public": { - Type: schema.TypeBool, - Optional: true, - Description: "Find public/private images", - }, - "hot_resize": { - Type: schema.TypeBool, - Optional: true, - Description: "Find hot resizable images", - }, - "bootable": { - Type: schema.TypeBool, - Optional: true, - Description: "Find bootable images", - }, - "page": { - Type: schema.TypeInt, - Optional: true, - Description: "page number", - }, - "size": { - Type: schema.TypeInt, - Optional: true, - Description: "page size", - }, - "items": { - Type: schema.TypeList, - Computed: true, - Description: "image list", - Elem: &schema.Resource{ - Schema: dataSourceImageSchemaMake(), - }, - }, - "entry_count": { - Type: schema.TypeInt, - Computed: true, - }, - } - - return rets -} - -func DataSourceImageList() *schema.Resource { - return &schema.Resource{ - SchemaVersion: 1, - - ReadContext: dataSourceImageListRead, - - Timeouts: &schema.ResourceTimeout{ - Read: &constants.Timeout30s, - Default: &constants.Timeout60s, - }, - - Schema: dataSourceImageListSchemaMake(), - } -} +/* +Copyright (c) 2019-2022 Digital Energy Cloud Solutions LLC. All Rights Reserved. +Authors: +Petr Krutov, +Stanislav Solovev, +Kasim Baybikov, + +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 + +import ( + "context" + + "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" +) + +func dataSourceImageListRead(ctx context.Context, d *schema.ResourceData, m interface{}) diag.Diagnostics { + imageList, err := utilityImageListCheckPresence(ctx, d, m) + if err != nil { + d.SetId("") + return diag.FromErr(err) + } + id := uuid.New() + d.SetId(id.String()) + d.Set("items", flattenImageList(imageList)) + d.Set("entry_count", imageList.EntryCount) + + return nil +} + +func dataSourceImageListSchemaMake() map[string]*schema.Schema { + rets := map[string]*schema.Schema{ + "sep_id": { + Type: schema.TypeInt, + Optional: true, + Description: "Filter by Storage Endpoint ID", + }, + "by_id": { + Type: schema.TypeInt, + Optional: true, + Description: "Filter by ID", + }, + "name": { + Type: schema.TypeString, + Optional: true, + Description: "Filter by name", + }, + "status": { + Type: schema.TypeString, + Optional: true, + Description: "Filter by status", + }, + "architecture": { + Type: schema.TypeString, + Optional: true, + Description: "Filter by architecture", + }, + "type_image": { + Type: schema.TypeString, + Optional: true, + Description: "Filter by image type", + }, + "image_size": { + Type: schema.TypeInt, + Optional: true, + Description: "Filter by image size", + }, + "sep_name": { + Type: schema.TypeString, + Optional: true, + Description: "Filter by SEP name", + }, + "pool": { + Type: schema.TypeString, + Optional: true, + Description: "Filter by pool", + }, + "public": { + Type: schema.TypeBool, + Optional: true, + Description: "Find public/private images", + }, + "hot_resize": { + Type: schema.TypeBool, + Optional: true, + Description: "Find hot resizable images", + }, + "bootable": { + Type: schema.TypeBool, + Optional: true, + Description: "Find bootable images", + }, + "page": { + Type: schema.TypeInt, + Optional: true, + Description: "page number", + }, + "size": { + Type: schema.TypeInt, + Optional: true, + Description: "page size", + }, + "items": { + Type: schema.TypeList, + Computed: true, + Description: "image list", + Elem: &schema.Resource{ + Schema: dataSourceImageSchemaMake(), + }, + }, + "entry_count": { + Type: schema.TypeInt, + Computed: true, + }, + } + + return rets +} + +func DataSourceImageList() *schema.Resource { + return &schema.Resource{ + SchemaVersion: 1, + + ReadContext: dataSourceImageListRead, + + Timeouts: &schema.ResourceTimeout{ + Read: &constants.Timeout30s, + Default: &constants.Timeout60s, + }, + + Schema: dataSourceImageListSchemaMake(), + } +} diff --git a/internal/service/cloudapi/image/flattens.go b/internal/service/cloudapi/image/flattens.go index bd47fed..8288f99 100644 --- a/internal/service/cloudapi/image/flattens.go +++ b/internal/service/cloudapi/image/flattens.go @@ -3,6 +3,7 @@ package image import ( "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" "repository.basistech.ru/BASIS/decort-golang-sdk/pkg/cloudapi/image" + "strconv" ) func flattenHistory(history []image.History) []map[string]interface{} { @@ -23,7 +24,7 @@ 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("acl", FlattenACL(img.ACL)) d.Set("architecture", img.Architecture) d.Set("boot_type", img.BootType) d.Set("bootable", img.Bootable) @@ -85,3 +86,18 @@ func flattenImageList(il *image.ListImages) []map[string]interface{} { } return res } + +func FlattenACL(acl interface{}) string { + switch d := acl.(type) { + case string: + return d + case int: + return strconv.Itoa(d) + case int64: + return strconv.FormatInt(d, 10) + case float64: + return strconv.FormatInt(int64(d), 10) + default: + return "" + } +} diff --git a/internal/service/cloudapi/image/resource_image.go b/internal/service/cloudapi/image/resource_image.go index 68bd7a8..035ef5e 100644 --- a/internal/service/cloudapi/image/resource_image.go +++ b/internal/service/cloudapi/image/resource_image.go @@ -1,274 +1,276 @@ -/* -Copyright (c) 2019-2022 Digital Energy Cloud Solutions LLC. All Rights Reserved. -Authors: -Petr Krutov, -Stanislav Solovev, -Kasim Baybikov, - -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 - -import ( - "context" - "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" -) - -func resourceImageCreate(ctx context.Context, d *schema.ResourceData, m interface{}) diag.Diagnostics { - log.Debugf("resourceImageCreate: called for image %s", d.Get("name").(string)) - - haveGID, err := existGID(ctx, d, m) - if err != nil { - return diag.FromErr(err) - } - - if !haveGID { - return diag.Errorf("resourceImageCreate: can't create Image because GID %d is not allowed or does not exist", d.Get("gid").(int)) - } - - if _, ok := d.GetOk("account_id"); ok { - haveAccountID, err := existAccountID(ctx, d, m) - if err != nil { - return diag.FromErr(err) - } - - if !haveAccountID { - return diag.Errorf("resourceImageCreate: can't create Image because AccountID %d is not allowed or does not exist", d.Get("account_id").(int)) - } - } - - c := m.(*controller.ControllerCfg) - req := image.CreateRequest{} - - 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)) - } - - req.Drivers = drivers - - if hotresize, ok := d.GetOk("hot_resize"); ok { - req.HotResize = hotresize.(bool) - } - if username, ok := d.GetOk("username"); ok { - req.Username = username.(string) - } - if password, ok := d.GetOk("password"); ok { - req.Password = password.(string) - } - if accountId, ok := d.GetOk("account_id"); ok { - req.AccountID = uint64(accountId.(int)) - } - if usernameDL, ok := d.GetOk("username_dl"); ok { - req.UsernameDL = usernameDL.(string) - } - if passwordDL, ok := d.GetOk("password_dl"); ok { - req.PasswordDL = passwordDL.(string) - } - if sepId, ok := d.GetOk("sep_id"); ok { - req.SEPID = uint64(sepId.(int)) - } - if poolName, ok := d.GetOk("pool_name"); ok { - req.Pool = poolName.(string) - } - if architecture, ok := d.GetOk("architecture"); ok { - req.Architecture = architecture.(string) - } - - imageId, err := c.CloudAPI().Image().Create(ctx, req) - if err != nil { - return diag.FromErr(err) - } - - d.SetId(strconv.FormatUint(imageId, 10)) - d.Set("image_id", imageId) - - _, err = utilityImageCheckPresence(ctx, d, m) - if err != nil { - return diag.FromErr(err) - } - - return resourceImageRead(ctx, d, m) -} - -func resourceImageRead(ctx context.Context, d *schema.ResourceData, m interface{}) diag.Diagnostics { - log.Debugf("resourceImageRead: called for %s id: %s", d.Get("name").(string), d.Id()) - - img, err := utilityImageCheckPresence(ctx, d, m) - if img == nil { - d.SetId("") - return diag.FromErr(err) - } - - switch img.Status { - case status.Modeled: - return diag.Errorf("The image is in status: %s, please, contact support for more information", img.Status) - case status.Creating: - case status.Created: - case status.Destroyed, status.Purged: - d.SetId("") - return diag.Errorf("The resource cannot be updated because it has been destroyed") - // return resourceImageCreate(ctx, d, m) - } - - flattenImage(d, img) - - return nil -} - -func resourceImageDelete(ctx context.Context, d *schema.ResourceData, m interface{}) diag.Diagnostics { - log.Debugf("resourceImageDelete: called for %s, id: %s", d.Get("name").(string), d.Id()) - - _, 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 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) - 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 - } - - return nil -} - -func resourceImageUpdate(ctx context.Context, d *schema.ResourceData, m interface{}) diag.Diagnostics { - log.Debugf("resourceImageUpdate: called for %s, id: %s", d.Get("name").(string), d.Id()) - - haveGID, err := existGID(ctx, d, m) - if err != nil { - return diag.FromErr(err) - } - - if !haveGID { - return diag.Errorf("resourceImageUpdate: can't update Image because GID %d is not allowed or does not exist", d.Get("gid").(int)) - } - - if _, ok := d.GetOk("account_id"); ok { - haveAccountID, err := existAccountID(ctx, d, m) - if err != nil { - return diag.FromErr(err) - } - - if !haveAccountID { - return diag.Errorf("resourceImageUpdate: can't update Image because AccountID %d is not allowed or does not exist", d.Get("account_id").(int)) - } - } - - image, err := utilityImageCheckPresence(ctx, d, m) - if image == nil { - if err != nil { - return diag.FromErr(err) - } - return nil - } - - switch image.Status { - case status.Modeled: - return diag.Errorf("The image is in status: %s, please, contact support for more information", image.Status) - case status.Creating: - case status.Created: - case status.Destroyed, status.Purged: - d.SetId("") - return diag.Errorf("The resource cannot be updated because it has been destroyed") - // return resourceImageCreate(ctx, d, m) - } - - if d.HasChange("name") { - err := resourceImageRename(ctx, d, m) - if err != nil { - return diag.FromErr(err) - } - } - - return resourceImageRead(ctx, d, m) -} - -func ResourceImage() *schema.Resource { - return &schema.Resource{ - SchemaVersion: 1, - - CreateContext: resourceImageCreate, - ReadContext: resourceImageRead, - UpdateContext: resourceImageUpdate, - DeleteContext: resourceImageDelete, - - Importer: &schema.ResourceImporter{ - StateContext: schema.ImportStatePassthroughContext, - }, - - Timeouts: &schema.ResourceTimeout{ - Create: &constants.Timeout600s, - Read: &constants.Timeout300s, - Update: &constants.Timeout300s, - Delete: &constants.Timeout300s, - Default: &constants.Timeout300s, - }, - - Schema: resourceImageSchemaMake(dataSourceImageExtendSchemaMake()), - } -} +/* +Copyright (c) 2019-2022 Digital Energy Cloud Solutions LLC. All Rights Reserved. +Authors: +Petr Krutov, +Stanislav Solovev, +Kasim Baybikov, + +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 + +import ( + "context" + "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" +) + +func resourceImageCreate(ctx context.Context, d *schema.ResourceData, m interface{}) diag.Diagnostics { + log.Debugf("resourceImageCreate: called for image %s", d.Get("name").(string)) + + haveGID, err := existGID(ctx, d, m) + if err != nil { + return diag.FromErr(err) + } + + if !haveGID { + return diag.Errorf("resourceImageCreate: can't create Image because GID %d is not allowed or does not exist", d.Get("gid").(int)) + } + + if _, ok := d.GetOk("account_id"); ok { + haveAccountID, err := existAccountID(ctx, d, m) + if err != nil { + return diag.FromErr(err) + } + + if !haveAccountID { + return diag.Errorf("resourceImageCreate: can't create Image because AccountID %d is not allowed or does not exist", d.Get("account_id").(int)) + } + } + + c := m.(*controller.ControllerCfg) + req := image.CreateRequest{} + + 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)) + } + + req.Drivers = drivers + + if hotresize, ok := d.GetOk("hot_resize"); ok { + req.HotResize = hotresize.(bool) + } + if username, ok := d.GetOk("username"); ok { + req.Username = username.(string) + } + if password, ok := d.GetOk("password"); ok { + req.Password = password.(string) + } + if accountId, ok := d.GetOk("account_id"); ok { + req.AccountID = uint64(accountId.(int)) + } + if usernameDL, ok := d.GetOk("username_dl"); ok { + req.UsernameDL = usernameDL.(string) + } + if passwordDL, ok := d.GetOk("password_dl"); ok { + req.PasswordDL = passwordDL.(string) + } + if sepId, ok := d.GetOk("sep_id"); ok { + req.SEPID = uint64(sepId.(int)) + } + if poolName, ok := d.GetOk("pool_name"); ok { + req.Pool = poolName.(string) + } + if architecture, ok := d.GetOk("architecture"); ok { + req.Architecture = architecture.(string) + } + + imageId, err := c.CloudAPI().Image().Create(ctx, req) + if err != nil { + d.SetId("") + return diag.FromErr(err) + } + + d.SetId(strconv.FormatUint(imageId, 10)) + d.Set("image_id", imageId) + + _, err = utilityImageCheckPresence(ctx, d, m) + if err != nil { + return diag.FromErr(err) + } + + return resourceImageRead(ctx, d, m) +} + +func resourceImageRead(ctx context.Context, d *schema.ResourceData, m interface{}) diag.Diagnostics { + log.Debugf("resourceImageRead: called for %s id: %s", d.Get("name").(string), d.Id()) + + img, err := utilityImageCheckPresence(ctx, d, m) + if img == nil { + d.SetId("") + return diag.FromErr(err) + } + + switch img.Status { + case status.Modeled: + return diag.Errorf("The image is in status: %s, please, contact support for more information", img.Status) + case status.Creating: + case status.Created: + case status.Destroyed, status.Purged: + d.SetId("") + return diag.Errorf("The resource cannot be updated because it has been destroyed") + // return resourceImageCreate(ctx, d, m) + } + + flattenImage(d, img) + + return nil +} + +func resourceImageDelete(ctx context.Context, d *schema.ResourceData, m interface{}) diag.Diagnostics { + log.Debugf("resourceImageDelete: called for %s, id: %s", d.Get("name").(string), d.Id()) + + _, err := utilityImageCheckPresence(ctx, d, m) + if err != nil { + d.SetId("") + 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 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) + 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 + } + + return nil +} + +func resourceImageUpdate(ctx context.Context, d *schema.ResourceData, m interface{}) diag.Diagnostics { + log.Debugf("resourceImageUpdate: called for %s, id: %s", d.Get("name").(string), d.Id()) + + haveGID, err := existGID(ctx, d, m) + if err != nil { + return diag.FromErr(err) + } + + if !haveGID { + return diag.Errorf("resourceImageUpdate: can't update Image because GID %d is not allowed or does not exist", d.Get("gid").(int)) + } + + if _, ok := d.GetOk("account_id"); ok { + haveAccountID, err := existAccountID(ctx, d, m) + if err != nil { + return diag.FromErr(err) + } + + if !haveAccountID { + return diag.Errorf("resourceImageUpdate: can't update Image because AccountID %d is not allowed or does not exist", d.Get("account_id").(int)) + } + } + + image, err := utilityImageCheckPresence(ctx, d, m) + if image == nil { + if err != nil { + return diag.FromErr(err) + } + return nil + } + + switch image.Status { + case status.Modeled: + return diag.Errorf("The image is in status: %s, please, contact support for more information", image.Status) + case status.Creating: + case status.Created: + case status.Destroyed, status.Purged: + d.SetId("") + return diag.Errorf("The resource cannot be updated because it has been destroyed") + // return resourceImageCreate(ctx, d, m) + } + + if d.HasChange("name") { + err := resourceImageRename(ctx, d, m) + if err != nil { + return diag.FromErr(err) + } + } + + return resourceImageRead(ctx, d, m) +} + +func ResourceImage() *schema.Resource { + return &schema.Resource{ + SchemaVersion: 1, + + CreateContext: resourceImageCreate, + ReadContext: resourceImageRead, + UpdateContext: resourceImageUpdate, + DeleteContext: resourceImageDelete, + + Importer: &schema.ResourceImporter{ + StateContext: schema.ImportStatePassthroughContext, + }, + + Timeouts: &schema.ResourceTimeout{ + Create: &constants.Timeout600s, + Read: &constants.Timeout300s, + Update: &constants.Timeout300s, + Delete: &constants.Timeout300s, + Default: &constants.Timeout300s, + }, + + Schema: resourceImageSchemaMake(dataSourceImageExtendSchemaMake()), + } +} diff --git a/internal/service/cloudapi/k8s/data_source_k8s.go b/internal/service/cloudapi/k8s/data_source_k8s.go index 98550f6..3bdd006 100644 --- a/internal/service/cloudapi/k8s/data_source_k8s.go +++ b/internal/service/cloudapi/k8s/data_source_k8s.go @@ -50,6 +50,7 @@ import ( func dataSourceK8sRead(ctx context.Context, d *schema.ResourceData, m interface{}) diag.Diagnostics { cluster, err := utilityDataK8sCheckPresence(ctx, d, m) if err != nil { + d.SetId("") return diag.FromErr(err) } d.SetId(strconv.FormatUint(cluster.ID, 10)) @@ -399,6 +400,10 @@ func dataSourceK8sSchemaMake() map[string]*schema.Schema { Type: schema.TypeString, Computed: true, }, + "network_plugin": { + Type: schema.TypeString, + Computed: true, + }, "rg_id": { Type: schema.TypeInt, Computed: true, diff --git a/internal/service/cloudapi/k8s/data_source_k8s_list.go b/internal/service/cloudapi/k8s/data_source_k8s_list.go index 72e16d5..82f7852 100644 --- a/internal/service/cloudapi/k8s/data_source_k8s_list.go +++ b/internal/service/cloudapi/k8s/data_source_k8s_list.go @@ -271,6 +271,10 @@ func createK8sListSchema() map[string]*schema.Schema { Type: schema.TypeString, Computed: true, }, + "network_plugin": { + Type: schema.TypeString, + Computed: true, + }, "rg_id": { Type: schema.TypeInt, Computed: true, diff --git a/internal/service/cloudapi/k8s/data_source_k8s_wg.go b/internal/service/cloudapi/k8s/data_source_k8s_wg.go index 79ac1bf..1ef9548 100644 --- a/internal/service/cloudapi/k8s/data_source_k8s_wg.go +++ b/internal/service/cloudapi/k8s/data_source_k8s_wg.go @@ -47,6 +47,7 @@ func dataSourceK8sWgRead(ctx context.Context, d *schema.ResourceData, m interfac wg, workersComputeList, err := utilityDataK8sWgCheckPresence(ctx, d, m) if err != nil { + d.SetId("") return diag.FromErr(err) } diff --git a/internal/service/cloudapi/k8s/data_source_k8s_wg_cloud_init.go b/internal/service/cloudapi/k8s/data_source_k8s_wg_cloud_init.go index cfa23d8..873940f 100644 --- a/internal/service/cloudapi/k8s/data_source_k8s_wg_cloud_init.go +++ b/internal/service/cloudapi/k8s/data_source_k8s_wg_cloud_init.go @@ -47,6 +47,7 @@ func dataSourceK8sWgCloudInitRead(ctx context.Context, d *schema.ResourceData, m metaData, err := utilityK8sWgCloudInitCheckPresence(ctx, d, m) if err != nil { + d.SetId("") return diag.FromErr(err) } diff --git a/internal/service/cloudapi/k8s/data_source_k8s_wg_list.go b/internal/service/cloudapi/k8s/data_source_k8s_wg_list.go index 6025ac7..427a069 100644 --- a/internal/service/cloudapi/k8s/data_source_k8s_wg_list.go +++ b/internal/service/cloudapi/k8s/data_source_k8s_wg_list.go @@ -45,6 +45,7 @@ import ( func dataSourceK8sWgListRead(ctx context.Context, d *schema.ResourceData, m interface{}) diag.Diagnostics { wgList, err := utilityK8sWgListCheckPresence(ctx, d, m) if err != nil { + d.SetId("") return diag.FromErr(err) } diff --git a/internal/service/cloudapi/k8s/flattens.go b/internal/service/cloudapi/k8s/flattens.go index c016c5f..5700660 100644 --- a/internal/service/cloudapi/k8s/flattens.go +++ b/internal/service/cloudapi/k8s/flattens.go @@ -106,7 +106,7 @@ func flattenWorkerComputes(cluster *k8s.RecordK8S) []map[string]interface{} { } func flattenAclList(aclList k8s.ListACL) []map[string]interface{} { - res := make([]map[string]interface{}, 0, len (aclList)) + res := make([]map[string]interface{}, 0, len(aclList)) for _, acl := range aclList { temp := map[string]interface{}{ "explicit": acl.Explicit, @@ -134,7 +134,7 @@ func flattenAcl(acl k8s.RecordACL) []map[string]interface{} { } func flattenInterfaces(interfaces compute.ListInterfaces) []map[string]interface{} { - res := make([]map[string]interface{}, 0, len (interfaces)) + res := make([]map[string]interface{}, 0, len(interfaces)) for _, interfaceCompute := range interfaces { temp := map[string]interface{}{ "def_gw": interfaceCompute.DefGW, @@ -147,7 +147,7 @@ func flattenInterfaces(interfaces compute.ListInterfaces) []map[string]interface } func flattenDetailedInfo(detailedInfoList k8s.ListDetailedInfo, computes []compute.RecordCompute) []map[string]interface{} { - res := make([]map[string]interface{}, 0, len (detailedInfoList)) + res := make([]map[string]interface{}, 0, len(detailedInfoList)) if computes != nil { for i, detailedInfo := range detailedInfoList { temp := map[string]interface{}{ @@ -247,6 +247,7 @@ func flattenK8sData(d *schema.ResourceData, cluster k8s.RecordK8S, masters []com d.Set("workers", flattenK8sGroup(cluster.K8SGroups.Workers, workers)) d.Set("lb_id", cluster.LBID) d.Set("name", cluster.Name) + d.Set("network_plugin", cluster.NetworkPlugin) d.Set("rg_id", cluster.RGID) d.Set("rg_name", cluster.RGName) d.Set("status", cluster.Status) @@ -267,7 +268,7 @@ func flattenServiceAccount(serviceAccount k8s.RecordServiceAccount) []map[string } func flattenWorkersGroup(workersGroups k8s.ListK8SGroups) []map[string]interface{} { - res := make([]map[string]interface{}, 0, len (workersGroups)) + res := make([]map[string]interface{}, 0, len(workersGroups)) for _, worker := range workersGroups { temp := map[string]interface{}{ "annotations": worker.Annotations, @@ -288,11 +289,11 @@ func flattenWorkersGroup(workersGroups k8s.ListK8SGroups) []map[string]interface } func flattenK8sItems(k8sItems *k8s.ListK8SClusters) []map[string]interface{} { - res := make([]map[string]interface{}, 0, len (k8sItems.Data)) + res := make([]map[string]interface{}, 0, len(k8sItems.Data)) for _, item := range k8sItems.Data { temp := map[string]interface{}{ "account_id": item.AccountID, - "account_name": item.Name, + "account_name": item.AccountName, "acl": item.ACL, "bservice_id": item.BServiceID, "ci_id": item.CIID, @@ -308,6 +309,7 @@ func flattenK8sItems(k8sItems *k8s.ListK8SClusters) []map[string]interface{} { "lb_id": item.LBID, "milestones": item.Milestones, "k8s_name": item.Name, + "network_plugin": item.NetworkPlugin, "rg_id": item.RGID, "rg_name": item.RGName, "service_account": flattenServiceAccount(item.ServiceAccount), diff --git a/internal/service/cloudapi/k8s/node_subresource.go b/internal/service/cloudapi/k8s/node_subresource.go index 8fb1d2d..0afdf61 100644 --- a/internal/service/cloudapi/k8s/node_subresource.go +++ b/internal/service/cloudapi/k8s/node_subresource.go @@ -85,21 +85,21 @@ func mastersSchemaMake() map[string]*schema.Schema { Optional: true, } masters["cpu"] = &schema.Schema{ - Type: schema.TypeInt, - Required: true, - ForceNew: true, + Type: schema.TypeInt, + Required: true, + //ForceNew: true, Description: "Node CPU count.", } masters["ram"] = &schema.Schema{ - Type: schema.TypeInt, - Required: true, - ForceNew: true, + Type: schema.TypeInt, + Required: true, + //ForceNew: true, Description: "Node RAM in MB.", } masters["disk"] = &schema.Schema{ - Type: schema.TypeInt, - Required: true, - ForceNew: true, + Type: schema.TypeInt, + Required: true, + //ForceNew: true, Description: "Node boot disk size in GB.", } diff --git a/internal/service/cloudapi/k8s/old_schemas.go b/internal/service/cloudapi/k8s/old_schemas.go index 1554046..09db0a0 100644 --- a/internal/service/cloudapi/k8s/old_schemas.go +++ b/internal/service/cloudapi/k8s/old_schemas.go @@ -14,15 +14,15 @@ func resourceK8sCPSchemaV1() *schema.Resource { Description: "Name of the cluster.", }, "rg_id": { - Type: schema.TypeInt, - Required: true, - ForceNew: true, + Type: schema.TypeInt, + Required: true, + //ForceNew: true, Description: "Resource group ID that this instance belongs to.", }, "k8sci_id": { - Type: schema.TypeInt, - Required: true, - ForceNew: true, + Type: schema.TypeInt, + Required: true, + //ForceNew: true, Description: "ID of the k8s catalog item to base this instance on.", }, "network_plugin": { @@ -136,10 +136,10 @@ func resourceK8sCPSchemaV1() *schema.Resource { }, //// "extnet_id": { - Type: schema.TypeInt, - Optional: true, - Computed: true, - ForceNew: true, + Type: schema.TypeInt, + Optional: true, + Computed: true, + //ForceNew: true, Description: "ID of the external network to connect workers to. If omitted network will be chosen by the platfom.", }, "desc": { diff --git a/internal/service/cloudapi/k8s/resource_k8s.go b/internal/service/cloudapi/k8s/resource_k8s.go index 119bce5..848af76 100644 --- a/internal/service/cloudapi/k8s/resource_k8s.go +++ b/internal/service/cloudapi/k8s/resource_k8s.go @@ -211,6 +211,7 @@ func resourceK8sCreate(ctx context.Context, d *schema.ResourceData, m interface{ resp, err := c.CloudAPI().K8S().Create(ctx, createReq) if err != nil { + d.SetId("") return diag.FromErr(err) } @@ -316,7 +317,7 @@ func resourceK8sRead(ctx context.Context, d *schema.ResourceData, m interface{}) } } - k8sList, err := utilityK8sListCheckPresence(ctx, d, m) + k8sList, err := utilityK8sListForResourceCheckPresence(ctx, d, m) if err != nil { d.SetId("") return diag.FromErr(err) @@ -515,7 +516,7 @@ func resourceK8sUpdate(ctx context.Context, d *schema.ResourceData, m interface{ } } - return nil + return resourceK8sRead(ctx, d, m) } func resourceK8sDelete(ctx context.Context, d *schema.ResourceData, m interface{}) diag.Diagnostics { @@ -548,15 +549,15 @@ func resourceK8sSchemaMake() map[string]*schema.Schema { Description: "Name of the cluster.", }, "rg_id": { - Type: schema.TypeInt, - Required: true, - ForceNew: true, + Type: schema.TypeInt, + Required: true, + //ForceNew: true, Description: "Resource group ID that this instance belongs to.", }, "k8sci_id": { - Type: schema.TypeInt, - Required: true, - ForceNew: true, + Type: schema.TypeInt, + Required: true, + //ForceNew: true, Description: "ID of the k8s catalog item to base this instance on.", }, "wg_name": { @@ -595,7 +596,7 @@ func resourceK8sSchemaMake() map[string]*schema.Schema { Type: schema.TypeList, Optional: true, Computed: true, - ForceNew: true, + //ForceNew: true, MaxItems: 1, Elem: &schema.Resource{ Schema: mastersSchemaMake(), @@ -624,10 +625,10 @@ func resourceK8sSchemaMake() map[string]*schema.Schema { Description: "Use only selected ExtNet for infrastructure connections", }, "extnet_id": { - Type: schema.TypeInt, - Optional: true, - Computed: true, - ForceNew: true, + Type: schema.TypeInt, + Optional: true, + Computed: true, + //ForceNew: true, Description: "ID of the external network to connect workers to. If omitted network will be chosen by the platfom.", }, diff --git a/internal/service/cloudapi/k8s/resource_k8s_cp.go b/internal/service/cloudapi/k8s/resource_k8s_cp.go index 1e3ca0d..f1d105e 100644 --- a/internal/service/cloudapi/k8s/resource_k8s_cp.go +++ b/internal/service/cloudapi/k8s/resource_k8s_cp.go @@ -197,6 +197,7 @@ func resourceK8sCPCreate(ctx context.Context, d *schema.ResourceData, m interfac resp, err := c.CloudAPI().K8S().Create(ctx, createReq) if err != nil { + d.SetId("") return diag.FromErr(err) } @@ -317,7 +318,7 @@ func resourceK8sCPRead(ctx context.Context, d *schema.ResourceData, m interface{ } } - k8sList, err := utilityK8sListCheckPresence(ctx, d, m) + k8sList, err := utilityK8sListForResourceCheckPresence(ctx, d, m) if err != nil { d.SetId("") return diag.FromErr(err) @@ -532,7 +533,7 @@ func resourceK8sCPUpdate(ctx context.Context, d *schema.ResourceData, m interfac } } - return nil + return resourceK8sCPRead(ctx, d, m) } func resourceK8sCPDelete(ctx context.Context, d *schema.ResourceData, m interface{}) diag.Diagnostics { @@ -540,6 +541,7 @@ func resourceK8sCPDelete(ctx context.Context, d *schema.ResourceData, m interfac cluster, err := utilityK8sCheckPresence(ctx, d, m) if err != nil { + d.SetId("") return diag.FromErr(err) } @@ -554,6 +556,8 @@ func resourceK8sCPDelete(ctx context.Context, d *schema.ResourceData, m interfac return diag.FromErr(err) } + d.SetId("") + return nil } @@ -565,15 +569,15 @@ func resourceK8sCPSchemaMake() map[string]*schema.Schema { Description: "Name of the cluster.", }, "rg_id": { - Type: schema.TypeInt, - Required: true, - ForceNew: true, + Type: schema.TypeInt, + Required: true, + //ForceNew: true, Description: "Resource group ID that this instance belongs to.", }, "k8sci_id": { - Type: schema.TypeInt, - Required: true, - ForceNew: true, + Type: schema.TypeInt, + Required: true, + //ForceNew: true, Description: "ID of the k8s catalog item to base this instance on.", }, "network_plugin": { @@ -681,10 +685,10 @@ func resourceK8sCPSchemaMake() map[string]*schema.Schema { }, //// "extnet_id": { - Type: schema.TypeInt, - Optional: true, - Computed: true, - ForceNew: true, + Type: schema.TypeInt, + Optional: true, + Computed: true, + //ForceNew: true, Description: "ID of the external network to connect workers to. If omitted network will be chosen by the platfom.", }, "desc": { diff --git a/internal/service/cloudapi/k8s/resource_k8s_wg.go b/internal/service/cloudapi/k8s/resource_k8s_wg.go index 0951cd8..c376956 100644 --- a/internal/service/cloudapi/k8s/resource_k8s_wg.go +++ b/internal/service/cloudapi/k8s/resource_k8s_wg.go @@ -201,7 +201,7 @@ func resourceK8sWgUpdate(ctx context.Context, d *schema.ResourceData, m interfac } } - return nil + return resourceK8sWgRead(ctx, d, m) } func resourceK8sWgDelete(ctx context.Context, d *schema.ResourceData, m interface{}) diag.Diagnostics { @@ -209,6 +209,7 @@ func resourceK8sWgDelete(ctx context.Context, d *schema.ResourceData, m interfac wg, err := utilityK8sWgCheckPresence(ctx, d, m) if err != nil { + d.SetId("") return diag.FromErr(err) } @@ -223,22 +224,24 @@ func resourceK8sWgDelete(ctx context.Context, d *schema.ResourceData, m interfac return diag.FromErr(err) } + d.SetId("") + return nil } func resourceK8sWgSchemaMake() map[string]*schema.Schema { return map[string]*schema.Schema{ "k8s_id": { - Type: schema.TypeInt, - Required: true, - ForceNew: true, + Type: schema.TypeInt, + Required: true, + //ForceNew: true, Description: "ID of k8s instance.", }, "name": { - Type: schema.TypeString, - Required: true, - ForceNew: true, + Type: schema.TypeString, + Required: true, + //ForceNew: true, Description: "Name of the worker group.", }, @@ -250,17 +253,17 @@ func resourceK8sWgSchemaMake() map[string]*schema.Schema { }, "cpu": { - Type: schema.TypeInt, - Optional: true, - ForceNew: true, + Type: schema.TypeInt, + Optional: true, + //ForceNew: true, Default: 1, Description: "Worker node CPU count.", }, "ram": { - Type: schema.TypeInt, - Optional: true, - ForceNew: true, + Type: schema.TypeInt, + Optional: true, + //ForceNew: true, Default: 1024, Description: "Worker node RAM in MB.", }, diff --git a/internal/service/cloudapi/k8s/utility_k8s.go b/internal/service/cloudapi/k8s/utility_k8s.go index 8674e27..855c248 100644 --- a/internal/service/cloudapi/k8s/utility_k8s.go +++ b/internal/service/cloudapi/k8s/utility_k8s.go @@ -273,7 +273,22 @@ func utilityK8sListCheckPresence(ctx context.Context, d *schema.ResourceData, m req.Size = uint64(size.(int)) } + k8sList, err := c.CloudAPI().K8S().List(ctx, req) + if err != nil { + return nil, err + } + + return k8sList, nil +} +func utilityK8sListForResourceCheckPresence(ctx context.Context, d *schema.ResourceData, m interface{}) (*k8s.ListK8SClusters, error) { + c := m.(*controller.ControllerCfg) + req := k8s.ListRequest{ + IncludeDeleted: false, + } + if name, ok := d.GetOk("name"); ok { + req.Name = name.(string) + } k8sList, err := c.CloudAPI().K8S().List(ctx, req) if err != nil { return nil, err diff --git a/internal/service/cloudapi/kvmvm/data_source_compute.go b/internal/service/cloudapi/kvmvm/data_source_compute.go index 0901174..3c9196d 100644 --- a/internal/service/cloudapi/kvmvm/data_source_compute.go +++ b/internal/service/cloudapi/kvmvm/data_source_compute.go @@ -54,6 +54,7 @@ func findInExtraDisks(DiskId uint, ExtraDisks []interface{}) bool { func dataSourceComputeRead(ctx context.Context, d *schema.ResourceData, m interface{}) diag.Diagnostics { compute, err := utilityDataComputeCheckPresence(ctx, d, m) if err != nil { + d.SetId("") return diag.FromErr(err) } d.SetId(strconv.Itoa(int(compute.ID))) @@ -290,6 +291,10 @@ func computeListDisksSchemaMake() map[string]*schema.Schema { Type: schema.TypeInt, Computed: true, }, + "image_name": { + Type: schema.TypeString, + Computed: true, + }, "images": { Type: schema.TypeList, Computed: true, @@ -444,6 +449,10 @@ func computeInterfacesSchemaMake() map[string]*schema.Schema { Type: schema.TypeString, Computed: true, }, + "enabled": { + Type: schema.TypeBool, + Computed: true, + }, "flip_group_id": { Type: schema.TypeInt, Computed: true, diff --git a/internal/service/cloudapi/kvmvm/data_source_compute_audits.go b/internal/service/cloudapi/kvmvm/data_source_compute_audits.go index 59b109f..b8390bd 100644 --- a/internal/service/cloudapi/kvmvm/data_source_compute_audits.go +++ b/internal/service/cloudapi/kvmvm/data_source_compute_audits.go @@ -44,6 +44,7 @@ import ( func dataSourceComputeAuditsRead(ctx context.Context, d *schema.ResourceData, m interface{}) diag.Diagnostics { computeAudits, err := utilityComputeAuditsCheckPresence(ctx, d, m) if err != nil { + d.SetId("") return diag.FromErr(err) } id := uuid.New() diff --git a/internal/service/cloudapi/kvmvm/data_source_compute_get_audits.go b/internal/service/cloudapi/kvmvm/data_source_compute_get_audits.go index c43cca6..4bee35a 100644 --- a/internal/service/cloudapi/kvmvm/data_source_compute_get_audits.go +++ b/internal/service/cloudapi/kvmvm/data_source_compute_get_audits.go @@ -44,6 +44,7 @@ import ( func dataSourceComputeGetAuditsRead(ctx context.Context, d *schema.ResourceData, m interface{}) diag.Diagnostics { computeAudits, err := utilityComputeGetAuditsCheckPresence(ctx, d, m) if err != nil { + d.SetId("") return diag.FromErr(err) } id := uuid.New() diff --git a/internal/service/cloudapi/kvmvm/data_source_compute_get_console_url.go b/internal/service/cloudapi/kvmvm/data_source_compute_get_console_url.go index 5be7989..992d11e 100644 --- a/internal/service/cloudapi/kvmvm/data_source_compute_get_console_url.go +++ b/internal/service/cloudapi/kvmvm/data_source_compute_get_console_url.go @@ -45,12 +45,13 @@ import ( func dataSourceComputeGetConsoleUrlRead(ctx context.Context, d *schema.ResourceData, m interface{}) diag.Diagnostics { computeConsoleUrl, err := utilityComputeGetConsoleUrlCheckPresence(ctx, d, m) if err != nil { + d.SetId("") return diag.FromErr(err) } id := uuid.New() d.SetId(id.String()) - result := strings.ReplaceAll(string(computeConsoleUrl), "\"", "") - result = strings.ReplaceAll(string(result), "\\", "") + result := strings.ReplaceAll(computeConsoleUrl, "\"", "") + result = strings.ReplaceAll(result, "\\", "") d.Set("console_url", result) return nil } diff --git a/internal/service/cloudapi/kvmvm/data_source_compute_get_log.go b/internal/service/cloudapi/kvmvm/data_source_compute_get_log.go index 839e1d4..7235d3e 100644 --- a/internal/service/cloudapi/kvmvm/data_source_compute_get_log.go +++ b/internal/service/cloudapi/kvmvm/data_source_compute_get_log.go @@ -44,6 +44,7 @@ import ( func dataSourceComputeGetLogRead(ctx context.Context, d *schema.ResourceData, m interface{}) diag.Diagnostics { computeGetLog, err := utilityComputeGetLogCheckPresence(ctx, d, m) if err != nil { + d.SetId("") return diag.FromErr(err) } id := uuid.New() diff --git a/internal/service/cloudapi/kvmvm/data_source_compute_list.go b/internal/service/cloudapi/kvmvm/data_source_compute_list.go index 32f38e4..f6ea70d 100644 --- a/internal/service/cloudapi/kvmvm/data_source_compute_list.go +++ b/internal/service/cloudapi/kvmvm/data_source_compute_list.go @@ -44,6 +44,7 @@ import ( func dataSourceComputeListRead(ctx context.Context, d *schema.ResourceData, m interface{}) diag.Diagnostics { computeList, err := utilityDataComputeListCheckPresence(ctx, d, m) if err != nil { + d.SetId("") return diag.FromErr(err) } diff --git a/internal/service/cloudapi/kvmvm/data_source_compute_list_deleted.go b/internal/service/cloudapi/kvmvm/data_source_compute_list_deleted.go index 7dd2b3a..5d68d52 100644 --- a/internal/service/cloudapi/kvmvm/data_source_compute_list_deleted.go +++ b/internal/service/cloudapi/kvmvm/data_source_compute_list_deleted.go @@ -44,6 +44,7 @@ import ( func dataSourceComputeListDeletedRead(ctx context.Context, d *schema.ResourceData, m interface{}) diag.Diagnostics { computeList, err := utilityDataComputeListDeletedCheckPresence(ctx, d, m) if err != nil { + d.SetId("") return diag.FromErr(err) } diff --git a/internal/service/cloudapi/kvmvm/data_source_compute_pci_device_list.go b/internal/service/cloudapi/kvmvm/data_source_compute_pci_device_list.go index 37ec08b..d0573b8 100644 --- a/internal/service/cloudapi/kvmvm/data_source_compute_pci_device_list.go +++ b/internal/service/cloudapi/kvmvm/data_source_compute_pci_device_list.go @@ -44,6 +44,7 @@ import ( func dataSourceComputePCIDeviceListRead(ctx context.Context, d *schema.ResourceData, m interface{}) diag.Diagnostics { computePCIDeviceList, err := utilityComputePCIDeviceListCheckPresence(ctx, d, m) if err != nil { + d.SetId("") return diag.FromErr(err) } id := uuid.New() @@ -80,13 +81,13 @@ func dataSourceComputePCIDeviceListSchemaMake() map[string]*schema.Schema { Description: "Find by status", }, "page": { - Type: schema.TypeInt, - Optional: true, + Type: schema.TypeInt, + Optional: true, Description: "Page number", }, "size": { - Type: schema.TypeInt, - Optional: true, + Type: schema.TypeInt, + Optional: true, Description: "Page size", }, "items": { diff --git a/internal/service/cloudapi/kvmvm/data_source_compute_pfw_list.go b/internal/service/cloudapi/kvmvm/data_source_compute_pfw_list.go index 2e8e2e5..1b85be0 100644 --- a/internal/service/cloudapi/kvmvm/data_source_compute_pfw_list.go +++ b/internal/service/cloudapi/kvmvm/data_source_compute_pfw_list.go @@ -44,6 +44,7 @@ import ( func dataSourceComputePfwListRead(ctx context.Context, d *schema.ResourceData, m interface{}) diag.Diagnostics { computePfwList, err := utilityComputePfwListCheckPresence(ctx, d, m) if err != nil { + d.SetId("") return diag.FromErr(err) } id := uuid.New() diff --git a/internal/service/cloudapi/kvmvm/data_source_compute_snapshot_usage.go b/internal/service/cloudapi/kvmvm/data_source_compute_snapshot_usage.go index 3b7c7c4..e3a4c44 100644 --- a/internal/service/cloudapi/kvmvm/data_source_compute_snapshot_usage.go +++ b/internal/service/cloudapi/kvmvm/data_source_compute_snapshot_usage.go @@ -12,6 +12,7 @@ import ( func dataSourceComputeSnapshotUsageRead(ctx context.Context, d *schema.ResourceData, m interface{}) diag.Diagnostics { computeSnapshotUsage, err := utilityComputeSnapshotUsageCheckPresence(ctx, d, m) if err != nil { + d.SetId("") return diag.FromErr(err) } id := uuid.New() diff --git a/internal/service/cloudapi/kvmvm/data_source_compute_user_list.go b/internal/service/cloudapi/kvmvm/data_source_compute_user_list.go index 921a307..c523db6 100644 --- a/internal/service/cloudapi/kvmvm/data_source_compute_user_list.go +++ b/internal/service/cloudapi/kvmvm/data_source_compute_user_list.go @@ -44,6 +44,7 @@ import ( func dataSourceComputeUserListRead(ctx context.Context, d *schema.ResourceData, m interface{}) diag.Diagnostics { computeUserList, err := utilityComputeUserListCheckPresence(ctx, d, m) if err != nil { + d.SetId("") return diag.FromErr(err) } id := uuid.New() diff --git a/internal/service/cloudapi/kvmvm/data_source_compute_vgpu_list.go b/internal/service/cloudapi/kvmvm/data_source_compute_vgpu_list.go index 876b3d1..dc789f6 100644 --- a/internal/service/cloudapi/kvmvm/data_source_compute_vgpu_list.go +++ b/internal/service/cloudapi/kvmvm/data_source_compute_vgpu_list.go @@ -44,6 +44,7 @@ import ( func dataSourceComputeVGPUListRead(ctx context.Context, d *schema.ResourceData, m interface{}) diag.Diagnostics { computeVGPUList, err := utilityComputeVGPUListCheckPresence(ctx, d, m) if err != nil { + d.SetId("") return diag.FromErr(err) } id := uuid.New() @@ -75,18 +76,18 @@ func dataSourceComputeVGPUListSchemaMake() map[string]*schema.Schema { Description: "Find by status", }, "includedeleted": { - Type: schema.TypeBool, - Optional: true, + Type: schema.TypeBool, + Optional: true, Description: "Include deleted computes. If using field 'status', then includedeleted will be ignored", }, "page": { - Type: schema.TypeInt, - Optional: true, + Type: schema.TypeInt, + Optional: true, Description: "Page number", }, "size": { - Type: schema.TypeInt, - Optional: true, + Type: schema.TypeInt, + Optional: true, Description: "Page size", }, "items": { @@ -94,7 +95,6 @@ func dataSourceComputeVGPUListSchemaMake() map[string]*schema.Schema { Computed: true, Elem: &schema.Schema{ Type: schema.TypeString, - }, }, "entry_count": { diff --git a/internal/service/cloudapi/kvmvm/flattens.go b/internal/service/cloudapi/kvmvm/flattens.go index 98a5e30..180cd25 100644 --- a/internal/service/cloudapi/kvmvm/flattens.go +++ b/internal/service/cloudapi/kvmvm/flattens.go @@ -72,6 +72,7 @@ func flattenInterfaces(interfaces compute.ListInterfaces) []map[string]interface "conn_id": interfaceItem.ConnID, "conn_type": interfaceItem.ConnType, "def_gw": interfaceItem.DefGW, + "enabled": interfaceItem.Enabled, "flip_group_id": interfaceItem.FLIPGroupID, "guid": interfaceItem.GUID, "ip_address": interfaceItem.IPAddress, @@ -362,7 +363,7 @@ func flattenCompute(d *schema.ResourceData, computeRec compute.RecordCompute) er 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("tags", flattenTags(computeRec.Tags)) d.Set("tech_status", computeRec.TechStatus) d.Set("updated_by", computeRec.UpdatedBy) d.Set("updated_time", computeRec.UpdatedTime) @@ -554,6 +555,7 @@ func flattenDataCompute(d *schema.ResourceData, computeRec compute.RecordCompute d.Set("guid", computeRec.GUID) d.Set("compute_id", computeRec.ID) d.Set("image_id", computeRec.ImageID) + d.Set("image_name", computeRec.ImageName) d.Set("interfaces", flattenInterfaces(computeRec.Interfaces)) d.Set("lock_status", computeRec.LockStatus) d.Set("manager_id", computeRec.ManagerID) @@ -653,19 +655,19 @@ func flattenSnapshotUsage(computeSnapshotUsages compute.ListUsageSnapshots) []ma return res } -func flattenSnapshotList(computeSnapshotUsages *compute.ListSnapShots) []map[string]interface{} { - res := make([]map[string]interface{}, 0, len(computeSnapshotUsages.Data)) - for _, computeUsage := range computeSnapshotUsages.Data { - temp := map[string]interface{}{ - "disks": computeUsage.Disks, - "guid": computeUsage.GUID, - "label": computeUsage.Label, - "timestamp": computeUsage.Timestamp, - } - res = append(res, temp) - } - return res -} +// func flattenSnapshotList(computeSnapshotUsages *compute.ListSnapShots) []map[string]interface{} { +// res := make([]map[string]interface{}, 0, len(computeSnapshotUsages.Data)) +// for _, computeUsage := range computeSnapshotUsages.Data { +// temp := map[string]interface{}{ +// "disks": computeUsage.Disks, +// "guid": computeUsage.GUID, +// "label": computeUsage.Label, +// "timestamp": computeUsage.Timestamp, +// } +// res = append(res, temp) +// } +// return res +// } func flattenVGPU(m []interface{}) []string { output := []string{} @@ -703,4 +705,4 @@ func flattenPCIDevice(m []interface{}) []string { } } return output -} \ No newline at end of file +} diff --git a/internal/service/cloudapi/kvmvm/resource_compute.go b/internal/service/cloudapi/kvmvm/resource_compute.go index d799ebf..667a15f 100644 --- a/internal/service/cloudapi/kvmvm/resource_compute.go +++ b/internal/service/cloudapi/kvmvm/resource_compute.go @@ -155,6 +155,32 @@ func resourceComputeCreate(ctx context.Context, d *schema.ResourceData, m interf } } + createReqPPC.Interfaces = make([]kvmppc.Interface, 0) + + if networks, ok := d.GetOk("network"); ok { + if networks.(*schema.Set).Len() > 0 { + ns := networks.(*schema.Set).List() + + interfaces := make([]kvmppc.Interface, 0) + for _, elem := range ns { + netInterfaceVal := elem.(map[string]interface{}) + reqInterface := kvmppc.Interface{ + NetType: netInterfaceVal["net_type"].(string), + NetID: uint64(netInterfaceVal["net_id"].(int)), + } + + ipaddr, ipSet := netInterfaceVal["ip_address"] + if ipSet { + reqInterface.IPAddr = ipaddr.(string) + } + + interfaces = append(interfaces, reqInterface) + } + + createReqPPC.Interfaces = interfaces + } + } + argVal, ok = d.GetOk("cloud_init") if ok { userdata := argVal.(string) @@ -242,33 +268,79 @@ func resourceComputeCreate(ctx context.Context, d *schema.ResourceData, m interf } } - // Note bene: we created compute in a STOPPED state (this is required to properly attach 1st network interface), - // now we need to start it before we report the sequence complete - if d.Get("started").(bool) { - req := compute.StartRequest{ComputeID: computeId} - log.Debugf("resourceComputeCreate: starting Compute ID %d after completing its resource configuration", computeId) - if _, err := c.CloudAPI().Compute().Start(ctx, req); err != nil { - warnings.Add(err) + if disks, ok := d.GetOk("disks"); ok { + log.Debugf("resourceComputeCreate: Create disks on ComputeID: %d", computeId) + addedDisks := disks.([]interface{}) + if len(addedDisks) > 0 { + for _, disk := range addedDisks { + diskConv := disk.(map[string]interface{}) + req := compute.DiskAddRequest{ + ComputeID: computeId, + DiskName: diskConv["disk_name"].(string), + Size: uint64(diskConv["size"].(int)), + } + + if diskConv["sep_id"].(int) != 0 { + req.SepID = uint64(diskConv["sep_id"].(int)) + } + if diskConv["disk_type"].(string) != "" { + req.DiskType = diskConv["disk_type"].(string) + } + if diskConv["pool"].(string) != "" { + req.Pool = diskConv["pool"].(string) + } + if diskConv["desc"].(string) != "" { + req.Description = diskConv["desc"].(string) + } + if diskConv["image_id"].(int) != 0 { + req.ImageID = uint64(diskConv["image_id"].(int)) + } + + _, err := c.CloudAPI().Compute().DiskAdd(ctx, req) + if err != nil { + cleanup = true + return diag.FromErr(err) + } + } } } - if enabled, ok := d.GetOk("enabled"); ok { - if enabled.(bool) { - req := compute.EnableRequest{ComputeID: computeId} - log.Debugf("resourceComputeCreate: enable=%t Compute ID %d after completing its resource configuration", enabled, computeId) - if _, err := c.CloudAPI().Compute().Enable(ctx, req); err != nil { - warnings.Add(err) + if !cleanup { + if enabled, ok := d.GetOk("enabled"); ok { + if enabled.(bool) { + req := compute.EnableRequest{ComputeID: computeId} + log.Debugf("resourceComputeCreate: enable=%t Compute ID %d after completing its resource configuration", enabled, computeId) + if _, err := c.CloudAPI().Compute().Enable(ctx, req); err != nil { + warnings.Add(err) + } + } else { + req := compute.DisableRequest{ComputeID: computeId} + log.Debugf("resourceComputeCreate: enable=%t Compute ID %d after completing its resource configuration", enabled, computeId) + if _, err := c.CloudAPI().Compute().Disable(ctx, req); err != nil { + warnings.Add(err) + } } - } else { - req := compute.DisableRequest{ComputeID: computeId} - log.Debugf("resourceComputeCreate: enable=%t Compute ID %d after completing its resource configuration", enabled, computeId) - if _, err := c.CloudAPI().Compute().Disable(ctx, req); err != nil { - warnings.Add(err) + } + + // Note bene: we created compute in a STOPPED state (this is required to properly attach 1st network interface), + // now we need to start it before we report the sequence complete + if start, ok := d.GetOk("started"); ok { + if start.(bool) { + req := compute.StartRequest{ComputeID: computeId} + log.Debugf("resourceComputeCreate: starting Compute ID %d after completing its resource configuration", computeId) + if _, err := c.CloudAPI().Compute().Start(ctx, req); err != nil { + warnings.Add(err) + } + } + if !start.(bool) { + req := compute.StopRequest{ComputeID: computeId} + log.Debugf("resourceComputeCreate: stoping Compute ID %d after completing its resource configuration", computeId) + if _, err := c.CloudAPI().Compute().Stop(ctx, req); err != nil { + warnings.Add(err) + } } } - } - if !cleanup { if affinityLabel, ok := d.GetOk("affinity_label"); ok { req := compute.AffinityLabelSetRequest{ ComputeID: computeId, @@ -281,41 +353,6 @@ func resourceComputeCreate(ctx context.Context, d *schema.ResourceData, m interf } } - if disks, ok := d.GetOk("disks"); ok { - log.Debugf("resourceComputeCreate: Create disks on ComputeID: %d", computeId) - addedDisks := disks.([]interface{}) - if len(addedDisks) > 0 { - for _, disk := range addedDisks { - diskConv := disk.(map[string]interface{}) - req := compute.DiskAddRequest{ - ComputeID: computeId, - DiskName: diskConv["disk_name"].(string), - Size: uint64(diskConv["size"].(int)), - SepID: uint64(diskConv["sep_id"].(int)), - } - - if diskConv["disk_type"].(string) != "" { - req.DiskType = diskConv["disk_type"].(string) - } - if diskConv["pool"].(string) != "" { - req.Pool = diskConv["pool"].(string) - } - if diskConv["desc"].(string) != "" { - req.Description = diskConv["desc"].(string) - } - if diskConv["image_id"].(int) != 0 { - req.ImageID = uint64(diskConv["image_id"].(int)) - } - - _, err := c.CloudAPI().Compute().DiskAdd(ctx, req) - if err != nil { - cleanup = true - return diag.FromErr(err) - } - } - } - } - if ars, ok := d.GetOk("affinity_rules"); ok { log.Debugf("resourceComputeCreate: Create affinity rules on ComputeID: %d", computeId) addedAR := ars.([]interface{}) @@ -361,133 +398,134 @@ func resourceComputeCreate(ctx context.Context, d *schema.ResourceData, m interf } } } - } - if tags, ok := d.GetOk("tags"); ok { - log.Debugf("resourceComputeCreate: Create tags on ComputeID: %d", computeId) - addedTags := tags.(*schema.Set).List() - if len(addedTags) > 0 { - for _, tagInterface := range addedTags { - tagItem := tagInterface.(map[string]interface{}) - req := compute.TagAddRequest{ - ComputeID: computeId, - Key: tagItem["key"].(string), - Value: tagItem["value"].(string), - } + if tags, ok := d.GetOk("tags"); ok { + log.Debugf("resourceComputeCreate: Create tags on ComputeID: %d", computeId) + addedTags := tags.(*schema.Set).List() + if len(addedTags) > 0 { + for _, tagInterface := range addedTags { + tagItem := tagInterface.(map[string]interface{}) + req := compute.TagAddRequest{ + ComputeID: computeId, + Key: tagItem["key"].(string), + Value: tagItem["value"].(string), + } - _, err := c.CloudAPI().Compute().TagAdd(ctx, req) - if err != nil { - warnings.Add(err) + _, err := c.CloudAPI().Compute().TagAdd(ctx, req) + if err != nil { + warnings.Add(err) + } } } } - } - if pfws, ok := d.GetOk("port_forwarding"); ok { - log.Debugf("resourceComputeCreate: Create port farwarding on ComputeID: %d", computeId) - addedPfws := pfws.(*schema.Set).List() - if len(addedPfws) > 0 { - for _, pfwInterface := range addedPfws { - pfwItem := pfwInterface.(map[string]interface{}) - req := compute.PFWAddRequest{ - ComputeID: computeId, - PublicPortStart: uint64(pfwItem["public_port_start"].(int)), - PublicPortEnd: int64(pfwItem["public_port_end"].(int)), - LocalBasePort: uint64(pfwItem["local_port"].(int)), - Proto: pfwItem["proto"].(string), - } + if pfws, ok := d.GetOk("port_forwarding"); ok { + log.Debugf("resourceComputeCreate: Create port farwarding on ComputeID: %d", computeId) + addedPfws := pfws.(*schema.Set).List() + if len(addedPfws) > 0 { + for _, pfwInterface := range addedPfws { + pfwItem := pfwInterface.(map[string]interface{}) + req := compute.PFWAddRequest{ + ComputeID: computeId, + PublicPortStart: uint64(pfwItem["public_port_start"].(int)), + LocalBasePort: uint64(pfwItem["local_port"].(int)), + Proto: pfwItem["proto"].(string), + } + if pfwItem["public_port_end"].(int) != 0 { + req.PublicPortEnd = int64(pfwItem["public_port_end"].(int)) + } - _, err := c.CloudAPI().Compute().PFWAdd(ctx, req) - if err != nil { - warnings.Add(err) + _, err := c.CloudAPI().Compute().PFWAdd(ctx, req) + if err != nil { + warnings.Add(err) + } } } } - } - if userAcess, ok := d.GetOk("user_access"); ok { - log.Debugf("resourceComputeCreate: Create user access on ComputeID: %d", computeId) - usersAcess := userAcess.(*schema.Set).List() - if len(usersAcess) > 0 { - for _, userAcessInterface := range usersAcess { - userAccessItem := userAcessInterface.(map[string]interface{}) - req := compute.UserGrantRequest{ - ComputeID: computeId, - Username: userAccessItem["username"].(string), - AccessType: userAccessItem["access_type"].(string), + + if userAcess, ok := d.GetOk("user_access"); ok { + log.Debugf("resourceComputeCreate: Create user access on ComputeID: %d", computeId) + usersAcess := userAcess.(*schema.Set).List() + if len(usersAcess) > 0 { + for _, userAcessInterface := range usersAcess { + userAccessItem := userAcessInterface.(map[string]interface{}) + req := compute.UserGrantRequest{ + ComputeID: computeId, + Username: userAccessItem["username"].(string), + AccessType: userAccessItem["access_type"].(string), + } + + _, err := c.CloudAPI().Compute().UserGrant(ctx, req) + if err != nil { + warnings.Add(err) + } } + } + } - _, err := c.CloudAPI().Compute().UserGrant(ctx, req) - if err != nil { - warnings.Add(err) + if snapshotList, ok := d.GetOk("snapshot"); ok { + log.Debugf("resourceComputeCreate: Create snapshot on ComputeID: %d", computeId) + snapshots := snapshotList.(*schema.Set).List() + if len(snapshots) > 0 { + for _, snapshotInterface := range snapshots { + snapshotItem := snapshotInterface.(map[string]interface{}) + req := compute.SnapshotCreateRequest{ + ComputeID: computeId, + Label: snapshotItem["label"].(string), + } + + _, err := c.CloudAPI().Compute().SnapshotCreate(ctx, req) + if err != nil { + warnings.Add(err) + } } } } - } - if snapshotList, ok := d.GetOk("snapshot"); ok { - log.Debugf("resourceComputeCreate: Create snapshot on ComputeID: %d", computeId) - snapshots := snapshotList.(*schema.Set).List() - if len(snapshots) > 0 { - for _, snapshotInterface := range snapshots { - snapshotItem := snapshotInterface.(map[string]interface{}) - req := compute.SnapshotCreateRequest{ + if cdtList, ok := d.GetOk("cd"); ok { + log.Debugf("resourceComputeCreate: Create cd on ComputeID: %d", computeId) + cds := cdtList.(*schema.Set).List() + if len(cds) > 0 { + snapshotItem := cds[0].(map[string]interface{}) + req := compute.CDInsertRequest{ ComputeID: computeId, - Label: snapshotItem["label"].(string), + CDROMID: uint64(snapshotItem["cdrom_id"].(int)), } - _, err := c.CloudAPI().Compute().SnapshotCreate(ctx, req) + _, err := c.CloudAPI().Compute().CDInsert(ctx, req) if err != nil { warnings.Add(err) } } } - } - if cdtList, ok := d.GetOk("cd"); ok { - log.Debugf("resourceComputeCreate: Create cd on ComputeID: %d", computeId) - cds := cdtList.(*schema.Set).List() - if len(cds) > 0 { - snapshotItem := cds[0].(map[string]interface{}) - req := compute.CDInsertRequest{ + if d.Get("pin_to_stack").(bool) { + req := compute.PinToStackRequest{ ComputeID: computeId, - CDROMID: uint64(snapshotItem["cdrom_id"].(int)), } - - _, err := c.CloudAPI().Compute().CDInsert(ctx, req) + _, err := c.CloudAPI().Compute().PinToStack(ctx, req) if err != nil { warnings.Add(err) } } - } - - if d.Get("pin_to_stack").(bool) == true { - req := compute.PinToStackRequest{ - ComputeID: computeId, - } - _, err := c.CloudAPI().Compute().PinToStack(ctx, req) - if err != nil { - warnings.Add(err) - } - } - if d.Get("pause").(bool) == true { - req := compute.PauseRequest{ - ComputeID: computeId, - } - _, err := c.CloudAPI().Compute().Pause(ctx, req) - if err != nil { - warnings.Add(err) + if d.Get("pause").(bool) { + req := compute.PauseRequest{ + ComputeID: computeId, + } + _, err := c.CloudAPI().Compute().Pause(ctx, req) + if err != nil { + warnings.Add(err) + } } } - log.Debugf("resourceComputeCreate: new Compute ID %d, name %s creation sequence complete", computeId, d.Get("name").(string)) // We may reuse dataSourceComputeRead here as we maintain similarity // between Compute resource and Compute data source schemas // Compute read function will also update resource ID on success, so that Terraform // will know the resource exists - defer resourceComputeRead(ctx, d, m) - return warnings.Get() + return append(warnings.Get(), resourceComputeRead(ctx, d, m)...) } func resourceComputeRead(ctx context.Context, d *schema.ResourceData, m interface{}) diag.Diagnostics { @@ -498,6 +536,7 @@ func resourceComputeRead(ctx context.Context, d *schema.ResourceData, m interfac computeRec, err := utilityComputeCheckPresence(ctx, d, m) if err != nil { + d.SetId("") return diag.FromErr(err) } @@ -601,6 +640,76 @@ func resourceComputeUpdate(ctx context.Context, d *schema.ResourceData, m interf return diag.FromErr(err) } + hasChanged := false + + // check compute statuses + switch computeRec.Status { + case status.Deleted: + if restore, ok := d.GetOk("restore"); ok && restore.(bool) { + restoreReq := compute.RestoreRequest{ComputeID: computeRec.ID} + _, err := c.CloudAPI().Compute().Restore(ctx, restoreReq) + if err != nil { + d.SetId("") + return diag.FromErr(err) + } + } + + if enabled, ok := d.GetOk("enabled"); ok { + if enabled.(bool) { + enableReq := compute.EnableRequest{ComputeID: computeRec.ID} + _, err = c.CloudAPI().Compute().Enable(ctx, enableReq) + if err != nil { + return diag.FromErr(err) + } + } + if !enabled.(bool) { + enableReq := compute.DisableRequest{ComputeID: computeRec.ID} + _, err = c.CloudAPI().Compute().Disable(ctx, enableReq) + if err != nil { + return diag.FromErr(err) + } + } + } + + if start, ok := d.GetOk("started"); ok { + if start.(bool) { + req := compute.StartRequest{ComputeID: computeRec.ID} + + if _, err := c.CloudAPI().Compute().Start(ctx, req); err != nil { + return diag.FromErr(err) + } + } + if !start.(bool) { + req := compute.StopRequest{ComputeID: computeRec.ID} + + if _, err := c.CloudAPI().Compute().Stop(ctx, req); err != nil { + return diag.FromErr(err) + } + } + } + + hasChanged = true + case status.Destroyed: + d.SetId("") + return diag.Errorf("The resource cannot be updated because it has been destroyed") + // return resourceComputeCreate(ctx, d, m) + case status.Disabled: + log.Debugf("The compute is in status: %s, may troubles can be occured with update. Please, enable compute first.", computeRec.Status) + case status.Redeploying: + case status.Deleting: + case status.Destroying: + return diag.Errorf("The compute is in progress with status: %s", computeRec.Status) + case status.Modeled: + return diag.Errorf("The compute is in status: %s, please, contant the support for more information", computeRec.Status) + } + + if hasChanged { + computeRec, err = utilityComputeCheckPresence(ctx, d, m) + if err != nil { + return diag.FromErr(err) + } + } + if d.HasChange("enabled") { enabled := d.Get("enabled").(bool) if enabled { @@ -623,34 +732,22 @@ func resourceComputeUpdate(ctx context.Context, d *schema.ResourceData, m interf log.Debugf("resourceComputeUpdate: enable=%s Compute ID %v after completing its resource configuration", d.Id(), enabled) } - // check compute statuses - switch computeRec.Status { - case status.Deleted: - restoreReq := compute.RestoreRequest{ComputeID: computeRec.ID} - enableReq := compute.EnableRequest{ComputeID: computeRec.ID} + if d.HasChange("started") { + start := d.Get("started").(bool) + if start { + req := compute.StartRequest{ComputeID: computeRec.ID} - _, err := c.CloudAPI().Compute().Restore(ctx, restoreReq) - if err != nil { - return diag.FromErr(err) + if _, err := c.CloudAPI().Compute().Start(ctx, req); err != nil { + return diag.FromErr(err) + } } + if !start { + req := compute.StopRequest{ComputeID: computeRec.ID} - _, err = c.CloudAPI().Compute().Enable(ctx, enableReq) - if err != nil { - return diag.FromErr(err) + if _, err := c.CloudAPI().Compute().Stop(ctx, req); err != nil { + return diag.FromErr(err) + } } - - case status.Destroyed: - d.SetId("") - return diag.Errorf("The resource cannot be updated because it has been destroyed") - // return resourceComputeCreate(ctx, d, m) - case status.Disabled: - log.Debugf("The compute is in status: %s, may troubles can be occured with update. Please, enable compute first.", computeRec.Status) - case status.Redeploying: - case status.Deleting: - case status.Destroying: - return diag.Errorf("The compute is in progress with status: %s", computeRec.Status) - case status.Modeled: - return diag.Errorf("The compute is in status: %s, please, contant the support for more information", computeRec.Status) } doUpdate := false @@ -729,14 +826,16 @@ func resourceComputeUpdate(ctx context.Context, d *schema.ResourceData, m interf } } - if d.HasChange("description") || d.HasChange("name") { + if d.HasChanges("description", "name") { req := compute.UpdateRequest{ ComputeID: computeRec.ID, - Name: d.Get("name").(string), } - if desc, ok := d.GetOk("description"); ok { - req.Description = desc.(string) + if d.HasChange("name") { + req.Name = d.Get("name").(string) + } + if d.HasChange("description") { + req.Description = d.Get("description").(string) } if _, err := c.CloudAPI().Compute().Update(ctx, req); err != nil { @@ -835,9 +934,11 @@ func resourceComputeUpdate(ctx context.Context, d *schema.ResourceData, m interf ComputeID: computeRec.ID, DiskName: diskConv["disk_name"].(string), Size: uint64(diskConv["size"].(int)), - SepID: uint64(diskConv["sep_id"].(int)), } + if diskConv["sep_id"].(int) != 0 { + req.SepID = uint64(diskConv["sep_id"].(int)) + } if diskConv["disk_type"].(string) != "" { req.DiskType = diskConv["disk_type"].(string) } @@ -1267,7 +1368,7 @@ func resourceComputeUpdate(ctx context.Context, d *schema.ResourceData, m interf if d.HasChange("pin_to_stack") { oldPin, newPin := d.GetChange("pin_to_stack") - if oldPin.(bool) == true && newPin.(bool) == false { + if !newPin.(bool) { req := compute.UnpinFromStackRequest{ ComputeID: computeRec.ID, } @@ -1277,7 +1378,7 @@ func resourceComputeUpdate(ctx context.Context, d *schema.ResourceData, m interf return diag.FromErr(err) } } - if oldPin.(bool) == false && newPin.(bool) == true { + if !oldPin.(bool) { req := compute.PinToStackRequest{ ComputeID: computeRec.ID, } @@ -1291,7 +1392,7 @@ func resourceComputeUpdate(ctx context.Context, d *schema.ResourceData, m interf if d.HasChange("pause") { oldPause, newPause := d.GetChange("pause") - if oldPause.(bool) == true && newPause.(bool) == false { + if !newPause.(bool) { req := compute.ResumeRequest{ ComputeID: computeRec.ID, } @@ -1300,7 +1401,7 @@ func resourceComputeUpdate(ctx context.Context, d *schema.ResourceData, m interf return diag.FromErr(err) } } - if oldPause.(bool) == false && newPause.(bool) == true { + if !oldPause.(bool) { req := compute.PauseRequest{ ComputeID: computeRec.ID, } @@ -1313,8 +1414,8 @@ func resourceComputeUpdate(ctx context.Context, d *schema.ResourceData, m interf } if d.HasChange("reset") { - oldReset, newReset := d.GetChange("reset") - if oldReset.(bool) == false && newReset.(bool) == true { + _, newReset := d.GetChange("reset") + if newReset.(bool) { req := compute.ResetRequest{ ComputeID: computeRec.ID, } @@ -1394,8 +1495,8 @@ func resourceComputeUpdate(ctx context.Context, d *schema.ResourceData, m interf // we may reuse dataSourceComputeRead here as we maintain similarity // between Compute resource and Compute data source schemas - defer resourceComputeRead(ctx, d, m) - return warnings.Get() + + return append(warnings.Get(), resourceComputeRead(ctx, d, m)...) } func isChangeDisk(els []interface{}, el interface{}) bool { @@ -1456,6 +1557,8 @@ func resourceComputeDelete(ctx context.Context, d *schema.ResourceData, m interf return diag.FromErr(err) } + d.SetId("") + return nil } @@ -1504,7 +1607,6 @@ func disksSubresourceSchemaMake() map[string]*schema.Schema { }, "permanently": { Type: schema.TypeBool, - Computed: true, Optional: true, Description: "Disk deletion status", }, @@ -1877,6 +1979,12 @@ func ResourceComputeSchemaMake() map[string]*schema.Schema { Default: false, }, + "restore": { + Type: schema.TypeBool, + Optional: true, + Default: false, + }, + "auto_start": { Type: schema.TypeBool, Optional: true, diff --git a/internal/service/cloudapi/kvmvm/utility_compute.go b/internal/service/cloudapi/kvmvm/utility_compute.go index 837eaeb..80bebf2 100644 --- a/internal/service/cloudapi/kvmvm/utility_compute.go +++ b/internal/service/cloudapi/kvmvm/utility_compute.go @@ -34,18 +34,17 @@ package kvmvm import ( "context" - "regexp" - "strconv" - log "github.com/sirupsen/logrus" + "regexp" "repository.basistech.ru/BASIS/decort-golang-sdk/pkg/cloudapi/compute" "repository.basistech.ru/BASIS/terraform-provider-decort/internal/controller" + "strconv" "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" ) func matchComputes(computeList *compute.ListComputes) *compute.ListComputes { - matched, _ := regexp.Compile("[a-zA-Z]+\\d+-[a-zA-Z]+\\d+-[a-zA-Z]+\\d+") + matched, _ := regexp.Compile(`[a-zA-Z]+\\d+-[a-zA-Z]+\\d+-[a-zA-Z]+\\d+`) result := computeList.FilterFunc(func(ic compute.ItemCompute) bool { res := matched.Match([]byte(ic.Name)) return !res @@ -176,17 +175,6 @@ func utilityComputeNetworksConfigure(ctx context.Context, d *schema.ResourceData old_set, new_set := d.GetChange("network") - req := compute.StopRequest{ - ComputeID: computeID, - Force: true, - } - - log.Debugf("utilityComputeNetworksConfigure: stopping compute %d", computeID) - _, err := c.CloudAPI().Compute().Stop(ctx, req) - if err != nil { - return err - } - apiErrCount := 0 var lastSavedError error @@ -246,6 +234,17 @@ func utilityComputeNetworksConfigure(ctx context.Context, d *schema.ResourceData } } + needStart := false + + if d.Get("network").(*schema.Set).Len() == 1 || old_set.(*schema.Set).Len() < 1 { + computeId, _ := strconv.ParseUint(d.Id(), 10, 64) + if err := utilityComputeStop(ctx, computeId, m); err != nil { + apiErrCount++ + lastSavedError = err + } + needStart = true + } + 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() { @@ -270,13 +269,12 @@ func utilityComputeNetworksConfigure(ctx context.Context, d *schema.ResourceData } } - startReq := compute.StartRequest{ComputeID: computeID} - - log.Debugf("utilityComputeNetworksConfigure: starting compute %d", computeID) - _, err = c.CloudAPI().Compute().Start(ctx, startReq) - if err != nil { - apiErrCount++ - lastSavedError = err + if needStart { + computeId, _ := strconv.ParseUint(d.Id(), 10, 64) + if numErr, err := utilityComputeStart(ctx, computeId, m); err != nil { + apiErrCount += numErr + lastSavedError = err + } } if apiErrCount > 0 { @@ -302,3 +300,30 @@ func utilityComputeCheckPresence(ctx context.Context, d *schema.ResourceData, m return *computeRecord, nil } + +func utilityComputeStop(ctx context.Context, computeID uint64, m interface{}) error { + c := m.(*controller.ControllerCfg) + req := compute.StopRequest{ + ComputeID: computeID, + Force: true, + } + + log.Debugf("utilityComputeNetworksConfigure: stopping compute %d", computeID) + _, err := c.CloudAPI().Compute().Stop(ctx, req) + if err != nil { + return err + } + return nil +} + +func utilityComputeStart(ctx context.Context, computeID uint64, m interface{}) (int, error) { + c := m.(*controller.ControllerCfg) + startReq := compute.StartRequest{ComputeID: computeID} + + log.Debugf("utilityComputeNetworksConfigure: starting compute %d", computeID) + _, err := c.CloudAPI().Compute().Start(ctx, startReq) + if err != nil { + return 1, err + } + return 0, nil +} diff --git a/internal/service/cloudapi/lb/data_source_lb.go b/internal/service/cloudapi/lb/data_source_lb.go index acbe98e..6d1a207 100644 --- a/internal/service/cloudapi/lb/data_source_lb.go +++ b/internal/service/cloudapi/lb/data_source_lb.go @@ -1,70 +1,71 @@ -/* -Copyright (c) 2019-2022 Digital Energy Cloud Solutions LLC. All Rights Reserved. -Authors: -Petr Krutov, -Stanislav Solovev, -Kasim Baybikov, - -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 lb - -import ( - "context" - "strconv" - - "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" -) - -func dataSourceLBRead(ctx context.Context, d *schema.ResourceData, m interface{}) diag.Diagnostics { - lb, err := utilityLBCheckPresence(ctx, d, m) - if err != nil { - return diag.FromErr(err) - } - - d.SetId(strconv.FormatUint(lb.ID, 10)) - - flattenLB(d, lb) - - return nil -} - -func DataSourceLB() *schema.Resource { - return &schema.Resource{ - SchemaVersion: 1, - - ReadContext: dataSourceLBRead, - - Timeouts: &schema.ResourceTimeout{ - Read: &constants.Timeout30s, - Default: &constants.Timeout60s, - }, - - Schema: dsLBSchemaMake(), - } -} +/* +Copyright (c) 2019-2022 Digital Energy Cloud Solutions LLC. All Rights Reserved. +Authors: +Petr Krutov, +Stanislav Solovev, +Kasim Baybikov, + +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 lb + +import ( + "context" + "strconv" + + "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" +) + +func dataSourceLBRead(ctx context.Context, d *schema.ResourceData, m interface{}) diag.Diagnostics { + lb, err := utilityLBCheckPresence(ctx, d, m) + if err != nil { + d.SetId("") + return diag.FromErr(err) + } + + d.SetId(strconv.FormatUint(lb.ID, 10)) + + flattenLB(d, lb) + + return nil +} + +func DataSourceLB() *schema.Resource { + return &schema.Resource{ + SchemaVersion: 1, + + ReadContext: dataSourceLBRead, + + Timeouts: &schema.ResourceTimeout{ + Read: &constants.Timeout30s, + Default: &constants.Timeout60s, + }, + + Schema: dsLBSchemaMake(), + } +} diff --git a/internal/service/cloudapi/lb/data_source_lb_list.go b/internal/service/cloudapi/lb/data_source_lb_list.go index 7547cc1..00aa6fd 100644 --- a/internal/service/cloudapi/lb/data_source_lb_list.go +++ b/internal/service/cloudapi/lb/data_source_lb_list.go @@ -1,70 +1,71 @@ -/* -Copyright (c) 2019-2022 Digital Energy Cloud Solutions LLC. All Rights Reserved. -Authors: -Petr Krutov, -Stanislav Solovev, -Kasim Baybikov, - -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 lb - -import ( - "context" - - "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" -) - -func dataSourceLBListRead(ctx context.Context, d *schema.ResourceData, m interface{}) diag.Diagnostics { - lbList, err := utilityLBListCheckPresence(ctx, d, m) - if err != nil { - return diag.FromErr(err) - } - id := uuid.New() - d.SetId(id.String()) - d.Set("items", flattenLBList(lbList)) - d.Set("entry_count", lbList.EntryCount) - - return nil -} - -func DataSourceLBList() *schema.Resource { - return &schema.Resource{ - SchemaVersion: 1, - - ReadContext: dataSourceLBListRead, - - Timeouts: &schema.ResourceTimeout{ - Read: &constants.Timeout30s, - Default: &constants.Timeout60s, - }, - - Schema: dsLBListSchemaMake(), - } -} +/* +Copyright (c) 2019-2022 Digital Energy Cloud Solutions LLC. All Rights Reserved. +Authors: +Petr Krutov, +Stanislav Solovev, +Kasim Baybikov, + +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 lb + +import ( + "context" + + "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" +) + +func dataSourceLBListRead(ctx context.Context, d *schema.ResourceData, m interface{}) diag.Diagnostics { + lbList, err := utilityLBListCheckPresence(ctx, d, m) + if err != nil { + d.SetId("") + return diag.FromErr(err) + } + id := uuid.New() + d.SetId(id.String()) + d.Set("items", flattenLBList(lbList)) + d.Set("entry_count", lbList.EntryCount) + + return nil +} + +func DataSourceLBList() *schema.Resource { + return &schema.Resource{ + SchemaVersion: 1, + + ReadContext: dataSourceLBListRead, + + Timeouts: &schema.ResourceTimeout{ + Read: &constants.Timeout30s, + Default: &constants.Timeout60s, + }, + + Schema: dsLBListSchemaMake(), + } +} diff --git a/internal/service/cloudapi/lb/data_source_lb_list_deleted.go b/internal/service/cloudapi/lb/data_source_lb_list_deleted.go index 23be1b4..3965590 100644 --- a/internal/service/cloudapi/lb/data_source_lb_list_deleted.go +++ b/internal/service/cloudapi/lb/data_source_lb_list_deleted.go @@ -1,70 +1,71 @@ -/* -Copyright (c) 2019-2022 Digital Energy Cloud Solutions LLC. All Rights Reserved. -Authors: -Petr Krutov, -Stanislav Solovev, -Kasim Baybikov, - -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 lb - -import ( - "context" - - "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" -) - -func dataSourceLBListDeletedRead(ctx context.Context, d *schema.ResourceData, m interface{}) diag.Diagnostics { - lbList, err := utilityLBListDeletedCheckPresence(ctx, d, m) - if err != nil { - return diag.FromErr(err) - } - id := uuid.New() - d.SetId(id.String()) - d.Set("items", flattenLBList(lbList)) - d.Set("entry_count", lbList.EntryCount) - - return nil -} - -func DataSourceLBListDeleted() *schema.Resource { - return &schema.Resource{ - SchemaVersion: 1, - - ReadContext: dataSourceLBListDeletedRead, - - Timeouts: &schema.ResourceTimeout{ - Read: &constants.Timeout30s, - Default: &constants.Timeout60s, - }, - - Schema: dsLBListDeletedSchemaMake(), - } -} +/* +Copyright (c) 2019-2022 Digital Energy Cloud Solutions LLC. All Rights Reserved. +Authors: +Petr Krutov, +Stanislav Solovev, +Kasim Baybikov, + +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 lb + +import ( + "context" + + "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" +) + +func dataSourceLBListDeletedRead(ctx context.Context, d *schema.ResourceData, m interface{}) diag.Diagnostics { + lbList, err := utilityLBListDeletedCheckPresence(ctx, d, m) + if err != nil { + d.SetId("") + return diag.FromErr(err) + } + id := uuid.New() + d.SetId(id.String()) + d.Set("items", flattenLBList(lbList)) + d.Set("entry_count", lbList.EntryCount) + + return nil +} + +func DataSourceLBListDeleted() *schema.Resource { + return &schema.Resource{ + SchemaVersion: 1, + + ReadContext: dataSourceLBListDeletedRead, + + Timeouts: &schema.ResourceTimeout{ + Read: &constants.Timeout30s, + Default: &constants.Timeout60s, + }, + + Schema: dsLBListDeletedSchemaMake(), + } +} diff --git a/internal/service/cloudapi/lb/resource_lb.go b/internal/service/cloudapi/lb/resource_lb.go index 7732e6d..38bd05d 100644 --- a/internal/service/cloudapi/lb/resource_lb.go +++ b/internal/service/cloudapi/lb/resource_lb.go @@ -1,432 +1,467 @@ -/* -Copyright (c) 2019-2022 Digital Energy Cloud Solutions LLC. All Rights Reserved. -Authors: -Petr Krutov, -Stanislav Solovev, -Kasim Baybikov, - -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 lb - -import ( - "context" - "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/lb" - "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" -) - -func resourceLBCreate(ctx context.Context, d *schema.ResourceData, m interface{}) diag.Diagnostics { - log.Debugf("resourceLBCreate") - - haveRGID, err := existRGID(ctx, d, m) - if err != nil { - return diag.FromErr(err) - } - - if !haveRGID { - return diag.Errorf("resourceLBCreate: can't create LB because RGID %d is not allowed or does not exist", d.Get("rg_id").(int)) - } - - haveExtNetID, err := existExtNetID(ctx, d, m) - if err != nil { - return diag.FromErr(err) - } - - if !haveExtNetID { - return diag.Errorf("resourceLBCreate: can't create LB because ExtNetID %d is not allowed or does not exist", d.Get("extnet_id").(int)) - } - - haveVins, err := existViNSID(ctx, d, m) - if err != nil { - return diag.FromErr(err) - } - - if !haveVins { - return diag.Errorf("resourceLBCreate: can't create LB because ViNSID %d is not allowed or does not exist", d.Get("vins_id").(int)) - } - - c := m.(*controller.ControllerCfg) - req := lb.CreateRequest{ - Name: d.Get("name").(string), - RGID: uint64(d.Get("rg_id").(int)), - ExtNetID: uint64(d.Get("extnet_id").(int)), - VINSID: uint64(d.Get("vins_id").(int)), - Start: d.Get("start").(bool), - } - - if desc, ok := d.GetOk("desc"); ok { - req.Description = desc.(string) - } - - if haMode, ok := d.GetOk("ha_mode"); ok { - req.HighlyAvailable = haMode.(bool) - } - - lbId, err := c.CloudAPI().LB().Create(ctx, req) - if err != nil { - return diag.FromErr(err) - } - - lbIdParsed := strconv.Itoa(int(lbId)) - - d.SetId(lbIdParsed) - d.Set("lb_id", lbId) - - _, err = utilityLBCheckPresence(ctx, d, m) - if err != nil { - return diag.FromErr(err) - } - - if enable, ok := d.GetOk("enable"); ok { - lbId := uint64(d.Get("lb_id").(int)) - req := lb.DisableEnableRequest{ - LBID: lbId, - } - - if enable.(bool) { - _, err := c.CloudAPI().LB().Enable(ctx, req) - if err != nil { - return diag.FromErr(err) - } - } else { - _, err := c.CloudAPI().LB().Disable(ctx, req) - if err != nil { - return diag.FromErr(err) - } - } - } - - return resourceLBRead(ctx, d, m) -} - -func resourceLBRead(ctx context.Context, d *schema.ResourceData, m interface{}) diag.Diagnostics { - log.Debugf("resourceLBRead") - - // c := m.(*controller.ControllerCfg) - - lbRec, err := utilityLBCheckPresence(ctx, d, m) - if lbRec == nil { - d.SetId("") - return diag.FromErr(err) - } - - hasChanged := false - - switch lbRec.Status { - case status.Modeled: - return diag.Errorf("The LB is in status: %s, please, contact support for more information", lbRec.Status) - case status.Creating: - case status.Created: - case status.Deleting: - case status.Deleted: - // lbId, _ := strconv.ParseUint(d.Id(), 10, 64) - // restoreReq := lb.RestoreRequest{LBID: lbId} - // enableReq := lb.DisableEnableRequest{LBID: lbId} - - // _, err := c.CloudAPI().LB().Restore(ctx, restoreReq) - // if err != nil { - // return diag.FromErr(err) - // } - // _, err = c.CloudAPI().LB().Enable(ctx, enableReq) - // if err != nil { - // return diag.FromErr(err) - // } - - // hasChanged = true - case status.Destroying: - return diag.Errorf("The LB is in progress with status: %s", lbRec.Status) - case status.Destroyed: - d.SetId("") - return diag.Errorf("The resource cannot be updated because it has been destroyed") - // return resourceLBCreate(ctx, d, m) - case status.Enabled: - case status.Enabling: - case status.Disabling: - case status.Disabled: - log.Debugf("The LB is in status: %s, troubles may occur with update. Please, enable LB first.", lbRec.Status) - case status.Restoring: - } - - if hasChanged { - lbRec, err = utilityLBCheckPresence(ctx, d, m) - if err != nil { - d.SetId("") - return diag.FromErr(err) - } - } - - flattenResourceLB(d, lbRec) - - return nil -} - -func resourceLBDelete(ctx context.Context, d *schema.ResourceData, m interface{}) diag.Diagnostics { - log.Debugf("resourceLBDelete") - - _, err := utilityLBCheckPresence(ctx, d, m) - if err != nil { - return diag.FromErr(err) - } - - c := m.(*controller.ControllerCfg) - req := lb.DeleteRequest{ - LBID: uint64(d.Get("lb_id").(int)), - } - - if permanently, ok := d.GetOk("permanently"); ok { - req.Permanently = permanently.(bool) - } - - _, err = c.CloudAPI().LB().Delete(ctx, req) - if err != nil { - return diag.FromErr(err) - } - - d.SetId("") - - return nil -} - -func resourceLBUpdate(ctx context.Context, d *schema.ResourceData, m interface{}) diag.Diagnostics { - log.Debugf("resourceLBUpdate") - c := m.(*controller.ControllerCfg) - - haveRGID, err := existRGID(ctx, d, m) - if err != nil { - return diag.FromErr(err) - } - - if !haveRGID { - return diag.Errorf("resourceLBUpdate: can't update LB because RGID %d is not allowed or does not exist", d.Get("rg_id").(int)) - } - - haveExtNetID, err := existExtNetID(ctx, d, m) - if err != nil { - return diag.FromErr(err) - } - - if !haveExtNetID { - return diag.Errorf("resourceLBUpdate: can't update LB because ExtNetID %d is not allowed or does not exist", d.Get("extnet_id").(int)) - } - - haveVins, err := existViNSID(ctx, d, m) - if err != nil { - return diag.FromErr(err) - } - - if !haveVins { - return diag.Errorf("resourceLBUpdate: can't update LB because ViNSID %d is not allowed or does not exist", d.Get("vins_id").(int)) - } - - lbRec, err := utilityLBCheckPresence(ctx, d, m) - if lbRec == nil { - d.SetId("") - return diag.FromErr(err) - } - - hasChanged := false - - switch lbRec.Status { - case status.Modeled: - return diag.Errorf("The LB is in status: %s, please, contact support for more information", lbRec.Status) - case status.Creating: - case status.Created: - case status.Deleting: - case status.Deleted: - lbId, _ := strconv.ParseUint(d.Id(), 10, 64) - restoreReq := lb.RestoreRequest{LBID: lbId} - enableReq := lb.DisableEnableRequest{LBID: lbId} - - _, err := c.CloudAPI().LB().Restore(ctx, restoreReq) - if err != nil { - return diag.FromErr(err) - } - _, err = c.CloudAPI().LB().Enable(ctx, enableReq) - if err != nil { - return diag.FromErr(err) - } - - hasChanged = true - case status.Destroying: - return diag.Errorf("The LB is in progress with status: %s", lbRec.Status) - case status.Destroyed: - d.SetId("") - return diag.Errorf("The resource cannot be updated because it has been destroyed") - // return resourceLBCreate(ctx, d, m) - case status.Enabled: - case status.Enabling: - case status.Disabling: - case status.Disabled: - log.Debugf("The LB is in status: %s, troubles may occur with update. Please, enable LB first.", lbRec.Status) - case status.Restoring: - } - - if hasChanged { - _, err = utilityLBCheckPresence(ctx, d, m) - if err != nil { - d.SetId("") - return diag.FromErr(err) - } - } - - if d.HasChange("ha_mode") { - hamode := d.Get("ha_mode").(bool) - if hamode { - req:= lb.HighlyAvailableRequest { - LBID: uint64(d.Get("lb_id").(int)), - } - _, err := c.CloudAPI().LB().HighlyAvailable(ctx, req) - if err != nil { - return diag.FromErr(err) - } - } - } - - if d.HasChange("enable") { - enable := d.Get("enable").(bool) - req := lb.DisableEnableRequest{ - LBID: uint64(d.Get("lb_id").(int)), - } - if enable { - _, err := c.CloudAPI().LB().Enable(ctx, req) - if err != nil { - return diag.FromErr(err) - } - } else { - _, err := c.CloudAPI().LB().Disable(ctx, req) - if err != nil { - return diag.FromErr(err) - } - - } - } - - if d.HasChange("start") { - start := d.Get("start").(bool) - lbId := uint64(d.Get("lb_id").(int)) - if start { - req := lb.StartRequest{LBID: lbId} - _, err := c.CloudAPI().LB().Start(ctx, req) - if err != nil { - return diag.FromErr(err) - } - } else { - req := lb.StopRequest{LBID: lbId} - _, err := c.CloudAPI().LB().Stop(ctx, req) - if err != nil { - return diag.FromErr(err) - } - } - } - - if d.HasChange("desc") { - req := lb.UpdateRequest{ - LBID: uint64(d.Get("lb_id").(int)), - Description: d.Get("desc").(string), - } - - _, err := c.CloudAPI().LB().Update(ctx, req) - if err != nil { - return diag.FromErr(err) - } - } - - if d.HasChange("restart") { - restart := d.Get("restart").(bool) - if restart { - req := lb.RestartRequest{ - LBID: uint64(d.Get("lb_id").(int)), - } - - _, err := c.CloudAPI().LB().Restart(ctx, req) - if err != nil { - return diag.FromErr(err) - } - } - } - - if d.HasChange("restore") { - restore := d.Get("restore").(bool) - if restore { - req := lb.RestoreRequest{ - LBID: uint64(d.Get("lb_id").(int)), - } - - _, err := c.CloudAPI().LB().Restore(ctx, req) - if err != nil { - return diag.FromErr(err) - } - } - } - - if d.HasChange("config_reset") { - cfgReset := d.Get("config_reset").(bool) - if cfgReset { - req := lb.ConfigResetRequest{ - LBID: uint64(d.Get("lb_id").(int)), - } - - _, err := c.CloudAPI().LB().ConfigReset(ctx, req) - if err != nil { - return diag.FromErr(err) - } - } - } - - return resourceLBRead(ctx, d, m) -} - -func ResourceLB() *schema.Resource { - return &schema.Resource{ - SchemaVersion: 1, - - CreateContext: resourceLBCreate, - ReadContext: resourceLBRead, - UpdateContext: resourceLBUpdate, - DeleteContext: resourceLBDelete, - - Importer: &schema.ResourceImporter{ - StateContext: schema.ImportStatePassthroughContext, - }, - - Timeouts: &schema.ResourceTimeout{ - Create: &constants.Timeout600s, - Read: &constants.Timeout300s, - Update: &constants.Timeout300s, - Delete: &constants.Timeout300s, - Default: &constants.Timeout300s, - }, - - Schema: lbResourceSchemaMake(), - } -} +/* +Copyright (c) 2019-2022 Digital Energy Cloud Solutions LLC. All Rights Reserved. +Authors: +Petr Krutov, +Stanislav Solovev, +Kasim Baybikov, + +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 lb + +import ( + "context" + "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/lb" + "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" + "repository.basistech.ru/BASIS/terraform-provider-decort/internal/status" +) + +func resourceLBCreate(ctx context.Context, d *schema.ResourceData, m interface{}) diag.Diagnostics { + log.Debugf("resourceLBCreate") + + haveRGID, err := existRGID(ctx, d, m) + if err != nil { + return diag.FromErr(err) + } + + if !haveRGID { + return diag.Errorf("resourceLBCreate: can't create LB because RGID %d is not allowed or does not exist", d.Get("rg_id").(int)) + } + + haveExtNetID, err := existExtNetID(ctx, d, m) + if err != nil { + return diag.FromErr(err) + } + + if !haveExtNetID { + return diag.Errorf("resourceLBCreate: can't create LB because ExtNetID %d is not allowed or does not exist", d.Get("extnet_id").(int)) + } + + haveVins, err := existViNSID(ctx, d, m) + if err != nil { + return diag.FromErr(err) + } + + if !haveVins { + return diag.Errorf("resourceLBCreate: can't create LB because ViNSID %d is not allowed or does not exist", d.Get("vins_id").(int)) + } + + c := m.(*controller.ControllerCfg) + req := lb.CreateRequest{ + Name: d.Get("name").(string), + RGID: uint64(d.Get("rg_id").(int)), + ExtNetID: uint64(d.Get("extnet_id").(int)), + VINSID: uint64(d.Get("vins_id").(int)), + Start: d.Get("start").(bool), + } + + if desc, ok := d.GetOk("desc"); ok { + req.Description = desc.(string) + } + + if haMode, ok := d.GetOk("ha_mode"); ok { + req.HighlyAvailable = haMode.(bool) + } + + lbId, err := c.CloudAPI().LB().Create(ctx, req) + if err != nil { + d.SetId("") + return diag.FromErr(err) + } + + d.SetId(strconv.FormatUint(lbId, 10)) + d.Set("lb_id", lbId) + + w := dc.Warnings{} + + if enable, ok := d.GetOk("enable"); ok { + req := lb.DisableEnableRequest{ + LBID: lbId, + } + + if enable.(bool) { + _, err := c.CloudAPI().LB().Enable(ctx, req) + if err != nil { + w.Add(err) + } + } else { + _, err := c.CloudAPI().LB().Disable(ctx, req) + if err != nil { + w.Add(err) + } + } + + if start, ok := d.GetOk("start"); ok && enable.(bool) { + if start.(bool) { + req := lb.StartRequest{LBID: lbId} + _, err := c.CloudAPI().LB().Start(ctx, req) + if err != nil { + w.Add(err) + } + } else { + req := lb.StopRequest{LBID: lbId} + _, err := c.CloudAPI().LB().Stop(ctx, req) + if err != nil { + w.Add(err) + } + } + } + } + + return append(w.Get(), resourceLBRead(ctx, d, m)...) +} + +func resourceLBRead(ctx context.Context, d *schema.ResourceData, m interface{}) diag.Diagnostics { + log.Debugf("resourceLBRead") + + // c := m.(*controller.ControllerCfg) + + lbRec, err := utilityLBCheckPresence(ctx, d, m) + if lbRec == nil { + d.SetId("") + return diag.FromErr(err) + } + + hasChanged := false + + switch lbRec.Status { + case status.Modeled: + return diag.Errorf("The LB is in status: %s, please, contact support for more information", lbRec.Status) + case status.Creating: + case status.Created: + case status.Deleting: + case status.Deleted: + // lbId, _ := strconv.ParseUint(d.Id(), 10, 64) + // restoreReq := lb.RestoreRequest{LBID: lbId} + // enableReq := lb.DisableEnableRequest{LBID: lbId} + + // _, err := c.CloudAPI().LB().Restore(ctx, restoreReq) + // if err != nil { + // return diag.FromErr(err) + // } + // _, err = c.CloudAPI().LB().Enable(ctx, enableReq) + // if err != nil { + // return diag.FromErr(err) + // } + + // hasChanged = true + case status.Destroying: + return diag.Errorf("The LB is in progress with status: %s", lbRec.Status) + case status.Destroyed: + d.SetId("") + return diag.Errorf("The resource cannot be updated because it has been destroyed") + // return resourceLBCreate(ctx, d, m) + case status.Enabled: + case status.Enabling: + case status.Disabling: + case status.Disabled: + log.Debugf("The LB is in status: %s, troubles may occur with update. Please, enable LB first.", lbRec.Status) + case status.Restoring: + } + + if hasChanged { + lbRec, err = utilityLBCheckPresence(ctx, d, m) + if err != nil { + d.SetId("") + return diag.FromErr(err) + } + } + + flattenResourceLB(d, lbRec) + + return nil +} + +func resourceLBDelete(ctx context.Context, d *schema.ResourceData, m interface{}) diag.Diagnostics { + log.Debugf("resourceLBDelete") + + c := m.(*controller.ControllerCfg) + lbId, _ := strconv.ParseUint(d.Id(), 10, 64) + req := lb.DeleteRequest{ + LBID: lbId, + } + + if permanently, ok := d.GetOk("permanently"); ok { + req.Permanently = permanently.(bool) + } + + _, err := c.CloudAPI().LB().Delete(ctx, req) + if err != nil { + return diag.FromErr(err) + } + + d.SetId("") + + return nil +} + +func resourceLBUpdate(ctx context.Context, d *schema.ResourceData, m interface{}) diag.Diagnostics { + log.Debugf("resourceLBUpdate") + c := m.(*controller.ControllerCfg) + + haveRGID, err := existRGID(ctx, d, m) + if err != nil { + return diag.FromErr(err) + } + + if !haveRGID { + return diag.Errorf("resourceLBUpdate: can't update LB because RGID %d is not allowed or does not exist", d.Get("rg_id").(int)) + } + + haveExtNetID, err := existExtNetID(ctx, d, m) + if err != nil { + return diag.FromErr(err) + } + + if !haveExtNetID { + return diag.Errorf("resourceLBUpdate: can't update LB because ExtNetID %d is not allowed or does not exist", d.Get("extnet_id").(int)) + } + + haveVins, err := existViNSID(ctx, d, m) + if err != nil { + return diag.FromErr(err) + } + + if !haveVins { + return diag.Errorf("resourceLBUpdate: can't update LB because ViNSID %d is not allowed or does not exist", d.Get("vins_id").(int)) + } + + lbRec, err := utilityLBCheckPresence(ctx, d, m) + if lbRec == nil { + d.SetId("") + return diag.FromErr(err) + } + + hasChanged := false + + switch lbRec.Status { + case status.Modeled: + return diag.Errorf("The LB is in status: %s, please, contact support for more information", lbRec.Status) + case status.Creating: + case status.Created: + case status.Deleting: + case status.Deleted: + if restore, ok := d.GetOk("restore"); ok && restore.(bool) { + restoreReq := lb.RestoreRequest{LBID: lbRec.ID} + + _, err := c.CloudAPI().LB().Restore(ctx, restoreReq) + if err != nil { + return diag.FromErr(err) + } + } + if enable, ok := d.GetOk("enable"); ok { + req := lb.DisableEnableRequest{ + LBID: lbRec.ID, + } + + if enable.(bool) { + _, err := c.CloudAPI().LB().Enable(ctx, req) + if err != nil { + return diag.FromErr(err) + } + } else { + _, err := c.CloudAPI().LB().Disable(ctx, req) + if err != nil { + return diag.FromErr(err) + } + } + + if start, ok := d.GetOk("start"); ok && enable.(bool) { + if start.(bool) { + req := lb.StartRequest{LBID: lbRec.ID} + _, err := c.CloudAPI().LB().Start(ctx, req) + if err != nil { + return diag.FromErr(err) + } + } else { + req := lb.StopRequest{LBID: lbRec.ID} + _, err := c.CloudAPI().LB().Stop(ctx, req) + if err != nil { + return diag.FromErr(err) + } + } + } + } + hasChanged = true + case status.Destroying: + return diag.Errorf("The LB is in progress with status: %s", lbRec.Status) + case status.Destroyed: + d.SetId("") + return diag.Errorf("The resource cannot be updated because it has been destroyed") + // return resourceLBCreate(ctx, d, m) + case status.Enabled: + case status.Enabling: + case status.Disabling: + case status.Disabled: + log.Debugf("The LB is in status: %s, troubles may occur with update. Please, enable LB first.", lbRec.Status) + case status.Restoring: + } + + if hasChanged { + _, err = utilityLBCheckPresence(ctx, d, m) + if err != nil { + d.SetId("") + return diag.FromErr(err) + } + } + + if d.HasChange("ha_mode") { + hamode := d.Get("ha_mode").(bool) + if hamode { + req := lb.HighlyAvailableRequest{ + LBID: uint64(d.Get("lb_id").(int)), + } + _, err := c.CloudAPI().LB().HighlyAvailable(ctx, req) + if err != nil { + return diag.FromErr(err) + } + } + } + + if d.HasChange("enable") { + enable := d.Get("enable").(bool) + req := lb.DisableEnableRequest{ + LBID: uint64(d.Get("lb_id").(int)), + } + if enable { + _, err := c.CloudAPI().LB().Enable(ctx, req) + if err != nil { + return diag.FromErr(err) + } + } else { + _, err := c.CloudAPI().LB().Disable(ctx, req) + if err != nil { + return diag.FromErr(err) + } + } + } + + if d.HasChange("start") { + start := d.Get("start").(bool) + lbId := uint64(d.Get("lb_id").(int)) + if start { + req := lb.StartRequest{LBID: lbId} + _, err := c.CloudAPI().LB().Start(ctx, req) + if err != nil { + return diag.FromErr(err) + } + } else { + req := lb.StopRequest{LBID: lbId} + _, err := c.CloudAPI().LB().Stop(ctx, req) + if err != nil { + return diag.FromErr(err) + } + } + } + + if d.HasChange("desc") { + req := lb.UpdateRequest{ + LBID: uint64(d.Get("lb_id").(int)), + Description: d.Get("desc").(string), + } + + _, err := c.CloudAPI().LB().Update(ctx, req) + if err != nil { + return diag.FromErr(err) + } + } + + if d.HasChange("restart") { + restart := d.Get("restart").(bool) + if restart { + req := lb.RestartRequest{ + LBID: uint64(d.Get("lb_id").(int)), + } + + _, err := c.CloudAPI().LB().Restart(ctx, req) + if err != nil { + return diag.FromErr(err) + } + } + } + + if d.HasChange("restore") { + restore := d.Get("restore").(bool) + if restore { + req := lb.RestoreRequest{ + LBID: uint64(d.Get("lb_id").(int)), + } + + _, err := c.CloudAPI().LB().Restore(ctx, req) + if err != nil { + return diag.FromErr(err) + } + } + } + + if d.HasChange("config_reset") { + cfgReset := d.Get("config_reset").(bool) + if cfgReset { + req := lb.ConfigResetRequest{ + LBID: uint64(d.Get("lb_id").(int)), + } + + _, err := c.CloudAPI().LB().ConfigReset(ctx, req) + if err != nil { + return diag.FromErr(err) + } + } + } + + return resourceLBRead(ctx, d, m) +} + +func ResourceLB() *schema.Resource { + return &schema.Resource{ + SchemaVersion: 1, + + CreateContext: resourceLBCreate, + ReadContext: resourceLBRead, + UpdateContext: resourceLBUpdate, + DeleteContext: resourceLBDelete, + + Importer: &schema.ResourceImporter{ + StateContext: schema.ImportStatePassthroughContext, + }, + + Timeouts: &schema.ResourceTimeout{ + Create: &constants.Timeout600s, + Read: &constants.Timeout300s, + Update: &constants.Timeout300s, + Delete: &constants.Timeout300s, + Default: &constants.Timeout300s, + }, + + Schema: lbResourceSchemaMake(), + } +} diff --git a/internal/service/cloudapi/lb/resource_lb_backend.go b/internal/service/cloudapi/lb/resource_lb_backend.go index 69c1462..e469e97 100644 --- a/internal/service/cloudapi/lb/resource_lb_backend.go +++ b/internal/service/cloudapi/lb/resource_lb_backend.go @@ -1,374 +1,379 @@ -/* -Copyright (c) 2019-2022 Digital Energy Cloud Solutions LLC. All Rights Reserved. -Authors: -Petr Krutov, -Stanislav Solovev, -Kasim Baybikov, - -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 lb - -import ( - "context" - "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/lb" - "repository.basistech.ru/BASIS/terraform-provider-decort/internal/constants" - "repository.basistech.ru/BASIS/terraform-provider-decort/internal/controller" -) - -func resourceLBBackendCreate(ctx context.Context, d *schema.ResourceData, m interface{}) diag.Diagnostics { - log.Debugf("resourceLBBackendCreate") - - haveLBID, err := existLBID(ctx, d, m) - if err != nil { - return diag.FromErr(err) - } - - if !haveLBID { - return diag.Errorf("resourceLBBackendCreate: can't create LB backend because LBID %d is not allowed or does not exist", d.Get("lb_id").(int)) - } - - c := m.(*controller.ControllerCfg) - req := lb.BackendCreateRequest{} - - req.BackendName = d.Get("name").(string) - req.LBID = uint64(d.Get("lb_id").(int)) - - if algorithm, ok := d.GetOk("algorithm"); ok { - req.Algorithm = algorithm.(string) - } - if inter, ok := d.GetOk("inter"); ok { - req.Inter = uint64(inter.(int)) - } - if downinter, ok := d.GetOk("downinter"); ok { - req.DownInter = uint64(downinter.(int)) - } - if rise, ok := d.GetOk("rise"); ok { - req.Rise = uint64(rise.(int)) - } - if fall, ok := d.GetOk("fall"); ok { - req.Fall = uint64(fall.(int)) - } - if slowstart, ok := d.GetOk("slowstart"); ok { - req.SlowStart = uint64(slowstart.(int)) - } - if maxconn, ok := d.GetOk("maxconn"); ok { - req.MaxConn = uint64(maxconn.(int)) - } - if maxqueue, ok := d.GetOk("maxqueue"); ok { - req.MaxQueue = uint64(maxqueue.(int)) - } - if weight, ok := d.GetOk("weight"); ok { - req.Weight = uint64(weight.(int)) - } - - _, err = c.CloudAPI().LB().BackendCreate(ctx, req) - if err != nil { - return diag.FromErr(err) - } - - d.SetId(strconv.Itoa(d.Get("lb_id").(int)) + "#" + d.Get("name").(string)) - - _, err = utilityLBBackendCheckPresence(ctx, d, m) - if err != nil { - return diag.FromErr(err) - } - - return resourceLBBackendRead(ctx, d, m) -} - -func resourceLBBackendRead(ctx context.Context, d *schema.ResourceData, m interface{}) diag.Diagnostics { - log.Debugf("resourceLBBackendRead") - - b, err := utilityLBBackendCheckPresence(ctx, d, m) - if b == nil { - d.SetId("") - return diag.FromErr(err) - } - - lbId, _ := strconv.ParseInt(strings.Split(d.Id(), "#")[0], 10, 32) - - flattenResourceLBBackend(d, b, lbId) - - return nil -} - -func resourceLBBackendDelete(ctx context.Context, d *schema.ResourceData, m interface{}) diag.Diagnostics { - log.Debugf("resourceLBBackendDelete") - - _, err := utilityLBBackendCheckPresence(ctx, d, m) - if err != nil { - return diag.FromErr(err) - } - - c := m.(*controller.ControllerCfg) - req := lb.BackendDeleteRequest{ - LBID: uint64(d.Get("lb_id").(int)), - BackendName: d.Get("name").(string), - } - - _, err = c.CloudAPI().LB().BackendDelete(ctx, req) - if err != nil { - return diag.FromErr(err) - } - - d.SetId("") - - return nil -} - -func resourceLBBackendUpdate(ctx context.Context, d *schema.ResourceData, m interface{}) diag.Diagnostics { - log.Debugf("resourceLBBackendEdit") - c := m.(*controller.ControllerCfg) - - haveLBID, err := existLBID(ctx, d, m) - if err != nil { - return diag.FromErr(err) - } - - if !haveLBID { - return diag.Errorf("resourceLBBackendUpdate: can't update LB backend because LBID %d is not allowed or does not exist", d.Get("lb_id").(int)) - } - - req := lb.BackendUpdateRequest{ - LBID: uint64(d.Get("lb_id").(int)), - BackendName: d.Get("name").(string), - } - - if d.HasChange("algorithm") { - req.Algorithm = d.Get("algorithm").(string) - } - if d.HasChange("inter") { - req.Inter = uint64(d.Get("inter").(int)) - } - if d.HasChange("downinter") { - req.DownInter = uint64(d.Get("downinter").(int)) - } - if d.HasChange("rise") { - req.Rise = uint64(d.Get("rise").(int)) - } - if d.HasChange("fall") { - req.Fall = uint64(d.Get("fall").(int)) - } - if d.HasChange("slowstart") { - req.SlowStart = uint64(d.Get("slowstart").(int)) - } - if d.HasChange("maxconn") { - req.MaxConn = uint64(d.Get("maxconn").(int)) - } - if d.HasChange("maxqueue") { - req.MaxQueue = uint64(d.Get("maxqueue").(int)) - } - if d.HasChange("weight") { - req.Weight = uint64(d.Get("weight").(int)) - } - - _, err = c.CloudAPI().LB().BackendUpdate(ctx, req) - if err != nil { - return diag.FromErr(err) - } - - return resourceLBBackendRead(ctx, d, m) -} - -func ResourceLBBackend() *schema.Resource { - return &schema.Resource{ - SchemaVersion: 1, - - CreateContext: resourceLBBackendCreate, - ReadContext: resourceLBBackendRead, - UpdateContext: resourceLBBackendUpdate, - DeleteContext: resourceLBBackendDelete, - - Importer: &schema.ResourceImporter{ - StateContext: schema.ImportStatePassthroughContext, - }, - - Timeouts: &schema.ResourceTimeout{ - Create: &constants.Timeout600s, - Read: &constants.Timeout300s, - Update: &constants.Timeout300s, - Delete: &constants.Timeout300s, - Default: &constants.Timeout300s, - }, - - Schema: map[string]*schema.Schema{ - "lb_id": { - Type: schema.TypeInt, - Required: true, - Description: "ID of the LB instance to backendCreate", - }, - "name": { - Type: schema.TypeString, - Required: true, - Description: "Must be unique among all backends of this LB - name of the new backend to create", - }, - "algorithm": { - Type: schema.TypeString, - Optional: true, - Computed: true, - ValidateFunc: validation.StringInSlice([]string{"roundrobin", "static-rr", "leastconn"}, false), - }, - "guid": { - Type: schema.TypeString, - Computed: true, - }, - "downinter": { - Type: schema.TypeInt, - Optional: true, - Computed: true, - }, - "fall": { - Type: schema.TypeInt, - Optional: true, - Computed: true, - }, - "inter": { - Type: schema.TypeInt, - Optional: true, - Computed: true, - }, - "maxconn": { - Type: schema.TypeInt, - Optional: true, - Computed: true, - }, - "maxqueue": { - Type: schema.TypeInt, - Optional: true, - Computed: true, - }, - "rise": { - Type: schema.TypeInt, - Optional: true, - Computed: true, - }, - "slowstart": { - Type: schema.TypeInt, - Optional: true, - Computed: true, - }, - "weight": { - Type: schema.TypeInt, - Optional: true, - Computed: true, - }, - "servers": { - Type: schema.TypeList, - Optional: true, - Computed: true, - Elem: &schema.Resource{ - Schema: map[string]*schema.Schema{ - "address": { - Type: schema.TypeString, - Optional: true, - Computed: true, - }, - "check": { - Type: schema.TypeString, - Optional: true, - Computed: true, - }, - "guid": { - Type: schema.TypeString, - Computed: true, - }, - "name": { - Type: schema.TypeString, - Optional: true, - Computed: true, - }, - "port": { - Type: schema.TypeInt, - Optional: true, - Computed: true, - }, - "server_settings": { - Type: schema.TypeList, - Optional: true, - Computed: true, - Elem: &schema.Resource{ - Schema: map[string]*schema.Schema{ - "downinter": { - Type: schema.TypeInt, - Optional: true, - Computed: true, - }, - "fall": { - Type: schema.TypeInt, - Optional: true, - Computed: true, - }, - "guid": { - Type: schema.TypeString, - Computed: true, - }, - "inter": { - Type: schema.TypeInt, - Optional: true, - Computed: true, - }, - "maxconn": { - Type: schema.TypeInt, - Optional: true, - Computed: true, - }, - "maxqueue": { - Type: schema.TypeInt, - Optional: true, - Computed: true, - }, - "rise": { - Type: schema.TypeInt, - Optional: true, - Computed: true, - }, - "slowstart": { - Type: schema.TypeInt, - Optional: true, - Computed: true, - }, - "weight": { - Type: schema.TypeInt, - Optional: true, - Computed: true, - }, - }, - }, - }, - }, - }, - }, - }, - } -} +/* +Copyright (c) 2019-2022 Digital Energy Cloud Solutions LLC. All Rights Reserved. +Authors: +Petr Krutov, +Stanislav Solovev, +Kasim Baybikov, + +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 lb + +import ( + "context" + "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/lb" + "repository.basistech.ru/BASIS/terraform-provider-decort/internal/constants" + "repository.basistech.ru/BASIS/terraform-provider-decort/internal/controller" +) + +func resourceLBBackendCreate(ctx context.Context, d *schema.ResourceData, m interface{}) diag.Diagnostics { + log.Debugf("resourceLBBackendCreate") + + haveLBID, err := existLBID(ctx, d, m) + if err != nil { + return diag.FromErr(err) + } + + if !haveLBID { + return diag.Errorf("resourceLBBackendCreate: can't create LB backend because LBID %d is not allowed or does not exist", d.Get("lb_id").(int)) + } + + c := m.(*controller.ControllerCfg) + req := lb.BackendCreateRequest{} + + req.BackendName = d.Get("name").(string) + req.LBID = uint64(d.Get("lb_id").(int)) + + if algorithm, ok := d.GetOk("algorithm"); ok { + req.Algorithm = algorithm.(string) + } + if inter, ok := d.GetOk("inter"); ok { + req.Inter = uint64(inter.(int)) + } + if downinter, ok := d.GetOk("downinter"); ok { + req.DownInter = uint64(downinter.(int)) + } + if rise, ok := d.GetOk("rise"); ok { + req.Rise = uint64(rise.(int)) + } + if fall, ok := d.GetOk("fall"); ok { + req.Fall = uint64(fall.(int)) + } + if slowstart, ok := d.GetOk("slowstart"); ok { + req.SlowStart = uint64(slowstart.(int)) + } + if maxconn, ok := d.GetOk("maxconn"); ok { + req.MaxConn = uint64(maxconn.(int)) + } + if maxqueue, ok := d.GetOk("maxqueue"); ok { + req.MaxQueue = uint64(maxqueue.(int)) + } + if weight, ok := d.GetOk("weight"); ok { + req.Weight = uint64(weight.(int)) + } + + _, err = c.CloudAPI().LB().BackendCreate(ctx, req) + if err != nil { + d.SetId("") + return diag.FromErr(err) + } + + d.SetId(strconv.Itoa(d.Get("lb_id").(int)) + "#" + d.Get("name").(string)) + + _, err = utilityLBBackendCheckPresence(ctx, d, m) + if err != nil { + d.SetId("") + return diag.FromErr(err) + } + + return resourceLBBackendRead(ctx, d, m) +} + +func resourceLBBackendRead(ctx context.Context, d *schema.ResourceData, m interface{}) diag.Diagnostics { + log.Debugf("resourceLBBackendRead") + + b, err := utilityLBBackendCheckPresence(ctx, d, m) + if b == nil { + d.SetId("") + return diag.FromErr(err) + } + + lbId, _ := strconv.ParseInt(strings.Split(d.Id(), "#")[0], 10, 32) + + flattenResourceLBBackend(d, b, lbId) + + return nil +} + +func resourceLBBackendDelete(ctx context.Context, d *schema.ResourceData, m interface{}) diag.Diagnostics { + log.Debugf("resourceLBBackendDelete") + + _, err := utilityLBBackendCheckPresence(ctx, d, m) + if err != nil { + d.SetId("") + return diag.FromErr(err) + } + + c := m.(*controller.ControllerCfg) + req := lb.BackendDeleteRequest{ + LBID: uint64(d.Get("lb_id").(int)), + BackendName: d.Get("name").(string), + } + + _, err = c.CloudAPI().LB().BackendDelete(ctx, req) + if err != nil { + d.SetId("") + return diag.FromErr(err) + } + + d.SetId("") + + return nil +} + +func resourceLBBackendUpdate(ctx context.Context, d *schema.ResourceData, m interface{}) diag.Diagnostics { + log.Debugf("resourceLBBackendEdit") + c := m.(*controller.ControllerCfg) + + haveLBID, err := existLBID(ctx, d, m) + if err != nil { + return diag.FromErr(err) + } + + if !haveLBID { + return diag.Errorf("resourceLBBackendUpdate: can't update LB backend because LBID %d is not allowed or does not exist", d.Get("lb_id").(int)) + } + + req := lb.BackendUpdateRequest{ + LBID: uint64(d.Get("lb_id").(int)), + BackendName: d.Get("name").(string), + } + + if d.HasChange("algorithm") { + req.Algorithm = d.Get("algorithm").(string) + } + if d.HasChange("inter") { + req.Inter = uint64(d.Get("inter").(int)) + } + if d.HasChange("downinter") { + req.DownInter = uint64(d.Get("downinter").(int)) + } + if d.HasChange("rise") { + req.Rise = uint64(d.Get("rise").(int)) + } + if d.HasChange("fall") { + req.Fall = uint64(d.Get("fall").(int)) + } + if d.HasChange("slowstart") { + req.SlowStart = uint64(d.Get("slowstart").(int)) + } + if d.HasChange("maxconn") { + req.MaxConn = uint64(d.Get("maxconn").(int)) + } + if d.HasChange("maxqueue") { + req.MaxQueue = uint64(d.Get("maxqueue").(int)) + } + if d.HasChange("weight") { + req.Weight = uint64(d.Get("weight").(int)) + } + + _, err = c.CloudAPI().LB().BackendUpdate(ctx, req) + if err != nil { + d.SetId("") + return diag.FromErr(err) + } + + return resourceLBBackendRead(ctx, d, m) +} + +func ResourceLBBackend() *schema.Resource { + return &schema.Resource{ + SchemaVersion: 1, + + CreateContext: resourceLBBackendCreate, + ReadContext: resourceLBBackendRead, + UpdateContext: resourceLBBackendUpdate, + DeleteContext: resourceLBBackendDelete, + + Importer: &schema.ResourceImporter{ + StateContext: schema.ImportStatePassthroughContext, + }, + + Timeouts: &schema.ResourceTimeout{ + Create: &constants.Timeout600s, + Read: &constants.Timeout300s, + Update: &constants.Timeout300s, + Delete: &constants.Timeout300s, + Default: &constants.Timeout300s, + }, + + Schema: map[string]*schema.Schema{ + "lb_id": { + Type: schema.TypeInt, + Required: true, + Description: "ID of the LB instance to backendCreate", + }, + "name": { + Type: schema.TypeString, + Required: true, + Description: "Must be unique among all backends of this LB - name of the new backend to create", + }, + "algorithm": { + Type: schema.TypeString, + Optional: true, + Computed: true, + ValidateFunc: validation.StringInSlice([]string{"roundrobin", "static-rr", "leastconn"}, false), + }, + "guid": { + Type: schema.TypeString, + Computed: true, + }, + "downinter": { + Type: schema.TypeInt, + Optional: true, + Computed: true, + }, + "fall": { + Type: schema.TypeInt, + Optional: true, + Computed: true, + }, + "inter": { + Type: schema.TypeInt, + Optional: true, + Computed: true, + }, + "maxconn": { + Type: schema.TypeInt, + Optional: true, + Computed: true, + }, + "maxqueue": { + Type: schema.TypeInt, + Optional: true, + Computed: true, + }, + "rise": { + Type: schema.TypeInt, + Optional: true, + Computed: true, + }, + "slowstart": { + Type: schema.TypeInt, + Optional: true, + Computed: true, + }, + "weight": { + Type: schema.TypeInt, + Optional: true, + Computed: true, + }, + "servers": { + Type: schema.TypeList, + Optional: true, + Computed: true, + Elem: &schema.Resource{ + Schema: map[string]*schema.Schema{ + "address": { + Type: schema.TypeString, + Optional: true, + Computed: true, + }, + "check": { + Type: schema.TypeString, + Optional: true, + Computed: true, + }, + "guid": { + Type: schema.TypeString, + Computed: true, + }, + "name": { + Type: schema.TypeString, + Optional: true, + Computed: true, + }, + "port": { + Type: schema.TypeInt, + Optional: true, + Computed: true, + }, + "server_settings": { + Type: schema.TypeList, + Optional: true, + Computed: true, + Elem: &schema.Resource{ + Schema: map[string]*schema.Schema{ + "downinter": { + Type: schema.TypeInt, + Optional: true, + Computed: true, + }, + "fall": { + Type: schema.TypeInt, + Optional: true, + Computed: true, + }, + "guid": { + Type: schema.TypeString, + Computed: true, + }, + "inter": { + Type: schema.TypeInt, + Optional: true, + Computed: true, + }, + "maxconn": { + Type: schema.TypeInt, + Optional: true, + Computed: true, + }, + "maxqueue": { + Type: schema.TypeInt, + Optional: true, + Computed: true, + }, + "rise": { + Type: schema.TypeInt, + Optional: true, + Computed: true, + }, + "slowstart": { + Type: schema.TypeInt, + Optional: true, + Computed: true, + }, + "weight": { + Type: schema.TypeInt, + Optional: true, + Computed: true, + }, + }, + }, + }, + }, + }, + }, + }, + } +} diff --git a/internal/service/cloudapi/lb/resource_lb_backend_server.go b/internal/service/cloudapi/lb/resource_lb_backend_server.go index edeaedb..780f909 100644 --- a/internal/service/cloudapi/lb/resource_lb_backend_server.go +++ b/internal/service/cloudapi/lb/resource_lb_backend_server.go @@ -1,314 +1,320 @@ -/* -Copyright (c) 2019-2022 Digital Energy Cloud Solutions LLC. All Rights Reserved. -Authors: -Petr Krutov, -Stanislav Solovev, -Kasim Baybikov, - -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 lb - -import ( - "context" - "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/lb" - "repository.basistech.ru/BASIS/terraform-provider-decort/internal/constants" - "repository.basistech.ru/BASIS/terraform-provider-decort/internal/controller" -) - -func resourceLBBackendServerCreate(ctx context.Context, d *schema.ResourceData, m interface{}) diag.Diagnostics { - log.Debugf("resourceLBBackendServerCreate") - - haveLBID, err := existLBID(ctx, d, m) - if err != nil { - return diag.FromErr(err) - } - - if !haveLBID { - return diag.Errorf("resourceLBBackendServerCreate: can't create LB backend server because LBID %d is not allowed or does not exist", d.Get("lb_id").(int)) - } - - c := m.(*controller.ControllerCfg) - req := lb.BackendServerAddRequest{ - BackendName: d.Get("backend_name").(string), - ServerName: d.Get("name").(string), - Address: d.Get("address").(string), - LBID: uint64(d.Get("lb_id").(int)), - Port: uint64(d.Get("port").(int)), - } - - if check, ok := d.GetOk("check"); ok { - req.Check = check.(string) - } - - if inter, ok := d.GetOk("inter"); ok { - req.Inter = uint64(inter.(int)) - } - if downinter, ok := d.GetOk("downinter"); ok { - req.DownInter = uint64(downinter.(int)) - } - if rise, ok := d.GetOk("rise"); ok { - req.Rise = uint64(rise.(int)) - } - if fall, ok := d.GetOk("fall"); ok { - req.Fall = uint64(fall.(int)) - } - if slowstart, ok := d.GetOk("slowstart"); ok { - req.SlowStart = uint64(slowstart.(int)) - } - if maxconn, ok := d.GetOk("maxconn"); ok { - req.MaxConn = uint64(maxconn.(int)) - } - if maxqueue, ok := d.GetOk("maxqueue"); ok { - req.MaxQueue = uint64(maxqueue.(int)) - } - if weight, ok := d.GetOk("weight"); ok { - req.Weight = uint64(weight.(int)) - } - - _, err = c.CloudAPI().LB().BackendServerAdd(ctx, req) - if err != nil { - return diag.FromErr(err) - } - - d.SetId(strconv.Itoa(d.Get("lb_id").(int)) + "#" + d.Get("backend_name").(string) + "#" + d.Get("name").(string)) - - _, err = utilityLBBackendServerCheckPresence(ctx, d, m) - if err != nil { - return diag.FromErr(err) - } - - return resourceLBBackendServerRead(ctx, d, m) -} - -func resourceLBBackendServerRead(ctx context.Context, d *schema.ResourceData, m interface{}) diag.Diagnostics { - log.Debugf("resourceLBBackendServerRead") - - s, err := utilityLBBackendServerCheckPresence(ctx, d, m) - if err != nil { - d.SetId("") - return diag.FromErr(err) - } - - lbId, _ := strconv.ParseInt(strings.Split(d.Id(), "#")[0], 10, 32) - backendName := strings.Split(d.Id(), "#")[1] - - flattenResourceLBBackendServer(d, s, lbId, backendName) - - return nil -} - -func resourceLBBackendServerDelete(ctx context.Context, d *schema.ResourceData, m interface{}) diag.Diagnostics { - log.Debugf("resourceLBBackendServerDelete") - - _, err := utilityLBBackendServerCheckPresence(ctx, d, m) - if err != nil { - return diag.FromErr(err) - } - - c := m.(*controller.ControllerCfg) - req := lb.BackendServerDeleteRequest{ - LBID: uint64(d.Get("lb_id").(int)), - BackendName: d.Get("backend_name").(string), - ServerName: d.Get("name").(string), - } - - _, err = c.CloudAPI().LB().BackendServerDelete(ctx, req) - if err != nil { - return diag.FromErr(err) - } - d.SetId("") - - return nil -} - -func resourceLBBackendServerUpdate(ctx context.Context, d *schema.ResourceData, m interface{}) diag.Diagnostics { - log.Debugf("resourceLBBackendServerEdit") - c := m.(*controller.ControllerCfg) - - haveLBID, err := existLBID(ctx, d, m) - if err != nil { - return diag.FromErr(err) - } - - if !haveLBID { - return diag.Errorf("resourceLBBackendServerUpdate: can't update LB backend server because LBID %d is not allowed or does not exist", d.Get("lb_id").(int)) - } - - req := lb.BackendServerUpdateRequest{ - BackendName: d.Get("backend_name").(string), - LBID: uint64(d.Get("lb_id").(int)), - ServerName: d.Get("name").(string), - Address: d.Get("address").(string), - Port: uint64(d.Get("port").(int)), - } - - if d.HasChange("check") { - req.Check = d.Get("check").(string) - } - if d.HasChange("inter") { - req.Inter = uint64(d.Get("inter").(int)) - } - if d.HasChange("downinter") { - req.DownInter = uint64(d.Get("downinter").(int)) - } - if d.HasChange("rise") { - req.Rise = uint64(d.Get("rise").(int)) - } - if d.HasChange("fall") { - req.Fall = uint64(d.Get("fall").(int)) - } - if d.HasChange("slowstart") { - req.SlowStart = uint64(d.Get("slowstart").(int)) - } - if d.HasChange("maxconn") { - req.MaxConn = uint64(d.Get("maxconn").(int)) - } - if d.HasChange("maxqueue") { - req.MaxQueue = uint64(d.Get("maxqueue").(int)) - } - if d.HasChange("weight") { - req.Weight = uint64(d.Get("weight").(int)) - } - - _, err = c.CloudAPI().LB().BackendServerUpdate(ctx, req) - if err != nil { - return diag.FromErr(err) - } - - //TODO: перенести servers сюда - - return resourceLBBackendServerRead(ctx, d, m) -} - -func ResourceLBBackendServer() *schema.Resource { - return &schema.Resource{ - SchemaVersion: 1, - - CreateContext: resourceLBBackendServerCreate, - ReadContext: resourceLBBackendServerRead, - UpdateContext: resourceLBBackendServerUpdate, - DeleteContext: resourceLBBackendServerDelete, - - Importer: &schema.ResourceImporter{ - StateContext: schema.ImportStatePassthroughContext, - }, - - Timeouts: &schema.ResourceTimeout{ - Create: &constants.Timeout600s, - Read: &constants.Timeout300s, - Update: &constants.Timeout300s, - Delete: &constants.Timeout300s, - Default: &constants.Timeout300s, - }, - - Schema: map[string]*schema.Schema{ - "lb_id": { - Type: schema.TypeInt, - Required: true, - Description: "ID of the LB instance to backendCreate", - }, - "backend_name": { - Type: schema.TypeString, - Required: true, - Description: "Must be unique among all backends of this LB - name of the new backend to create", - }, - "name": { - Type: schema.TypeString, - Required: true, - Description: "Must be unique among all servers defined for this backend - name of the server definition to add.", - }, - "address": { - Type: schema.TypeString, - Required: true, - Description: "IP address of the server.", - }, - "port": { - Type: schema.TypeInt, - Required: true, - Description: "Port number on the server", - }, - "check": { - Type: schema.TypeString, - Optional: true, - Computed: true, - ValidateFunc: validation.StringInSlice([]string{"disabled", "enabled"}, false), - Description: "set to disabled if this server should be used regardless of its state.", - }, - "guid": { - Type: schema.TypeString, - Computed: true, - }, - "downinter": { - Type: schema.TypeInt, - Optional: true, - Computed: true, - }, - "fall": { - Type: schema.TypeInt, - Optional: true, - Computed: true, - }, - "inter": { - Type: schema.TypeInt, - Optional: true, - Computed: true, - }, - "maxconn": { - Type: schema.TypeInt, - Optional: true, - Computed: true, - }, - "maxqueue": { - Type: schema.TypeInt, - Optional: true, - Computed: true, - }, - "rise": { - Type: schema.TypeInt, - Optional: true, - Computed: true, - }, - "slowstart": { - Type: schema.TypeInt, - Optional: true, - Computed: true, - }, - "weight": { - Type: schema.TypeInt, - Optional: true, - Computed: true, - }, - }, - } -} +/* +Copyright (c) 2019-2022 Digital Energy Cloud Solutions LLC. All Rights Reserved. +Authors: +Petr Krutov, +Stanislav Solovev, +Kasim Baybikov, + +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 lb + +import ( + "context" + "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/lb" + "repository.basistech.ru/BASIS/terraform-provider-decort/internal/constants" + "repository.basistech.ru/BASIS/terraform-provider-decort/internal/controller" +) + +func resourceLBBackendServerCreate(ctx context.Context, d *schema.ResourceData, m interface{}) diag.Diagnostics { + log.Debugf("resourceLBBackendServerCreate") + + haveLBID, err := existLBID(ctx, d, m) + if err != nil { + return diag.FromErr(err) + } + + if !haveLBID { + return diag.Errorf("resourceLBBackendServerCreate: can't create LB backend server because LBID %d is not allowed or does not exist", d.Get("lb_id").(int)) + } + + c := m.(*controller.ControllerCfg) + req := lb.BackendServerAddRequest{ + BackendName: d.Get("backend_name").(string), + ServerName: d.Get("name").(string), + Address: d.Get("address").(string), + LBID: uint64(d.Get("lb_id").(int)), + Port: uint64(d.Get("port").(int)), + } + + if check, ok := d.GetOk("check"); ok { + req.Check = check.(string) + } + + if inter, ok := d.GetOk("inter"); ok { + req.Inter = uint64(inter.(int)) + } + if downinter, ok := d.GetOk("downinter"); ok { + req.DownInter = uint64(downinter.(int)) + } + if rise, ok := d.GetOk("rise"); ok { + req.Rise = uint64(rise.(int)) + } + if fall, ok := d.GetOk("fall"); ok { + req.Fall = uint64(fall.(int)) + } + if slowstart, ok := d.GetOk("slowstart"); ok { + req.SlowStart = uint64(slowstart.(int)) + } + if maxconn, ok := d.GetOk("maxconn"); ok { + req.MaxConn = uint64(maxconn.(int)) + } + if maxqueue, ok := d.GetOk("maxqueue"); ok { + req.MaxQueue = uint64(maxqueue.(int)) + } + if weight, ok := d.GetOk("weight"); ok { + req.Weight = uint64(weight.(int)) + } + + _, err = c.CloudAPI().LB().BackendServerAdd(ctx, req) + if err != nil { + d.SetId("") + return diag.FromErr(err) + } + + d.SetId(strconv.Itoa(d.Get("lb_id").(int)) + "#" + d.Get("backend_name").(string) + "#" + d.Get("name").(string)) + + _, err = utilityLBBackendServerCheckPresence(ctx, d, m) + if err != nil { + d.SetId("") + return diag.FromErr(err) + } + + return resourceLBBackendServerRead(ctx, d, m) +} + +func resourceLBBackendServerRead(ctx context.Context, d *schema.ResourceData, m interface{}) diag.Diagnostics { + log.Debugf("resourceLBBackendServerRead") + + s, err := utilityLBBackendServerCheckPresence(ctx, d, m) + if err != nil { + d.SetId("") + return diag.FromErr(err) + } + + lbId, _ := strconv.ParseInt(strings.Split(d.Id(), "#")[0], 10, 32) + backendName := strings.Split(d.Id(), "#")[1] + + flattenResourceLBBackendServer(d, s, lbId, backendName) + + return nil +} + +func resourceLBBackendServerDelete(ctx context.Context, d *schema.ResourceData, m interface{}) diag.Diagnostics { + log.Debugf("resourceLBBackendServerDelete") + + _, err := utilityLBBackendServerCheckPresence(ctx, d, m) + if err != nil { + d.SetId("") + return diag.FromErr(err) + } + + c := m.(*controller.ControllerCfg) + req := lb.BackendServerDeleteRequest{ + LBID: uint64(d.Get("lb_id").(int)), + BackendName: d.Get("backend_name").(string), + ServerName: d.Get("name").(string), + } + + _, err = c.CloudAPI().LB().BackendServerDelete(ctx, req) + if err != nil { + d.SetId("") + return diag.FromErr(err) + } + d.SetId("") + + return nil +} + +func resourceLBBackendServerUpdate(ctx context.Context, d *schema.ResourceData, m interface{}) diag.Diagnostics { + log.Debugf("resourceLBBackendServerEdit") + c := m.(*controller.ControllerCfg) + + haveLBID, err := existLBID(ctx, d, m) + if err != nil { + d.SetId("") + return diag.FromErr(err) + } + + if !haveLBID { + return diag.Errorf("resourceLBBackendServerUpdate: can't update LB backend server because LBID %d is not allowed or does not exist", d.Get("lb_id").(int)) + } + + req := lb.BackendServerUpdateRequest{ + BackendName: d.Get("backend_name").(string), + LBID: uint64(d.Get("lb_id").(int)), + ServerName: d.Get("name").(string), + Address: d.Get("address").(string), + Port: uint64(d.Get("port").(int)), + } + + if d.HasChange("check") { + req.Check = d.Get("check").(string) + } + if d.HasChange("inter") { + req.Inter = uint64(d.Get("inter").(int)) + } + if d.HasChange("downinter") { + req.DownInter = uint64(d.Get("downinter").(int)) + } + if d.HasChange("rise") { + req.Rise = uint64(d.Get("rise").(int)) + } + if d.HasChange("fall") { + req.Fall = uint64(d.Get("fall").(int)) + } + if d.HasChange("slowstart") { + req.SlowStart = uint64(d.Get("slowstart").(int)) + } + if d.HasChange("maxconn") { + req.MaxConn = uint64(d.Get("maxconn").(int)) + } + if d.HasChange("maxqueue") { + req.MaxQueue = uint64(d.Get("maxqueue").(int)) + } + if d.HasChange("weight") { + req.Weight = uint64(d.Get("weight").(int)) + } + + _, err = c.CloudAPI().LB().BackendServerUpdate(ctx, req) + if err != nil { + d.SetId("") + return diag.FromErr(err) + } + + //TODO: перенести servers сюда + + return resourceLBBackendServerRead(ctx, d, m) +} + +func ResourceLBBackendServer() *schema.Resource { + return &schema.Resource{ + SchemaVersion: 1, + + CreateContext: resourceLBBackendServerCreate, + ReadContext: resourceLBBackendServerRead, + UpdateContext: resourceLBBackendServerUpdate, + DeleteContext: resourceLBBackendServerDelete, + + Importer: &schema.ResourceImporter{ + StateContext: schema.ImportStatePassthroughContext, + }, + + Timeouts: &schema.ResourceTimeout{ + Create: &constants.Timeout600s, + Read: &constants.Timeout300s, + Update: &constants.Timeout300s, + Delete: &constants.Timeout300s, + Default: &constants.Timeout300s, + }, + + Schema: map[string]*schema.Schema{ + "lb_id": { + Type: schema.TypeInt, + Required: true, + Description: "ID of the LB instance to backendCreate", + }, + "backend_name": { + Type: schema.TypeString, + Required: true, + Description: "Must be unique among all backends of this LB - name of the new backend to create", + }, + "name": { + Type: schema.TypeString, + Required: true, + Description: "Must be unique among all servers defined for this backend - name of the server definition to add.", + }, + "address": { + Type: schema.TypeString, + Required: true, + Description: "IP address of the server.", + }, + "port": { + Type: schema.TypeInt, + Required: true, + Description: "Port number on the server", + }, + "check": { + Type: schema.TypeString, + Optional: true, + Computed: true, + ValidateFunc: validation.StringInSlice([]string{"disabled", "enabled"}, false), + Description: "set to disabled if this server should be used regardless of its state.", + }, + "guid": { + Type: schema.TypeString, + Computed: true, + }, + "downinter": { + Type: schema.TypeInt, + Optional: true, + Computed: true, + }, + "fall": { + Type: schema.TypeInt, + Optional: true, + Computed: true, + }, + "inter": { + Type: schema.TypeInt, + Optional: true, + Computed: true, + }, + "maxconn": { + Type: schema.TypeInt, + Optional: true, + Computed: true, + }, + "maxqueue": { + Type: schema.TypeInt, + Optional: true, + Computed: true, + }, + "rise": { + Type: schema.TypeInt, + Optional: true, + Computed: true, + }, + "slowstart": { + Type: schema.TypeInt, + Optional: true, + Computed: true, + }, + "weight": { + Type: schema.TypeInt, + Optional: true, + Computed: true, + }, + }, + } +} diff --git a/internal/service/cloudapi/lb/resource_lb_frontend.go b/internal/service/cloudapi/lb/resource_lb_frontend.go index 233bae8..438f040 100644 --- a/internal/service/cloudapi/lb/resource_lb_frontend.go +++ b/internal/service/cloudapi/lb/resource_lb_frontend.go @@ -1,191 +1,195 @@ -/* -Copyright (c) 2019-2022 Digital Energy Cloud Solutions LLC. All Rights Reserved. -Authors: -Petr Krutov, -Stanislav Solovev, -Kasim Baybikov, - -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 lb - -import ( - "context" - "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/lb" - "repository.basistech.ru/BASIS/terraform-provider-decort/internal/constants" - "repository.basistech.ru/BASIS/terraform-provider-decort/internal/controller" -) - -func resourceLBFrontendCreate(ctx context.Context, d *schema.ResourceData, m interface{}) diag.Diagnostics { - log.Debugf("resourceLBFrontendCreate") - - haveLBID, err := existLBID(ctx, d, m) - if err != nil { - return diag.FromErr(err) - } - - if !haveLBID { - return diag.Errorf("resourceLBFrontendCreate: can't create LB frontend because LBID %d is not allowed or does not exist", d.Get("lb_id").(int)) - } - - c := m.(*controller.ControllerCfg) - req := lb.FrontendCreateRequest{ - BackendName: d.Get("backend_name").(string), - LBID: uint64(d.Get("lb_id").(int)), - FrontendName: d.Get("name").(string), - } - - _, err = c.CloudAPI().LB().FrontendCreate(ctx, req) - if err != nil { - return diag.FromErr(err) - } - - d.SetId(strconv.Itoa(d.Get("lb_id").(int)) + "#" + d.Get("name").(string)) - - _, err = utilityLBFrontendCheckPresence(ctx, d, m) - if err != nil { - return diag.FromErr(err) - } - - return resourceLBFrontendRead(ctx, d, m) -} - -func resourceLBFrontendRead(ctx context.Context, d *schema.ResourceData, m interface{}) diag.Diagnostics { - log.Debugf("resourceLBFrontendRead") - - f, err := utilityLBFrontendCheckPresence(ctx, d, m) - if err != nil { - d.SetId("") - return diag.FromErr(err) - } - - lbId, _ := strconv.ParseInt(strings.Split(d.Id(), "#")[0], 10, 32) - - flattenLBFrontend(d, f, lbId) - - return nil -} - -func resourceLBFrontendDelete(ctx context.Context, d *schema.ResourceData, m interface{}) diag.Diagnostics { - log.Debugf("resourceLBFrontendDelete") - - _, err := utilityLBFrontendCheckPresence(ctx, d, m) - if err != nil { - return diag.FromErr(err) - } - - c := m.(*controller.ControllerCfg) - req := lb.FrontendDeleteRequest{ - LBID: uint64(d.Get("lb_id").(int)), - FrontendName: d.Get("name").(string), - } - - _, err = c.CloudAPI().LB().FrontendDelete(ctx, req) - if err != nil { - return diag.FromErr(err) - } - - d.SetId("") - - return nil -} - -func resourceLBFrontendEdit(ctx context.Context, d *schema.ResourceData, m interface{}) diag.Diagnostics { - return nil -} - -func ResourceLBFrontend() *schema.Resource { - return &schema.Resource{ - SchemaVersion: 1, - - CreateContext: resourceLBFrontendCreate, - ReadContext: resourceLBFrontendRead, - UpdateContext: resourceLBFrontendEdit, - DeleteContext: resourceLBFrontendDelete, - - Importer: &schema.ResourceImporter{ - StateContext: schema.ImportStatePassthroughContext, - }, - - Timeouts: &schema.ResourceTimeout{ - Create: &constants.Timeout600s, - Read: &constants.Timeout300s, - Update: &constants.Timeout300s, - Delete: &constants.Timeout300s, - Default: &constants.Timeout300s, - }, - - Schema: map[string]*schema.Schema{ - "lb_id": { - Type: schema.TypeInt, - Required: true, - Description: "ID of the LB instance to backendCreate", - }, - "backend_name": { - Type: schema.TypeString, - Required: true, - }, - "name": { - Type: schema.TypeString, - Required: true, - }, - "bindings": { - Type: schema.TypeList, - Computed: true, - Elem: &schema.Resource{ - Schema: map[string]*schema.Schema{ - "address": { - Type: schema.TypeString, - Computed: true, - }, - "guid": { - Type: schema.TypeString, - Computed: true, - }, - "name": { - Type: schema.TypeString, - Computed: true, - }, - "port": { - Type: schema.TypeInt, - Computed: true, - }, - }, - }, - }, - "guid": { - Type: schema.TypeString, - Computed: true, - }, - }, - } -} +/* +Copyright (c) 2019-2022 Digital Energy Cloud Solutions LLC. All Rights Reserved. +Authors: +Petr Krutov, +Stanislav Solovev, +Kasim Baybikov, + +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 lb + +import ( + "context" + "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/lb" + "repository.basistech.ru/BASIS/terraform-provider-decort/internal/constants" + "repository.basistech.ru/BASIS/terraform-provider-decort/internal/controller" +) + +func resourceLBFrontendCreate(ctx context.Context, d *schema.ResourceData, m interface{}) diag.Diagnostics { + log.Debugf("resourceLBFrontendCreate") + + haveLBID, err := existLBID(ctx, d, m) + if err != nil { + return diag.FromErr(err) + } + + if !haveLBID { + return diag.Errorf("resourceLBFrontendCreate: can't create LB frontend because LBID %d is not allowed or does not exist", d.Get("lb_id").(int)) + } + + c := m.(*controller.ControllerCfg) + req := lb.FrontendCreateRequest{ + BackendName: d.Get("backend_name").(string), + LBID: uint64(d.Get("lb_id").(int)), + FrontendName: d.Get("name").(string), + } + + _, err = c.CloudAPI().LB().FrontendCreate(ctx, req) + if err != nil { + d.SetId("") + return diag.FromErr(err) + } + + d.SetId(strconv.Itoa(d.Get("lb_id").(int)) + "#" + d.Get("name").(string)) + + _, err = utilityLBFrontendCheckPresence(ctx, d, m) + if err != nil { + d.SetId("") + return diag.FromErr(err) + } + + return resourceLBFrontendRead(ctx, d, m) +} + +func resourceLBFrontendRead(ctx context.Context, d *schema.ResourceData, m interface{}) diag.Diagnostics { + log.Debugf("resourceLBFrontendRead") + + f, err := utilityLBFrontendCheckPresence(ctx, d, m) + if err != nil { + d.SetId("") + return diag.FromErr(err) + } + + lbId, _ := strconv.ParseInt(strings.Split(d.Id(), "#")[0], 10, 32) + + flattenLBFrontend(d, f, lbId) + + return nil +} + +func resourceLBFrontendDelete(ctx context.Context, d *schema.ResourceData, m interface{}) diag.Diagnostics { + log.Debugf("resourceLBFrontendDelete") + + _, err := utilityLBFrontendCheckPresence(ctx, d, m) + if err != nil { + d.SetId("") + return diag.FromErr(err) + } + + c := m.(*controller.ControllerCfg) + req := lb.FrontendDeleteRequest{ + LBID: uint64(d.Get("lb_id").(int)), + FrontendName: d.Get("name").(string), + } + + _, err = c.CloudAPI().LB().FrontendDelete(ctx, req) + if err != nil { + d.SetId("") + return diag.FromErr(err) + } + + d.SetId("") + + return nil +} + +func resourceLBFrontendEdit(ctx context.Context, d *schema.ResourceData, m interface{}) diag.Diagnostics { + return nil +} + +func ResourceLBFrontend() *schema.Resource { + return &schema.Resource{ + SchemaVersion: 1, + + CreateContext: resourceLBFrontendCreate, + ReadContext: resourceLBFrontendRead, + UpdateContext: resourceLBFrontendEdit, + DeleteContext: resourceLBFrontendDelete, + + Importer: &schema.ResourceImporter{ + StateContext: schema.ImportStatePassthroughContext, + }, + + Timeouts: &schema.ResourceTimeout{ + Create: &constants.Timeout600s, + Read: &constants.Timeout300s, + Update: &constants.Timeout300s, + Delete: &constants.Timeout300s, + Default: &constants.Timeout300s, + }, + + Schema: map[string]*schema.Schema{ + "lb_id": { + Type: schema.TypeInt, + Required: true, + Description: "ID of the LB instance to backendCreate", + }, + "backend_name": { + Type: schema.TypeString, + Required: true, + }, + "name": { + Type: schema.TypeString, + Required: true, + }, + "bindings": { + Type: schema.TypeList, + Computed: true, + Elem: &schema.Resource{ + Schema: map[string]*schema.Schema{ + "address": { + Type: schema.TypeString, + Computed: true, + }, + "guid": { + Type: schema.TypeString, + Computed: true, + }, + "name": { + Type: schema.TypeString, + Computed: true, + }, + "port": { + Type: schema.TypeInt, + Computed: true, + }, + }, + }, + }, + "guid": { + Type: schema.TypeString, + Computed: true, + }, + }, + } +} diff --git a/internal/service/cloudapi/lb/resource_lb_frontend_bind.go b/internal/service/cloudapi/lb/resource_lb_frontend_bind.go index 9d83b5d..853f4bd 100644 --- a/internal/service/cloudapi/lb/resource_lb_frontend_bind.go +++ b/internal/service/cloudapi/lb/resource_lb_frontend_bind.go @@ -1,211 +1,216 @@ -/* -Copyright (c) 2019-2022 Digital Energy Cloud Solutions LLC. All Rights Reserved. -Authors: -Petr Krutov, -Stanislav Solovev, -Kasim Baybikov, - -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 lb - -import ( - "context" - "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/lb" - "repository.basistech.ru/BASIS/terraform-provider-decort/internal/constants" - "repository.basistech.ru/BASIS/terraform-provider-decort/internal/controller" -) - -func resourceLBFrontendBindCreate(ctx context.Context, d *schema.ResourceData, m interface{}) diag.Diagnostics { - log.Debugf("resourceLBFrontendBindCreate") - - haveLBID, err := existLBID(ctx, d, m) - if err != nil { - return diag.FromErr(err) - } - - if !haveLBID { - return diag.Errorf("resourceLBFrontendBindCreate: can't create LB frontend bind because LBID %d is not allowed or does not exist", d.Get("lb_id").(int)) - } - - c := m.(*controller.ControllerCfg) - req := lb.FrontendBindRequest{ - LBID: uint64(d.Get("lb_id").(int)), - FrontendName: d.Get("frontend_name").(string), - BindingName: d.Get("name").(string), - BindingAddress: d.Get("address").(string), - BindingPort: uint64(d.Get("port").(int)), - } - - _, err = c.CloudAPI().LB().FrontendBind(ctx, req) - if err != nil { - return diag.FromErr(err) - } - - d.SetId(strconv.Itoa(d.Get("lb_id").(int)) + "#" + d.Get("frontend_name").(string) + "#" + d.Get("name").(string)) - - _, err = utilityLBFrontendBindCheckPresence(ctx, d, m) - if err != nil { - return diag.FromErr(err) - } - - return resourceLBFrontendBindRead(ctx, d, m) -} - -func resourceLBFrontendBindRead(ctx context.Context, d *schema.ResourceData, m interface{}) diag.Diagnostics { - log.Debugf("resourceLBFrontendBindRead") - - b, err := utilityLBFrontendBindCheckPresence(ctx, d, m) - if err != nil { - d.SetId("") - return diag.FromErr(err) - } - - lbId, _ := strconv.ParseInt(strings.Split(d.Id(), "#")[0], 10, 32) - frontendName := strings.Split(d.Id(), "#")[1] - - flattenLBFrontendBind(d, b, lbId, frontendName) - - return nil -} - -func resourceLBFrontendBindDelete(ctx context.Context, d *schema.ResourceData, m interface{}) diag.Diagnostics { - log.Debugf("resourceLBFrontendBindDelete") - - _, err := utilityLBFrontendBindCheckPresence(ctx, d, m) - if err != nil { - return diag.FromErr(err) - } - - c := m.(*controller.ControllerCfg) - req := lb.FrontendBindDeleteRequest{ - LBID: uint64(d.Get("lb_id").(int)), - FrontendName: d.Get("frontend_name").(string), - BindingName: d.Get("name").(string), - } - - _, err = c.CloudAPI().LB().FrontendBindDelete(ctx, req) - if err != nil { - return diag.FromErr(err) - } - - d.SetId("") - - return nil -} - -func resourceLBFrontendBindUpdate(ctx context.Context, d *schema.ResourceData, m interface{}) diag.Diagnostics { - log.Debugf("resourceLBFrontendBindEdit") - c := m.(*controller.ControllerCfg) - - haveLBID, err := existLBID(ctx, d, m) - if err != nil { - return diag.FromErr(err) - } - - if !haveLBID { - return diag.Errorf("resourceLBFrontendBindUpdate: can't update LB frontend bind because LBID %d is not allowed or does not exist", d.Get("lb_id").(int)) - } - - req := lb.FrontendBindUpdateRequest{ - FrontendName: d.Get("frontend_name").(string), - BindingName: d.Get("name").(string), - LBID: uint64(d.Get("lb_id").(int)), - } - - if d.HasChange("address") { - req.BindingAddress = d.Get("address").(string) - } - - if d.HasChange("port") { - req.BindingPort = uint64(d.Get("port").(int)) - } - - _, err = c.CloudAPI().LB().FrontendBindUpdate(ctx, req) - if err != nil { - return diag.FromErr(err) - } - - return resourceLBFrontendBindRead(ctx, d, m) -} - -func ResourceLBFrontendBind() *schema.Resource { - return &schema.Resource{ - SchemaVersion: 1, - - CreateContext: resourceLBFrontendBindCreate, - ReadContext: resourceLBFrontendBindRead, - UpdateContext: resourceLBFrontendBindUpdate, - DeleteContext: resourceLBFrontendBindDelete, - - Importer: &schema.ResourceImporter{ - StateContext: schema.ImportStatePassthroughContext, - }, - - Timeouts: &schema.ResourceTimeout{ - Create: &constants.Timeout600s, - Read: &constants.Timeout300s, - Update: &constants.Timeout300s, - Delete: &constants.Timeout300s, - Default: &constants.Timeout300s, - }, - - Schema: map[string]*schema.Schema{ - "lb_id": { - Type: schema.TypeInt, - Required: true, - Description: "ID of the LB instance to backendCreate", - }, - "frontend_name": { - Type: schema.TypeString, - Required: true, - Description: "Must be unique among all backends of this LB - name of the new backend to create", - }, - "address": { - Type: schema.TypeString, - Required: true, - }, - "guid": { - Type: schema.TypeString, - Computed: true, - }, - "name": { - Type: schema.TypeString, - Required: true, - }, - "port": { - Type: schema.TypeInt, - Required: true, - }, - }, - } -} +/* +Copyright (c) 2019-2022 Digital Energy Cloud Solutions LLC. All Rights Reserved. +Authors: +Petr Krutov, +Stanislav Solovev, +Kasim Baybikov, + +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 lb + +import ( + "context" + "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/lb" + "repository.basistech.ru/BASIS/terraform-provider-decort/internal/constants" + "repository.basistech.ru/BASIS/terraform-provider-decort/internal/controller" +) + +func resourceLBFrontendBindCreate(ctx context.Context, d *schema.ResourceData, m interface{}) diag.Diagnostics { + log.Debugf("resourceLBFrontendBindCreate") + + haveLBID, err := existLBID(ctx, d, m) + if err != nil { + return diag.FromErr(err) + } + + if !haveLBID { + return diag.Errorf("resourceLBFrontendBindCreate: can't create LB frontend bind because LBID %d is not allowed or does not exist", d.Get("lb_id").(int)) + } + + c := m.(*controller.ControllerCfg) + req := lb.FrontendBindRequest{ + LBID: uint64(d.Get("lb_id").(int)), + FrontendName: d.Get("frontend_name").(string), + BindingName: d.Get("name").(string), + BindingAddress: d.Get("address").(string), + BindingPort: uint64(d.Get("port").(int)), + } + + _, err = c.CloudAPI().LB().FrontendBind(ctx, req) + if err != nil { + d.SetId("") + return diag.FromErr(err) + } + + d.SetId(strconv.Itoa(d.Get("lb_id").(int)) + "#" + d.Get("frontend_name").(string) + "#" + d.Get("name").(string)) + + _, err = utilityLBFrontendBindCheckPresence(ctx, d, m) + if err != nil { + d.SetId("") + return diag.FromErr(err) + } + + return resourceLBFrontendBindRead(ctx, d, m) +} + +func resourceLBFrontendBindRead(ctx context.Context, d *schema.ResourceData, m interface{}) diag.Diagnostics { + log.Debugf("resourceLBFrontendBindRead") + + b, err := utilityLBFrontendBindCheckPresence(ctx, d, m) + if err != nil { + d.SetId("") + return diag.FromErr(err) + } + + lbId, _ := strconv.ParseInt(strings.Split(d.Id(), "#")[0], 10, 32) + frontendName := strings.Split(d.Id(), "#")[1] + + flattenLBFrontendBind(d, b, lbId, frontendName) + + return nil +} + +func resourceLBFrontendBindDelete(ctx context.Context, d *schema.ResourceData, m interface{}) diag.Diagnostics { + log.Debugf("resourceLBFrontendBindDelete") + + _, err := utilityLBFrontendBindCheckPresence(ctx, d, m) + if err != nil { + d.SetId("") + return diag.FromErr(err) + } + + c := m.(*controller.ControllerCfg) + req := lb.FrontendBindDeleteRequest{ + LBID: uint64(d.Get("lb_id").(int)), + FrontendName: d.Get("frontend_name").(string), + BindingName: d.Get("name").(string), + } + + _, err = c.CloudAPI().LB().FrontendBindDelete(ctx, req) + if err != nil { + d.SetId("") + return diag.FromErr(err) + } + + d.SetId("") + + return nil +} + +func resourceLBFrontendBindUpdate(ctx context.Context, d *schema.ResourceData, m interface{}) diag.Diagnostics { + log.Debugf("resourceLBFrontendBindEdit") + c := m.(*controller.ControllerCfg) + + haveLBID, err := existLBID(ctx, d, m) + if err != nil { + return diag.FromErr(err) + } + + if !haveLBID { + return diag.Errorf("resourceLBFrontendBindUpdate: can't update LB frontend bind because LBID %d is not allowed or does not exist", d.Get("lb_id").(int)) + } + + req := lb.FrontendBindUpdateRequest{ + FrontendName: d.Get("frontend_name").(string), + BindingName: d.Get("name").(string), + LBID: uint64(d.Get("lb_id").(int)), + } + + if d.HasChange("address") { + req.BindingAddress = d.Get("address").(string) + } + + if d.HasChange("port") { + req.BindingPort = uint64(d.Get("port").(int)) + } + + _, err = c.CloudAPI().LB().FrontendBindUpdate(ctx, req) + if err != nil { + d.SetId("") + return diag.FromErr(err) + } + + return resourceLBFrontendBindRead(ctx, d, m) +} + +func ResourceLBFrontendBind() *schema.Resource { + return &schema.Resource{ + SchemaVersion: 1, + + CreateContext: resourceLBFrontendBindCreate, + ReadContext: resourceLBFrontendBindRead, + UpdateContext: resourceLBFrontendBindUpdate, + DeleteContext: resourceLBFrontendBindDelete, + + Importer: &schema.ResourceImporter{ + StateContext: schema.ImportStatePassthroughContext, + }, + + Timeouts: &schema.ResourceTimeout{ + Create: &constants.Timeout600s, + Read: &constants.Timeout300s, + Update: &constants.Timeout300s, + Delete: &constants.Timeout300s, + Default: &constants.Timeout300s, + }, + + Schema: map[string]*schema.Schema{ + "lb_id": { + Type: schema.TypeInt, + Required: true, + Description: "ID of the LB instance to backendCreate", + }, + "frontend_name": { + Type: schema.TypeString, + Required: true, + Description: "Must be unique among all backends of this LB - name of the new backend to create", + }, + "address": { + Type: schema.TypeString, + Required: true, + }, + "guid": { + Type: schema.TypeString, + Computed: true, + }, + "name": { + Type: schema.TypeString, + Required: true, + }, + "port": { + Type: schema.TypeInt, + Required: true, + }, + }, + } +} diff --git a/internal/service/cloudapi/locations/data_source_locations_list.go b/internal/service/cloudapi/locations/data_source_locations_list.go index 715c2d6..f5ebb8e 100644 --- a/internal/service/cloudapi/locations/data_source_locations_list.go +++ b/internal/service/cloudapi/locations/data_source_locations_list.go @@ -1,181 +1,190 @@ -/* -Copyright (c) 2019-2022 Digital Energy Cloud Solutions LLC. All Rights Reserved. -Authors: -Petr Krutov, -Stanislav Solovev, -Kasim Baybikov, - -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 locations - -import ( - "context" - - "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/locations" - "repository.basistech.ru/BASIS/terraform-provider-decort/internal/constants" - "repository.basistech.ru/BASIS/terraform-provider-decort/internal/flattens" -) - -func flattenLocationsList(ll *locations.ListLocations) []map[string]interface{} { - res := make([]map[string]interface{}, 0) - for _, l := range ll.Data { - temp := map[string]interface{}{ - "ckey": l.CKey, - "meta": flattens.FlattenMeta(l.Meta), - "flag": l.Flag, - "gid": l.GID, - "guid": l.GUID, - "id": l.ID, - "location_code": l.LocationCode, - "name": l.Name, - } - res = append(res, temp) - } - return res - -} - -func dataSourceLocationsListRead(ctx context.Context, d *schema.ResourceData, m interface{}) diag.Diagnostics { - locations, err := utilityLocationsListCheckPresence(ctx, d, m) - if err != nil { - return diag.FromErr(err) - } - - id := uuid.New() - d.SetId(id.String()) - - d.Set("items", flattenLocationsList(locations)) - d.Set("entry_count", locations.EntryCount) - - return nil -} - -func dataSourceLocationsListSchemaMake() map[string]*schema.Schema { - return map[string]*schema.Schema{ - "flag": { - Type: schema.TypeString, - Optional: true, - Description: "Filter by flag", - }, - "name": { - Type: schema.TypeString, - Optional: true, - Description: "Filter by name", - }, - "by_id": { - Type: schema.TypeInt, - Optional: true, - Description: "Filter by ID", - }, - "location_code": { - Type: schema.TypeString, - Optional: true, - Description: "Filter by location code", - }, - "page": { - Type: schema.TypeInt, - Optional: true, - Description: "page number", - }, - "size": { - Type: schema.TypeInt, - Optional: true, - Description: "page size", - }, - "items": { - Type: schema.TypeList, - Computed: true, - Description: "Locations list", - Elem: &schema.Resource{ - Schema: map[string]*schema.Schema{ - "ckey": { - Type: schema.TypeString, - Computed: true, - }, - "meta": { - Type: schema.TypeList, - Computed: true, - Elem: &schema.Schema{ - Type: schema.TypeString, - }, - }, - "flag": { - Type: schema.TypeString, - Computed: true, - }, - "gid": { - Type: schema.TypeInt, - Computed: true, - Description: "Grid id", - }, - "guid": { - Type: schema.TypeInt, - Computed: true, - Description: "location id", - }, - "id": { - Type: schema.TypeInt, - Computed: true, - Description: "location id", - }, - "location_code": { - Type: schema.TypeString, - Computed: true, - Description: "Location code", - }, - "name": { - Type: schema.TypeString, - Computed: true, - Description: "Location name", - }, - }, - }, - }, - "entry_count": { - Type: schema.TypeInt, - Computed: true, - }, - } -} - -func DataSourceLocationsList() *schema.Resource { - return &schema.Resource{ - SchemaVersion: 1, - - ReadContext: dataSourceLocationsListRead, - - Timeouts: &schema.ResourceTimeout{ - Read: &constants.Timeout30s, - Default: &constants.Timeout60s, - }, - - Schema: dataSourceLocationsListSchemaMake(), - } -} +/* +Copyright (c) 2019-2022 Digital Energy Cloud Solutions LLC. All Rights Reserved. +Authors: +Petr Krutov, +Stanislav Solovev, +Kasim Baybikov, + +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 locations + +import ( + "context" + + "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/locations" + "repository.basistech.ru/BASIS/terraform-provider-decort/internal/constants" + "repository.basistech.ru/BASIS/terraform-provider-decort/internal/flattens" +) + +func flattenLocationsList(ll *locations.ListLocations) []map[string]interface{} { + res := make([]map[string]interface{}, 0, len(ll.Data)) + for _, l := range ll.Data { + temp := map[string]interface{}{ + "ckey": l.CKey, + "meta": flattens.FlattenMeta(l.Meta), + "auth_broker": l.AuthBroker, + "flag": l.Flag, + "gid": l.GID, + "guid": l.GUID, + "id": l.ID, + "location_code": l.LocationCode, + "name": l.Name, + } + res = append(res, temp) + } + return res + +} + +func dataSourceLocationsListRead(ctx context.Context, d *schema.ResourceData, m interface{}) diag.Diagnostics { + locations, err := utilityLocationsListCheckPresence(ctx, d, m) + if err != nil { + d.SetId("") + return diag.FromErr(err) + } + + id := uuid.New() + d.SetId(id.String()) + + d.Set("items", flattenLocationsList(locations)) + d.Set("entry_count", locations.EntryCount) + + return nil +} + +func dataSourceLocationsListSchemaMake() map[string]*schema.Schema { + return map[string]*schema.Schema{ + "flag": { + Type: schema.TypeString, + Optional: true, + Description: "Filter by flag", + }, + "name": { + Type: schema.TypeString, + Optional: true, + Description: "Filter by name", + }, + "by_id": { + Type: schema.TypeInt, + Optional: true, + Description: "Filter by ID", + }, + "location_code": { + Type: schema.TypeString, + Optional: true, + Description: "Filter by location code", + }, + "page": { + Type: schema.TypeInt, + Optional: true, + Description: "page number", + }, + "size": { + Type: schema.TypeInt, + Optional: true, + Description: "page size", + }, + "items": { + Type: schema.TypeList, + Computed: true, + Description: "Locations list", + Elem: &schema.Resource{ + Schema: map[string]*schema.Schema{ + "ckey": { + Type: schema.TypeString, + Computed: true, + }, + "meta": { + Type: schema.TypeList, + Computed: true, + Elem: &schema.Schema{ + Type: schema.TypeString, + }, + }, + "auth_broker": { + Type: schema.TypeList, + Computed: true, + Elem: &schema.Schema{ + Type: schema.TypeString, + }, + }, + "flag": { + Type: schema.TypeString, + Computed: true, + }, + "gid": { + Type: schema.TypeInt, + Computed: true, + Description: "Grid id", + }, + "guid": { + Type: schema.TypeInt, + Computed: true, + Description: "location id", + }, + "id": { + Type: schema.TypeInt, + Computed: true, + Description: "location id", + }, + "location_code": { + Type: schema.TypeString, + Computed: true, + Description: "Location code", + }, + "name": { + Type: schema.TypeString, + Computed: true, + Description: "Location name", + }, + }, + }, + }, + "entry_count": { + Type: schema.TypeInt, + Computed: true, + }, + } +} + +func DataSourceLocationsList() *schema.Resource { + return &schema.Resource{ + SchemaVersion: 1, + + ReadContext: dataSourceLocationsListRead, + + Timeouts: &schema.ResourceTimeout{ + Read: &constants.Timeout30s, + Default: &constants.Timeout60s, + }, + + Schema: dataSourceLocationsListSchemaMake(), + } +} diff --git a/internal/service/cloudapi/locations/data_source_locations_url.go b/internal/service/cloudapi/locations/data_source_locations_url.go index ee16668..3a35681 100644 --- a/internal/service/cloudapi/locations/data_source_locations_url.go +++ b/internal/service/cloudapi/locations/data_source_locations_url.go @@ -1,84 +1,85 @@ -/* -Copyright (c) 2019-2022 Digital Energy Cloud Solutions LLC. All Rights Reserved. -Authors: -Petr Krutov, -Stanislav Solovev, -Kasim Baybikov, - -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 locations - -import ( - "context" - "strings" - - "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" -) - -func dataSourceLocationUrlRead(ctx context.Context, d *schema.ResourceData, m interface{}) diag.Diagnostics { - url, err := utilityLocationUrlCheckPresence(ctx, m) - if err != nil { - return diag.FromErr(err) - } - - id := uuid.New() - d.SetId(id.String()) - - url = strings.ReplaceAll(url, "\\", "") - url = strings.ReplaceAll(url, "\"", "") - d.Set("url", url) - - return nil -} - -func dataSourceLocationUrlSchemaMake() map[string]*schema.Schema { - return map[string]*schema.Schema{ - "url": { - Type: schema.TypeString, - Computed: true, - Description: "Location url", - }, - } -} - -func DataSourceLocationUrl() *schema.Resource { - return &schema.Resource{ - SchemaVersion: 1, - - ReadContext: dataSourceLocationUrlRead, - - Timeouts: &schema.ResourceTimeout{ - Read: &constants.Timeout30s, - Default: &constants.Timeout60s, - }, - - Schema: dataSourceLocationUrlSchemaMake(), - } -} +/* +Copyright (c) 2019-2022 Digital Energy Cloud Solutions LLC. All Rights Reserved. +Authors: +Petr Krutov, +Stanislav Solovev, +Kasim Baybikov, + +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 locations + +import ( + "context" + "strings" + + "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" +) + +func dataSourceLocationUrlRead(ctx context.Context, d *schema.ResourceData, m interface{}) diag.Diagnostics { + url, err := utilityLocationUrlCheckPresence(ctx, m) + if err != nil { + d.SetId("") + return diag.FromErr(err) + } + + id := uuid.New() + d.SetId(id.String()) + + url = strings.ReplaceAll(url, "\\", "") + url = strings.ReplaceAll(url, "\"", "") + d.Set("url", url) + + return nil +} + +func dataSourceLocationUrlSchemaMake() map[string]*schema.Schema { + return map[string]*schema.Schema{ + "url": { + Type: schema.TypeString, + Computed: true, + Description: "Location url", + }, + } +} + +func DataSourceLocationUrl() *schema.Resource { + return &schema.Resource{ + SchemaVersion: 1, + + ReadContext: dataSourceLocationUrlRead, + + Timeouts: &schema.ResourceTimeout{ + Read: &constants.Timeout30s, + Default: &constants.Timeout60s, + }, + + Schema: dataSourceLocationUrlSchemaMake(), + } +} diff --git a/internal/service/cloudapi/rg/data_source_rg.go b/internal/service/cloudapi/rg/data_source_rg.go index 180eb05..8af83d3 100644 --- a/internal/service/cloudapi/rg/data_source_rg.go +++ b/internal/service/cloudapi/rg/data_source_rg.go @@ -42,146 +42,172 @@ import ( "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" ) -func sepsSchemaMake() map[string]*schema.Schema { - res := map[string]*schema.Schema{ - "sep_id": { - Type: schema.TypeString, - Computed: true, - }, - "data_name": { - Type: schema.TypeString, - Computed: true, - }, - "disk_size": { - Type: schema.TypeFloat, - Computed: true, - }, - "disk_size_max": { - Type: schema.TypeInt, - Computed: true, - }, +func dataSourceResgroupRead(ctx context.Context, d *schema.ResourceData, m interface{}) diag.Diagnostics { + rg, err := utilityResgroupCheckPresence(ctx, d, m) + if err != nil { + d.SetId("") // ensure ID is empty in this case + return diag.FromErr(err) } - - return res + d.SetId(strconv.Itoa(d.Get("rg_id").(int))) + flattenRg(d, *rg) + return nil } -func resourcesSchemaMake() map[string]*schema.Schema { - res := map[string]*schema.Schema{ - "current": { - Type: schema.TypeList, - Computed: true, - Elem: &schema.Resource{ - Schema: map[string]*schema.Schema{ - "cpu": { - Type: schema.TypeInt, - Computed: true, - }, - "disk_size": { - Type: schema.TypeFloat, - Computed: true, - }, - "disk_size_max": { - Type: schema.TypeFloat, - Computed: true, - }, - "extips": { - Type: schema.TypeInt, - Computed: true, - }, - "exttraffic": { - Type: schema.TypeInt, - Computed: true, - }, - "gpu": { - Type: schema.TypeInt, - Computed: true, - }, - "ram": { - Type: schema.TypeInt, - Computed: true, - }, - "seps": { - Type: schema.TypeSet, - Computed: true, - Elem: &schema.Resource{ - Schema: map[string]*schema.Schema{ - "sep_id": { - Type: schema.TypeString, - Computed: true, - }, - "map": { - Type: schema.TypeMap, - Computed: true, - Elem: &schema.Schema{ - Type: schema.TypeString, - }, - }, - }, - }, - }, - }, - }, - }, - "reserved": { - Type: schema.TypeList, - Computed: true, - Elem: &schema.Resource{ - Schema: map[string]*schema.Schema{ - "cpu": { - Type: schema.TypeInt, - Computed: true, - }, - "disk_size": { - Type: schema.TypeFloat, - Computed: true, - }, - "disk_size_max": { - Type: schema.TypeInt, - Computed: true, - }, - "extips": { - Type: schema.TypeInt, - Computed: true, - }, - "exttraffic": { - Type: schema.TypeInt, - Computed: true, - }, - "gpu": { - Type: schema.TypeInt, - Computed: true, - }, - "ram": { - Type: schema.TypeInt, - Computed: true, - }, - "seps": { - Type: schema.TypeSet, - Computed: true, - Elem: &schema.Resource{ - Schema: map[string]*schema.Schema{ - "sep_id": { - Type: schema.TypeString, - Computed: true, - }, - "map": { - Type: schema.TypeMap, - Computed: true, - Elem: &schema.Schema{ - Type: schema.TypeString, - }, - }, - }, - }, - }, - }, - }, +func DataSourceResgroup() *schema.Resource { + return &schema.Resource{ + SchemaVersion: 1, + + ReadContext: dataSourceResgroupRead, + + Timeouts: &schema.ResourceTimeout{ + Read: &constants.Timeout30s, + Default: &constants.Timeout60s, }, - } - return res + Schema: dataSourceRgSchemaMake(), + } } +// func sepsSchemaMake() map[string]*schema.Schema { +// res := map[string]*schema.Schema{ +// "sep_id": { +// Type: schema.TypeString, +// Computed: true, +// }, +// "data_name": { +// Type: schema.TypeString, +// Computed: true, +// }, +// "disk_size": { +// Type: schema.TypeFloat, +// Computed: true, +// }, +// "disk_size_max": { +// Type: schema.TypeInt, +// Computed: true, +// }, +// } + +// return res +// } + +// func resourcesSchemaMake() map[string]*schema.Schema { +// res := map[string]*schema.Schema{ +// "current": { +// Type: schema.TypeList, +// Computed: true, +// Elem: &schema.Resource{ +// Schema: map[string]*schema.Schema{ +// "cpu": { +// Type: schema.TypeInt, +// Computed: true, +// }, +// "disk_size": { +// Type: schema.TypeFloat, +// Computed: true, +// }, +// "disk_size_max": { +// Type: schema.TypeFloat, +// Computed: true, +// }, +// "extips": { +// Type: schema.TypeInt, +// Computed: true, +// }, +// "exttraffic": { +// Type: schema.TypeInt, +// Computed: true, +// }, +// "gpu": { +// Type: schema.TypeInt, +// Computed: true, +// }, +// "ram": { +// Type: schema.TypeInt, +// Computed: true, +// }, +// "seps": { +// Type: schema.TypeSet, +// Computed: true, +// Elem: &schema.Resource{ +// Schema: map[string]*schema.Schema{ +// "sep_id": { +// Type: schema.TypeString, +// Computed: true, +// }, +// "map": { +// Type: schema.TypeMap, +// Computed: true, +// Elem: &schema.Schema{ +// Type: schema.TypeString, +// }, +// }, +// }, +// }, +// }, +// }, +// }, +// }, +// "reserved": { +// Type: schema.TypeList, +// Computed: true, +// Elem: &schema.Resource{ +// Schema: map[string]*schema.Schema{ +// "cpu": { +// Type: schema.TypeInt, +// Computed: true, +// }, +// "disk_size": { +// Type: schema.TypeFloat, +// Computed: true, +// }, +// "disk_size_max": { +// Type: schema.TypeInt, +// Computed: true, +// }, +// "extips": { +// Type: schema.TypeInt, +// Computed: true, +// }, +// "exttraffic": { +// Type: schema.TypeInt, +// Computed: true, +// }, +// "gpu": { +// Type: schema.TypeInt, +// Computed: true, +// }, +// "ram": { +// Type: schema.TypeInt, +// Computed: true, +// }, +// "seps": { +// Type: schema.TypeSet, +// Computed: true, +// Elem: &schema.Resource{ +// Schema: map[string]*schema.Schema{ +// "sep_id": { +// Type: schema.TypeString, +// Computed: true, +// }, +// "map": { +// Type: schema.TypeMap, +// Computed: true, +// Elem: &schema.Schema{ +// Type: schema.TypeString, +// }, +// }, +// }, +// }, +// }, +// }, +// }, +// }, +// } + +// return res +// } + func aclSchemaMake() map[string]*schema.Schema { res := map[string]*schema.Schema{ "explicit": { @@ -391,29 +417,3 @@ func dataSourceRgSchemaMake() map[string]*schema.Schema { } return res } - -func dataSourceResgroupRead(ctx context.Context, d *schema.ResourceData, m interface{}) diag.Diagnostics { - rg, err := utilityResgroupCheckPresence(ctx, d, m) - if err != nil { - d.SetId("") // ensure ID is empty in this case - return diag.FromErr(err) - } - d.SetId(strconv.Itoa(d.Get("rg_id").(int))) - flattenRg(d, *rg) - return nil -} - -func DataSourceResgroup() *schema.Resource { - return &schema.Resource{ - SchemaVersion: 1, - - ReadContext: dataSourceResgroupRead, - - Timeouts: &schema.ResourceTimeout{ - Read: &constants.Timeout30s, - Default: &constants.Timeout60s, - }, - - Schema: dataSourceRgSchemaMake(), - } -} diff --git a/internal/service/cloudapi/rg/data_source_rg_affinity_group_computes.go b/internal/service/cloudapi/rg/data_source_rg_affinity_group_computes.go index fe8ffa1..e0e80f8 100644 --- a/internal/service/cloudapi/rg/data_source_rg_affinity_group_computes.go +++ b/internal/service/cloudapi/rg/data_source_rg_affinity_group_computes.go @@ -44,6 +44,7 @@ import ( func dataSourceRgAffinityGroupComputesRead(ctx context.Context, d *schema.ResourceData, m interface{}) diag.Diagnostics { rgComputes, err := utilityRgAffinityGroupComputesCheckPresence(ctx, d, m) if err != nil { + d.SetId("") return diag.FromErr(err) } @@ -64,7 +65,6 @@ func dataSourceRgAffinityGroupComputesSchemaMake() map[string]*schema.Schema { Required: true, Description: "Affinity group label", }, - "items": { Type: schema.TypeList, Computed: true, diff --git a/internal/service/cloudapi/rg/data_source_rg_affinity_groups_get.go b/internal/service/cloudapi/rg/data_source_rg_affinity_groups_get.go index c8627d9..bd4e719 100644 --- a/internal/service/cloudapi/rg/data_source_rg_affinity_groups_get.go +++ b/internal/service/cloudapi/rg/data_source_rg_affinity_groups_get.go @@ -44,6 +44,7 @@ import ( func dataSourceRgAffinityGroupsGetRead(ctx context.Context, d *schema.ResourceData, m interface{}) diag.Diagnostics { computes, err := utilityRgAffinityGroupsGetCheckPresence(ctx, d, m) if err != nil { + d.SetId("") return diag.FromErr(err) } d.SetId(strconv.Itoa(d.Get("rg_id").(int))) @@ -63,7 +64,6 @@ func dataSourceRgAffinityGroupsGetSchemaMake() map[string]*schema.Schema { Required: true, Description: "Affinity group label", }, - "ids": { Type: schema.TypeList, Computed: true, diff --git a/internal/service/cloudapi/rg/data_source_rg_affinity_groups_list.go b/internal/service/cloudapi/rg/data_source_rg_affinity_groups_list.go index 9f869cd..5bf5947 100644 --- a/internal/service/cloudapi/rg/data_source_rg_affinity_groups_list.go +++ b/internal/service/cloudapi/rg/data_source_rg_affinity_groups_list.go @@ -44,6 +44,7 @@ import ( func dataSourceRgAffinityGroupsListRead(ctx context.Context, d *schema.ResourceData, m interface{}) diag.Diagnostics { list, err := utilityRgAffinityGroupsListCheckPresence(ctx, d, m) if err != nil { + d.SetId("") return diag.FromErr(err) } diff --git a/internal/service/cloudapi/rg/data_source_rg_audits.go b/internal/service/cloudapi/rg/data_source_rg_audits.go index b634a79..1acf413 100644 --- a/internal/service/cloudapi/rg/data_source_rg_audits.go +++ b/internal/service/cloudapi/rg/data_source_rg_audits.go @@ -44,6 +44,7 @@ import ( func dataSourceRgAuditsRead(ctx context.Context, d *schema.ResourceData, m interface{}) diag.Diagnostics { rgAudits, err := utilityRgAuditsCheckPresence(ctx, d, m) if err != nil { + d.SetId("") return diag.FromErr(err) } @@ -59,7 +60,6 @@ func dataSourceRgAuditsSchemaMake() map[string]*schema.Schema { Type: schema.TypeInt, Required: true, }, - "items": { Type: schema.TypeList, Computed: true, diff --git a/internal/service/cloudapi/rg/data_source_rg_get_resource_consumption.go b/internal/service/cloudapi/rg/data_source_rg_get_resource_consumption.go index c36ed25..033bc37 100644 --- a/internal/service/cloudapi/rg/data_source_rg_get_resource_consumption.go +++ b/internal/service/cloudapi/rg/data_source_rg_get_resource_consumption.go @@ -44,6 +44,7 @@ import ( func dataSourceRGResourceConsumptionGetRead(ctx context.Context, d *schema.ResourceData, m interface{}) diag.Diagnostics { RGResourceConsumptionRec, err := utilityRGResourceConsumptionGetCheckPresence(ctx, d, m) if err != nil { + d.SetId("") return diag.FromErr(err) } diff --git a/internal/service/cloudapi/rg/data_source_rg_list.go b/internal/service/cloudapi/rg/data_source_rg_list.go index 3005083..ee8b164 100644 --- a/internal/service/cloudapi/rg/data_source_rg_list.go +++ b/internal/service/cloudapi/rg/data_source_rg_list.go @@ -1,287 +1,280 @@ -/* -Copyright (c) 2019-2022 Digital Energy Cloud Solutions LLC. All Rights Reserved. -Authors: -Petr Krutov, -Stanislav Solovev, -Kasim Baybikov, - -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 rg - -import ( - "context" - - "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" -) - -func dataSourceRgListRead(ctx context.Context, d *schema.ResourceData, m interface{}) diag.Diagnostics { - rgList, err := utilityRgListCheckPresence(ctx, d, m) - if err != nil { - return diag.FromErr(err) - } - - id := uuid.New() - d.SetId(id.String()) - d.Set("items", flattenRgList(rgList)) - d.Set("entry_count", rgList.EntryCount) - - return nil -} - -func dataSourceRgListSchemaMake() map[string]*schema.Schema { - res := map[string]*schema.Schema{ - "by_id": { - Type: schema.TypeInt, - Optional: true, - Description: "Find by ID", - }, - "name": { - Type: schema.TypeString, - Optional: true, - Description: "Find by name", - }, - "account_id": { - Type: schema.TypeInt, - Optional: true, - Description: "Find by account ID", - }, - "account_name": { - Type: schema.TypeString, - Optional: true, - Description: "Find by account name", - }, - "created_after": { - Type: schema.TypeInt, - Optional: true, - Description: "Find RGs created after specific time (unix timestamp)", - }, - "created_before": { - Type: schema.TypeInt, - Optional: true, - Description: "Find RGs created before specific time (unix timestamp)", - }, - "status": { - Type: schema.TypeString, - Optional: true, - Description: "Find by status", - }, - "lock_status": { - Type: schema.TypeString, - Optional: true, - Description: "Find by lock status", - }, - "includedeleted": { - Type: schema.TypeBool, - Optional: true, - Default: false, - Description: "included deleted resource groups", - }, - "page": { - Type: schema.TypeInt, - Optional: true, - Description: "Page number", - }, - "size": { - Type: schema.TypeInt, - Optional: true, - Description: "Page size", - }, - - "items": { - Type: schema.TypeList, - Computed: true, - Elem: &schema.Resource{ - Schema: map[string]*schema.Schema{ - "account_acl": { - Type: schema.TypeList, - Computed: true, - Elem: &schema.Resource{ - Schema: aclSchemaMake(), - }, - }, - "account_id": { - Type: schema.TypeInt, - Computed: true, - }, - "account_name": { - Type: schema.TypeString, - Computed: true, - }, - "acl": { - Type: schema.TypeList, - Computed: true, - Elem: &schema.Resource{ - Schema: aclSchemaMake(), - }, - }, - "created_by": { - Type: schema.TypeString, - Computed: true, - }, - "created_time": { - Type: schema.TypeInt, - Computed: true, - }, - "def_net_id": { - Type: schema.TypeInt, - Computed: true, - }, - "def_net_type": { - Type: schema.TypeString, - Computed: true, - }, - "deleted_by": { - Type: schema.TypeString, - Computed: true, - }, - "deleted_time": { - Type: schema.TypeInt, - Computed: true, - }, - "desc": { - Type: schema.TypeString, - Computed: true, - }, - "dirty": { - Type: schema.TypeBool, - Computed: true, - }, - "gid": { - Type: schema.TypeInt, - Computed: true, - }, - "guid": { - Type: schema.TypeInt, - Computed: true, - }, - "rg_id": { - Type: schema.TypeInt, - Computed: true, - }, - "lock_status": { - Type: schema.TypeString, - Computed: true, - }, - "milestones": { - Type: schema.TypeInt, - Computed: true, - }, - "name": { - Type: schema.TypeString, - Computed: true, - }, - "register_computes": { - Type: schema.TypeBool, - Computed: true, - }, - "resource_limits": { - Type: schema.TypeList, - Computed: true, - Elem: &schema.Resource{ - Schema: resourceLimitsSchemaMake(), - }, - }, - "secret": { - Type: schema.TypeString, - Computed: true, - }, - "status": { - Type: schema.TypeString, - Computed: true, - }, - "updated_by": { - Type: schema.TypeString, - Computed: true, - }, - "updated_time": { - Type: schema.TypeInt, - Computed: true, - }, - "vins": { - Type: schema.TypeList, - Computed: true, - Elem: &schema.Schema{ - Type: schema.TypeInt, - }, - }, - "vms": { - Type: schema.TypeList, - Computed: true, - Elem: &schema.Schema{ - Type: schema.TypeInt, - }, - }, - "resource_types": { - Type: schema.TypeList, - Computed: true, - Elem: &schema.Schema{ - Type: schema.TypeString, - }, - }, - "cpu_allocation_parameter": { - Type: schema.TypeString, - Computed: true, - }, - "cpu_allocation_ratio": { - Type: schema.TypeFloat, - Computed: true, - }, - "uniq_pools": { - Type: schema.TypeList, - Computed: true, - Elem: &schema.Schema{ - Type: schema.TypeString, - }, - }, - }, - }, - }, - "entry_count": { - Type: schema.TypeInt, - Computed: true, - }, - } - return res -} - -func DataSourceRgList() *schema.Resource { - return &schema.Resource{ - SchemaVersion: 1, - - ReadContext: dataSourceRgListRead, - - Timeouts: &schema.ResourceTimeout{ - Read: &constants.Timeout30s, - Default: &constants.Timeout60s, - }, - - Schema: dataSourceRgListSchemaMake(), - } -} +/* +Copyright (c) 2019-2022 Digital Energy Cloud Solutions LLC. All Rights Reserved. +Authors: +Petr Krutov, +Stanislav Solovev, +Kasim Baybikov, + +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 rg + +import ( + "context" + + "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" +) + +func dataSourceRgListRead(ctx context.Context, d *schema.ResourceData, m interface{}) diag.Diagnostics { + rgList, err := utilityRgListCheckPresence(ctx, d, m) + if err != nil { + d.SetId("") + return diag.FromErr(err) + } + + id := uuid.New() + d.SetId(id.String()) + d.Set("items", flattenRgList(rgList)) + d.Set("entry_count", rgList.EntryCount) + + return nil +} + +func dataSourceRgListSchemaMake() map[string]*schema.Schema { + res := map[string]*schema.Schema{ + "by_id": { + Type: schema.TypeInt, + Optional: true, + Description: "Find by ID", + }, + "name": { + Type: schema.TypeString, + Optional: true, + Description: "Find by name", + }, + "account_id": { + Type: schema.TypeInt, + Optional: true, + Description: "Find by account ID", + }, + "account_name": { + Type: schema.TypeString, + Optional: true, + Description: "Find by account name", + }, + "created_after": { + Type: schema.TypeInt, + Optional: true, + Description: "Find RGs created after specific time (unix timestamp)", + }, + "created_before": { + Type: schema.TypeInt, + Optional: true, + Description: "Find RGs created before specific time (unix timestamp)", + }, + "status": { + Type: schema.TypeString, + Optional: true, + Description: "Find by status", + }, + "lock_status": { + Type: schema.TypeString, + Optional: true, + Description: "Find by lock status", + }, + "includedeleted": { + Type: schema.TypeBool, + Optional: true, + Default: false, + Description: "included deleted resource groups", + }, + "page": { + Type: schema.TypeInt, + Optional: true, + Description: "Page number", + }, + "size": { + Type: schema.TypeInt, + Optional: true, + Description: "Page size", + }, + "items": { + Type: schema.TypeList, + Computed: true, + Elem: &schema.Resource{ + Schema: map[string]*schema.Schema{ + "account_acl": { + Type: schema.TypeList, + Computed: true, + Elem: &schema.Resource{ + Schema: aclSchemaMake(), + }, + }, + "account_id": { + Type: schema.TypeInt, + Computed: true, + }, + "account_name": { + Type: schema.TypeString, + Computed: true, + }, + "created_by": { + Type: schema.TypeString, + Computed: true, + }, + "created_time": { + Type: schema.TypeInt, + Computed: true, + }, + "def_net_id": { + Type: schema.TypeInt, + Computed: true, + }, + "def_net_type": { + Type: schema.TypeString, + Computed: true, + }, + "deleted_by": { + Type: schema.TypeString, + Computed: true, + }, + "deleted_time": { + Type: schema.TypeInt, + Computed: true, + }, + "desc": { + Type: schema.TypeString, + Computed: true, + }, + "dirty": { + Type: schema.TypeBool, + Computed: true, + }, + "gid": { + Type: schema.TypeInt, + Computed: true, + }, + "guid": { + Type: schema.TypeInt, + Computed: true, + }, + "rg_id": { + Type: schema.TypeInt, + Computed: true, + }, + "lock_status": { + Type: schema.TypeString, + Computed: true, + }, + "milestones": { + Type: schema.TypeInt, + Computed: true, + }, + "name": { + Type: schema.TypeString, + Computed: true, + }, + "register_computes": { + Type: schema.TypeBool, + Computed: true, + }, + "resource_limits": { + Type: schema.TypeList, + Computed: true, + Elem: &schema.Resource{ + Schema: resourceLimitsSchemaMake(), + }, + }, + "secret": { + Type: schema.TypeString, + Computed: true, + }, + "status": { + Type: schema.TypeString, + Computed: true, + }, + "updated_by": { + Type: schema.TypeString, + Computed: true, + }, + "updated_time": { + Type: schema.TypeInt, + Computed: true, + }, + "vins": { + Type: schema.TypeList, + Computed: true, + Elem: &schema.Schema{ + Type: schema.TypeInt, + }, + }, + "vms": { + Type: schema.TypeList, + Computed: true, + Elem: &schema.Schema{ + Type: schema.TypeInt, + }, + }, + "resource_types": { + Type: schema.TypeList, + Computed: true, + Elem: &schema.Schema{ + Type: schema.TypeString, + }, + }, + "cpu_allocation_parameter": { + Type: schema.TypeString, + Computed: true, + }, + "cpu_allocation_ratio": { + Type: schema.TypeFloat, + Computed: true, + }, + "uniq_pools": { + Type: schema.TypeList, + Computed: true, + Elem: &schema.Schema{ + Type: schema.TypeString, + }, + }, + }, + }, + }, + "entry_count": { + Type: schema.TypeInt, + Computed: true, + }, + } + return res +} + +func DataSourceRgList() *schema.Resource { + return &schema.Resource{ + SchemaVersion: 1, + + ReadContext: dataSourceRgListRead, + + Timeouts: &schema.ResourceTimeout{ + Read: &constants.Timeout30s, + Default: &constants.Timeout60s, + }, + + Schema: dataSourceRgListSchemaMake(), + } +} diff --git a/internal/service/cloudapi/rg/data_source_rg_list_computes.go b/internal/service/cloudapi/rg/data_source_rg_list_computes.go index 12d5d9d..a8b68b9 100644 --- a/internal/service/cloudapi/rg/data_source_rg_list_computes.go +++ b/internal/service/cloudapi/rg/data_source_rg_list_computes.go @@ -44,6 +44,7 @@ import ( func dataSourceRgListComputesRead(ctx context.Context, d *schema.ResourceData, m interface{}) diag.Diagnostics { listComputes, err := utilityRgListComputesCheckPresence(ctx, d, m) if err != nil { + d.SetId("") return diag.FromErr(err) } diff --git a/internal/service/cloudapi/rg/data_source_rg_list_deleted.go b/internal/service/cloudapi/rg/data_source_rg_list_deleted.go index 21d54ca..34e7240 100644 --- a/internal/service/cloudapi/rg/data_source_rg_list_deleted.go +++ b/internal/service/cloudapi/rg/data_source_rg_list_deleted.go @@ -44,6 +44,7 @@ import ( func dataSourceRgListDeletedRead(ctx context.Context, d *schema.ResourceData, m interface{}) diag.Diagnostics { rgList, err := utilityRgListDeletedCheckPresence(ctx, d, m) if err != nil { + d.SetId("") return diag.FromErr(err) } @@ -122,12 +123,13 @@ func dataSourceRgListDeletedSchemaMake() map[string]*schema.Schema { Type: schema.TypeString, Computed: true, }, - "acl": { - Type: schema.TypeList, + "cpu_allocation_parameter": { + Type: schema.TypeString, + Computed: true, + }, + "cpu_allocation_ratio": { + Type: schema.TypeFloat, Computed: true, - Elem: &schema.Resource{ - Schema: aclSchemaMake(), - }, }, "created_by": { Type: schema.TypeString, diff --git a/internal/service/cloudapi/rg/data_source_rg_list_lb.go b/internal/service/cloudapi/rg/data_source_rg_list_lb.go index ff0f62d..280ee4f 100644 --- a/internal/service/cloudapi/rg/data_source_rg_list_lb.go +++ b/internal/service/cloudapi/rg/data_source_rg_list_lb.go @@ -44,6 +44,7 @@ import ( func dataSourceRgListLbRead(ctx context.Context, d *schema.ResourceData, m interface{}) diag.Diagnostics { listLb, err := utilityRgListLbCheckPresence(ctx, d, m) if err != nil { + d.SetId("") return diag.FromErr(err) } @@ -307,6 +308,10 @@ func dataSourceRgListLbSchemaMake() map[string]*schema.Schema { Schema: aclSchemaMake(), }, }, + "backend_haip": { + Type: schema.TypeString, + Computed: true, + }, "backends": { Type: schema.TypeList, Computed: true, @@ -342,6 +347,10 @@ func dataSourceRgListLbSchemaMake() map[string]*schema.Schema { Type: schema.TypeInt, Computed: true, }, + "frontend_haip": { + Type: schema.TypeString, + Computed: true, + }, "frontends": { Type: schema.TypeList, Computed: true, diff --git a/internal/service/cloudapi/rg/data_source_rg_list_pfw.go b/internal/service/cloudapi/rg/data_source_rg_list_pfw.go index 6125843..ea97a1d 100644 --- a/internal/service/cloudapi/rg/data_source_rg_list_pfw.go +++ b/internal/service/cloudapi/rg/data_source_rg_list_pfw.go @@ -44,6 +44,7 @@ import ( func dataSourceRgListPfwRead(ctx context.Context, d *schema.ResourceData, m interface{}) diag.Diagnostics { listPfw, err := utilityRgListPfwCheckPresence(ctx, d, m) if err != nil { + d.SetId("") return diag.FromErr(err) } diff --git a/internal/service/cloudapi/rg/data_source_rg_list_vins.go b/internal/service/cloudapi/rg/data_source_rg_list_vins.go index a5b96a9..fe449e5 100644 --- a/internal/service/cloudapi/rg/data_source_rg_list_vins.go +++ b/internal/service/cloudapi/rg/data_source_rg_list_vins.go @@ -44,6 +44,7 @@ import ( func dataSourceRgListVinsRead(ctx context.Context, d *schema.ResourceData, m interface{}) diag.Diagnostics { listVins, err := utilityRgListVinsCheckPresence(ctx, d, m) if err != nil { + d.SetId("") return diag.FromErr(err) } diff --git a/internal/service/cloudapi/rg/data_source_rg_resource_consumption_list.go b/internal/service/cloudapi/rg/data_source_rg_resource_consumption_list.go index 019c10d..3ce473b 100644 --- a/internal/service/cloudapi/rg/data_source_rg_resource_consumption_list.go +++ b/internal/service/cloudapi/rg/data_source_rg_resource_consumption_list.go @@ -44,6 +44,7 @@ import ( func dataSourceRGResourceConsumptionListRead(ctx context.Context, d *schema.ResourceData, m interface{}) diag.Diagnostics { rgResourceConsumptionList, err := utilityRGResourceConsumptionListCheckPresence(ctx, d, m) if err != nil { + d.SetId("") return diag.FromErr(err) } diff --git a/internal/service/cloudapi/rg/data_source_rg_usage.go b/internal/service/cloudapi/rg/data_source_rg_usage.go index c5b8c00..9b49b61 100644 --- a/internal/service/cloudapi/rg/data_source_rg_usage.go +++ b/internal/service/cloudapi/rg/data_source_rg_usage.go @@ -44,6 +44,7 @@ import ( func dataSourceRgUsageRead(ctx context.Context, d *schema.ResourceData, m interface{}) diag.Diagnostics { usage, err := utilityDataRgUsageCheckPresence(ctx, d, m) if err != nil { + d.SetId("") return diag.FromErr(err) } diff --git a/internal/service/cloudapi/rg/flattens.go b/internal/service/cloudapi/rg/flattens.go index d7c7746..a06c20c 100644 --- a/internal/service/cloudapi/rg/flattens.go +++ b/internal/service/cloudapi/rg/flattens.go @@ -91,7 +91,6 @@ func flattenResgroup(d *schema.ResourceData, details rg.RecordResourceGroup) err d.Set("gid", details.GID) d.Set("def_net_type", details.DefNetType) d.Set("name", details.Name) - // d.Set("resources", flattenRgResource(details.Resources)) d.Set("account_name", details.AccountName) d.Set("acl", flattenRgAcl(details.ACL)) @@ -213,7 +212,6 @@ func flattenRgList(rgl *rg.ListResourceGroups) []map[string]interface{} { "account_acl": flattenRgAcl(rg.ACL), "account_id": rg.AccountID, "account_name": rg.AccountName, - "acl": flattenRgAcl(rg.ACL), "created_by": rg.CreatedBy, "created_time": rg.CreatedTime, "def_net_id": rg.DefNetID, @@ -431,6 +429,7 @@ func flattenRgListLb(listLb *rg.ListLB) []map[string]interface{} { temp := map[string]interface{}{ "ha_mode": lb.HAMode, "acl": lb.ACL, + "backend_haip": lb.BackendHAIP, "backends": flattenBackends(lb.Backends), "created_by": lb.CreatedBy, "created_time": lb.CreatedTime, @@ -439,6 +438,7 @@ func flattenRgListLb(listLb *rg.ListLB) []map[string]interface{} { "desc": lb.Description, "dp_api_user": lb.DPAPIUser, "extnet_id": lb.ExtNetID, + "frontend_haip": lb.FrontendHAIP, "frontends": flattenFrontends(lb.Frontends), "gid": lb.GID, "guid": lb.GUID, diff --git a/internal/service/cloudapi/rg/models.go b/internal/service/cloudapi/rg/models.go index a9a8c8d..cd45a9a 100644 --- a/internal/service/cloudapi/rg/models.go +++ b/internal/service/cloudapi/rg/models.go @@ -1,749 +1,749 @@ -/* -Copyright (c) 2019-2022 Digital Energy Cloud Solutions LLC. All Rights Reserved. -Authors: -Petr Krutov, -Stanislav Solovev, -Kasim Baybikov, - -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 rg - -type ResourceLimits struct { - CUC float64 `json:"CU_C"` - CUD float64 `json:"CU_D"` - CUI float64 `json:"CU_I"` - CUM float64 `json:"CU_M"` - CUNP float64 `json:"CU_NP"` - GpuUnits float64 `json:"gpu_units"` -} - -type QuotaRecord struct { // this is how quota is reported by /api/.../rg/get - Cpu int `json:"CU_C"` // CPU count in pcs - Ram float64 `json:"CU_M"` // RAM volume in MB, it is STILL reported as FLOAT - Disk int `json:"CU_D"` // Disk capacity in GB - ExtIPs int `json:"CU_I"` // Ext IPs count - ExtTraffic int `json:"CU_NP"` // Ext network traffic - GpuUnits int `json:"gpu_units"` // GPU count -} - -// Main information about audit -type ItemAudit struct { - // Call - Call string `json:"call"` - - // Response time - ResponseTime float64 `json:"responsetime"` - - // Status code - StatusCode uint64 `json:"statuscode"` - - // Timestamp - Timestamp float64 `json:"timestamp"` - - // User - User string `json:"user"` -} - -// List of audits -type ListAudits []ItemAudit - -// Resources used -type Resource struct { - // Number of cores - CPU int64 `json:"cpu"` - - // Disk size - DiskSize float64 `json:"disksize"` - - // Max disk size - DiskSizeMax uint64 `json:"disksizemax"` - - // Number of External IPs - ExtIPs int64 `json:"extips"` - - // External traffic - ExtTraffic int64 `json:"exttraffic"` - - // Number of grafic cores - GPU int64 `json:"gpu"` - - // Number of RAM - RAM int64 `json:"ram"` - - // SEPs - SEPs map[string]map[string]DiskUsage `json:"seps"` -} - -// Disk usage -type DiskUsage struct { - // Disk size - DiskSize float64 `json:"disksize"` - - // Disk size max - DiskSizeMax float64 `json:"disksizemax"` -} - -// Information about resources -type Resources struct { - // Current information about resources - Current Resource `json:"Current"` - - // Reserved information about resources - Reserved Resource `json:"Reserved"` -} - -// Detailed information about resource group -type RecordResourceGroup struct { - // Resources - Resources Resources `json:"Resources"` - - // Account ID - AccountID uint64 `json:"accountId"` - - // Account name - AccountName string `json:"accountName"` - - // Access Control List - ACL ListACL `json:"acl"` - - // Created by - CreatedBy string `json:"createdBy"` - - // Created time - CreatedTime uint64 `json:"createdTime"` - - // DefNetID - DefNetID int64 `json:"def_net_id"` - - // DefNetType - DefNetType string `json:"def_net_type"` - - // Deleted by - DeletedBy string `json:"deletedBy"` - - // Deleted time - DeletedTime uint64 `json:"deletedTime"` - - // Description - Description string `json:"desc"` - - // Dirty - Dirty bool `json:"dirty"` - - // Grid ID - GID uint64 `json:"gid"` - - // GUID - GUID uint64 `json:"guid"` - - // ID - ID uint64 `json:"id"` - - // Lock status - LockStatus string `json:"lockStatus"` - - // Milestones - Milestones uint64 `json:"milestones"` - - // Name - Name string `json:"name"` - - // RegisterComputes - RegisterComputes bool `json:"registerComputes"` - - // Resource limits - ResourceLimits ResourceLimits `json:"resourceLimits"` - - // Secret - Secret string `json:"secret"` - - // Status - Status string `json:"status"` - - // Updated by - UpdatedBy string `json:"updatedBy"` - - // Updated time - UpdatedTime uint64 `json:"updatedTime"` - - // List of VINS IDs - VINS []uint64 `json:"vins"` - - // List of compute IDs - Computes []uint64 `json:"vms"` - - // List of resource types - ResTypes []string `json:"resourceTypes"` - - // UniqPools - UniqPools []string `json:"uniqPools"` -} - -// Main information about Access Control List -type ItemACL struct { - // Explicit - Explicit bool `json:"explicit"` - - // GUID - GUID string `json:"guid"` - - // Right - Right string `json:"right"` - - // Status - Status string `json:"status"` - - // Type - Type string `json:"type"` - - // User group ID - UserGroupID string `json:"userGroupId"` -} - -// List ACL -type ListACL []ItemACL - -type ItemResourceGroup struct { - // - AccountACL ItemACL `json:"accountAcl"` - - // Account ID - AccountID uint64 `json:"accountId"` - - // Account name - AccountName string `json:"accountName"` - - // Access Control List - ACL ListACL `json:"acl"` - - // Created by - CreatedBy string `json:"createdBy"` - - // Created time - CreatedTime uint64 `json:"createdTime"` - - // DefNetID - DefNetID int64 `json:"def_net_id"` - - // DefNetType - DefNetType string `json:"def_net_type"` - - // Deleted by - DeletedBy string `json:"deletedBy"` - - // Deleted time - DeletedTime uint64 `json:"deletedTime"` - - // Description - Description string `json:"desc"` - - // Dirty - Dirty bool `json:"dirty"` - - // Grid ID - GID uint64 `json:"gid"` - - // GUID - GUID uint64 `json:"guid"` - - // ID - ID uint64 `json:"id"` - - // Lock status - LockStatus string `json:"lockStatus"` - - // Milestones - Milestones uint64 `json:"milestones"` - - // Name - Name string `json:"name"` - - // RegisterComputes - RegisterComputes bool `json:"registerComputes"` - - // Resource limits - ResourceLimits ResourceLimits `json:"resourceLimits"` - - // Secret - Secret string `json:"secret"` - - // Status - Status string `json:"status"` - - // Updated by - UpdatedBy string `json:"updatedBy"` - - // Updated time - UpdatedTime uint64 `json:"updatedTime"` - - // List of VINS IDs - VINS []uint64 `json:"vins"` - - // List of compute IDs - Computes []uint64 `json:"vms"` - - // List of resource types - ResTypes []string `json:"resourceTypes"` - - // UniqPools - UniqPools []string `json:"uniqPools"` -} - -// List of resource groups -type ListResourceGroups []ItemResourceGroup - -// Main information about affinity rule -type ItemRule struct { - // GUID - GUID string `json:"guid"` - - // Key - Key string `json:"key"` - - // Mode - Mode string `json:"mode"` - - // Policy - Policy string `json:"policy"` - - // Topology - Topology string `json:"topology"` - - // Value - Value string `json:"value"` -} - -// List rules -type ListRules []ItemRule - -// Main information about compute -type ItemCompute struct { - // Account ID - AccountID uint64 `json:"accountId"` - - // Account name - AccountName string `json:"accountName"` - - // Affinity label - AffinityLabel string `json:"affinityLabel"` - - // List affinity rules - AffinityRules ListRules `json:"affinityRules"` - - // Affinity weight - AffinityWeight uint64 `json:"affinityWeight"` - - // Anti affinity rules - AntiAffinityRules ListRules `json:"antiAffinityRules"` - - // Number of CPU - CPUs uint64 `json:"cpus"` - - // Created by - CreatedBy string `json:"createdBy"` - - // Created time - CreatedTime uint64 `json:"createdTime"` - - // Deleted by - DeletedBy string `json:"deletedBy"` - - // Deleted time - DeletedTime uint64 `json:"deletedTime"` - - // ID - ID uint64 `json:"id"` - - // Name - Name string `json:"name"` - - // Number of RAM - RAM uint64 `json:"ram"` - - // Registered - Registered bool `json:"registered"` - - // Resource group ID - RGID uint64 `json:"rgId"` - - // Resource group name - RGName string `json:"rgName"` - - // Status - Status string `json:"status"` - - // Tech status - TechStatus string `json:"techStatus"` - - // Total disks size - TotalDisksSize uint64 `json:"totalDisksSize"` - - // Updated by - UpdatedBy string `json:"updatedBy"` - - // Updated time - UpdatedTime uint64 `json:"updatedTime"` - - // User managed - UserManaged bool `json:"userManaged"` - - // VINS connected - VINSConnected uint64 `json:"vinsConnected"` -} - -// List computes -type ListComputes []ItemCompute - -// Main information about port forward -type ItemPFW struct { - // Public port end - PublicPortEnd uint64 `json:"Public Port End"` - - // Public port start - PublicPortStart uint64 `json:"Public Port Start"` - - // Virtual machine ID - VMID uint64 `json:"VM ID"` - - // Virtual machine IP - VMIP string `json:"VM IP"` - - // Virtual machine name - VMName string `json:"VM Name"` - - // Virtual machine port - VMPort uint64 `json:"VM Port"` - - // VINS ID - VINSID uint64 `json:"ViNS ID"` - - // VINS name - VINSName string `json:"ViNS Name"` -} - -// List PFWs -type ListPFW []ItemPFW - -// Main information about VINS -type ItemVINS struct { - // Account ID - AccountID uint64 `json:"accountId"` - - // Account name - AccountName string `json:"accountName"` - - // Computes - Computes uint64 `json:"computes"` - - // Created by - CreatedBy string `json:"createdBy"` - - // Created time - CreatedTime uint64 `json:"createdTime"` - - // Deleted by - DeletedBy string `json:"deletedBy"` - - // Deleted time - DeletedTime uint64 `json:"deletedTime"` - - // External IP - ExternalIP string `json:"externalIP"` - - // ID - ID uint64 `json:"id"` - - // Name - Name string `json:"name"` - - // Network - Network string `json:"network"` - - // PriVNFDev ID - PriVNFDevID uint64 `json:"priVnfDevId"` - - // Resource group ID - RGID uint64 `json:"rgId"` - - // Resource group name - RGName string `json:"rgName"` - - // Status - Status string `json:"status"` - - // Updated by - UpdatedBy string `json:"updatedBy"` - - // Updated time - UpdatedTime uint64 `json:"updatedTime"` -} - -// List VINSes -type ListVINS []ItemVINS - -// Server settings -type ServerSettings struct { - // Inter - Inter uint64 `json:"inter"` - - // GUID - GUID string `json:"guid"` - - // Down inter - DownInter uint64 `json:"downinter"` - - // Rise - Rise uint64 `json:"rise"` - - // Fall - Fall uint64 `json:"fall"` - - // Slow start - SlowStart uint64 `json:"slowstart"` - - // Max connections - MaxConn uint64 `json:"maxconn"` - - // Max queue - MaxQueue uint64 `json:"maxqueue"` - - // Weight - Weight uint64 `json:"weight"` -} - -// Main information about server -type ItemServer struct { - // Address - Address string `json:"address"` - - // Check - Check string `json:"check"` - - // GUID - GUID string `json:"guid"` - - // Name - Name string `json:"name"` - - // Port - Port uint64 `json:"port"` - - // Server settings - ServerSettings ServerSettings `json:"serverSettings"` -} - -// List of servers -type ListServers []ItemServer - -// Main information about backend -type ItemBackend struct { - // Algorithm - Algorithm string `json:"algorithm"` - - // GUID - GUID string `json:"guid"` - - // Name - Name string `json:"name"` - - // Server settings - ServerDefaultSettings ServerSettings `json:"serverDefaultSettings"` - - // List of servers - Servers ListServers `json:"servers"` -} - -// List of backends -type ListBackends []ItemBackend - -// Main information of binding -type ItemBinding struct { - // Address - Address string `json:"address"` - - // GUID - GUID string `json:"guid"` - - // Name - Name string `json:"name"` - - // Port - Port uint64 `json:"port"` -} - -// List of bindings -type ListBindings []ItemBinding - -// Main information about frontend -type ItemFrontend struct { - // Backend - Backend string `json:"backend"` - - // List of bindings - Bindings ListBindings `json:"bindings"` - - // GUID - GUID string `json:"guid"` - - // Name - Name string `json:"name"` -} - -// List of frontends -type ListFrontends []ItemFrontend - -// Main information about node -type RecordNode struct { - // Backend IP - BackendIP string `json:"backendIp"` - - // Compute ID - ComputeID uint64 `json:"computeId"` - - // Frontend IP - FrontendIP string `json:"frontendIp"` - - // GUID - GUID string `json:"guid"` - - // MGMT IP - MGMTIP string `json:"mgmtIp"` - - // Network ID - NetworkID uint64 `json:"networkId"` -} - -// Main information about load balancer -type ItemLB struct { - // HAMode - HAMode bool `json:"HAmode"` - - // List ACL - ACL ListACL `json:"acl"` - - // List backends - Backends ListBackends `json:"backends"` - - // Created by - CreatedBy string `json:"createdBy"` - - // Created time - CreatedTime uint64 `json:"createdTime"` - - // Deleted by - DeletedBy string `json:"deletedBy"` - - // Deleted time - DeletedTime uint64 `json:"deletedTime"` - - // Description - Description string `json:"desc"` - - // DPAPI user - DPAPIUser string `json:"dpApiUser"` - - // External network ID - ExtNetID uint64 `json:"extnetId"` - - // List of frontends - Frontends ListFrontends `json:"frontends"` - - // Grid ID - GID uint64 `json:"gid"` - - // GUID - GUID uint64 `json:"guid"` - - // ID - ID uint64 `json:"id"` - - // Image ID - ImageID uint64 `json:"imageId"` - - // Milestones - Milestones uint64 `json:"milestones"` - - // Name - Name string `json:"name"` - - // Primary node - PrimaryNode RecordNode `json:"primaryNode"` - - // Resource group ID - RGID uint64 `json:"rgId"` - - // Resource group name - RGName string `json:"rgName"` - - // Secondary node - SecondaryNode RecordNode `json:"secondaryNode"` - - // Status - Status string `json:"status"` - - // Tech status - TechStatus string `json:"techStatus"` - - // Updated by - UpdatedBy string `json:"updatedBy"` - - // Updated time - UpdatedTime uint64 `json:"updatedTime"` - - // VINS ID - VINSID uint64 `json:"vinsId"` -} - -// List load balancers -type ListLB []ItemLB - -// Main information about affinity group -type ItemAffinityGroupCompute struct { - // Compute ID - ComputeID uint64 `json:"computeId"` - - // Other node - OtherNode []uint64 `json:"otherNode"` - - // Other node indirect - OtherNodeIndirect []uint64 `json:"otherNodeIndirect"` - - // Other node indirect soft - OtherNodeIndirectSoft []uint64 `json:"otherNodeIndirectSoft"` - - // Other node soft - OtherNodeSoft []uint64 `json:"otherNodeSoft"` - - // Same node - SameNode []uint64 `json:"sameNode"` - - // Same node soft - SameNodeSoft []uint64 `json:"sameNodeSoft"` -} - -// List of affinity groups -type ListAffinityGroupCompute []ItemAffinityGroupCompute +/* +Copyright (c) 2019-2022 Digital Energy Cloud Solutions LLC. All Rights Reserved. +Authors: +Petr Krutov, +Stanislav Solovev, +Kasim Baybikov, + +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 rg + +type ResourceLimits struct { + CUC float64 `json:"CU_C"` + CUD float64 `json:"CU_D"` + CUI float64 `json:"CU_I"` + CUM float64 `json:"CU_M"` + CUNP float64 `json:"CU_NP"` + GpuUnits float64 `json:"gpu_units"` +} + +type QuotaRecord struct { // this is how quota is reported by /api/.../rg/get + Cpu int `json:"CU_C"` // CPU count in pcs + Ram int `json:"CU_M"` // RAM volume in MB + Disk int `json:"CU_D"` // Disk capacity in GB + ExtIPs int `json:"CU_I"` // Ext IPs count + ExtTraffic int `json:"CU_NP"` // Ext network traffic + GpuUnits int `json:"gpu_units"` // GPU count +} + +// Main information about audit +type ItemAudit struct { + // Call + Call string `json:"call"` + + // Response time + ResponseTime float64 `json:"responsetime"` + + // Status code + StatusCode uint64 `json:"statuscode"` + + // Timestamp + Timestamp float64 `json:"timestamp"` + + // User + User string `json:"user"` +} + +// List of audits +type ListAudits []ItemAudit + +// Resources used +type Resource struct { + // Number of cores + CPU int64 `json:"cpu"` + + // Disk size + DiskSize float64 `json:"disksize"` + + // Max disk size + DiskSizeMax uint64 `json:"disksizemax"` + + // Number of External IPs + ExtIPs int64 `json:"extips"` + + // External traffic + ExtTraffic int64 `json:"exttraffic"` + + // Number of grafic cores + GPU int64 `json:"gpu"` + + // Number of RAM + RAM int64 `json:"ram"` + + // SEPs + SEPs map[string]map[string]DiskUsage `json:"seps"` +} + +// Disk usage +type DiskUsage struct { + // Disk size + DiskSize float64 `json:"disksize"` + + // Disk size max + DiskSizeMax float64 `json:"disksizemax"` +} + +// Information about resources +type Resources struct { + // Current information about resources + Current Resource `json:"Current"` + + // Reserved information about resources + Reserved Resource `json:"Reserved"` +} + +// Detailed information about resource group +type RecordResourceGroup struct { + // Resources + Resources Resources `json:"Resources"` + + // Account ID + AccountID uint64 `json:"accountId"` + + // Account name + AccountName string `json:"accountName"` + + // Access Control List + ACL ListACL `json:"acl"` + + // Created by + CreatedBy string `json:"createdBy"` + + // Created time + CreatedTime uint64 `json:"createdTime"` + + // DefNetID + DefNetID int64 `json:"def_net_id"` + + // DefNetType + DefNetType string `json:"def_net_type"` + + // Deleted by + DeletedBy string `json:"deletedBy"` + + // Deleted time + DeletedTime uint64 `json:"deletedTime"` + + // Description + Description string `json:"desc"` + + // Dirty + Dirty bool `json:"dirty"` + + // Grid ID + GID uint64 `json:"gid"` + + // GUID + GUID uint64 `json:"guid"` + + // ID + ID uint64 `json:"id"` + + // Lock status + LockStatus string `json:"lockStatus"` + + // Milestones + Milestones uint64 `json:"milestones"` + + // Name + Name string `json:"name"` + + // RegisterComputes + RegisterComputes bool `json:"registerComputes"` + + // Resource limits + ResourceLimits ResourceLimits `json:"resourceLimits"` + + // Secret + Secret string `json:"secret"` + + // Status + Status string `json:"status"` + + // Updated by + UpdatedBy string `json:"updatedBy"` + + // Updated time + UpdatedTime uint64 `json:"updatedTime"` + + // List of VINS IDs + VINS []uint64 `json:"vins"` + + // List of compute IDs + Computes []uint64 `json:"vms"` + + // List of resource types + ResTypes []string `json:"resourceTypes"` + + // UniqPools + UniqPools []string `json:"uniqPools"` +} + +// Main information about Access Control List +type ItemACL struct { + // Explicit + Explicit bool `json:"explicit"` + + // GUID + GUID string `json:"guid"` + + // Right + Right string `json:"right"` + + // Status + Status string `json:"status"` + + // Type + Type string `json:"type"` + + // User group ID + UserGroupID string `json:"userGroupId"` +} + +// List ACL +type ListACL []ItemACL + +type ItemResourceGroup struct { + // + AccountACL ItemACL `json:"accountAcl"` + + // Account ID + AccountID uint64 `json:"accountId"` + + // Account name + AccountName string `json:"accountName"` + + // Access Control List + ACL ListACL `json:"acl"` + + // Created by + CreatedBy string `json:"createdBy"` + + // Created time + CreatedTime uint64 `json:"createdTime"` + + // DefNetID + DefNetID int64 `json:"def_net_id"` + + // DefNetType + DefNetType string `json:"def_net_type"` + + // Deleted by + DeletedBy string `json:"deletedBy"` + + // Deleted time + DeletedTime uint64 `json:"deletedTime"` + + // Description + Description string `json:"desc"` + + // Dirty + Dirty bool `json:"dirty"` + + // Grid ID + GID uint64 `json:"gid"` + + // GUID + GUID uint64 `json:"guid"` + + // ID + ID uint64 `json:"id"` + + // Lock status + LockStatus string `json:"lockStatus"` + + // Milestones + Milestones uint64 `json:"milestones"` + + // Name + Name string `json:"name"` + + // RegisterComputes + RegisterComputes bool `json:"registerComputes"` + + // Resource limits + ResourceLimits ResourceLimits `json:"resourceLimits"` + + // Secret + Secret string `json:"secret"` + + // Status + Status string `json:"status"` + + // Updated by + UpdatedBy string `json:"updatedBy"` + + // Updated time + UpdatedTime uint64 `json:"updatedTime"` + + // List of VINS IDs + VINS []uint64 `json:"vins"` + + // List of compute IDs + Computes []uint64 `json:"vms"` + + // List of resource types + ResTypes []string `json:"resourceTypes"` + + // UniqPools + UniqPools []string `json:"uniqPools"` +} + +// List of resource groups +type ListResourceGroups []ItemResourceGroup + +// Main information about affinity rule +type ItemRule struct { + // GUID + GUID string `json:"guid"` + + // Key + Key string `json:"key"` + + // Mode + Mode string `json:"mode"` + + // Policy + Policy string `json:"policy"` + + // Topology + Topology string `json:"topology"` + + // Value + Value string `json:"value"` +} + +// List rules +type ListRules []ItemRule + +// Main information about compute +type ItemCompute struct { + // Account ID + AccountID uint64 `json:"accountId"` + + // Account name + AccountName string `json:"accountName"` + + // Affinity label + AffinityLabel string `json:"affinityLabel"` + + // List affinity rules + AffinityRules ListRules `json:"affinityRules"` + + // Affinity weight + AffinityWeight uint64 `json:"affinityWeight"` + + // Anti affinity rules + AntiAffinityRules ListRules `json:"antiAffinityRules"` + + // Number of CPU + CPUs uint64 `json:"cpus"` + + // Created by + CreatedBy string `json:"createdBy"` + + // Created time + CreatedTime uint64 `json:"createdTime"` + + // Deleted by + DeletedBy string `json:"deletedBy"` + + // Deleted time + DeletedTime uint64 `json:"deletedTime"` + + // ID + ID uint64 `json:"id"` + + // Name + Name string `json:"name"` + + // Number of RAM + RAM uint64 `json:"ram"` + + // Registered + Registered bool `json:"registered"` + + // Resource group ID + RGID uint64 `json:"rgId"` + + // Resource group name + RGName string `json:"rgName"` + + // Status + Status string `json:"status"` + + // Tech status + TechStatus string `json:"techStatus"` + + // Total disks size + TotalDisksSize uint64 `json:"totalDisksSize"` + + // Updated by + UpdatedBy string `json:"updatedBy"` + + // Updated time + UpdatedTime uint64 `json:"updatedTime"` + + // User managed + UserManaged bool `json:"userManaged"` + + // VINS connected + VINSConnected uint64 `json:"vinsConnected"` +} + +// List computes +type ListComputes []ItemCompute + +// Main information about port forward +type ItemPFW struct { + // Public port end + PublicPortEnd uint64 `json:"Public Port End"` + + // Public port start + PublicPortStart uint64 `json:"Public Port Start"` + + // Virtual machine ID + VMID uint64 `json:"VM ID"` + + // Virtual machine IP + VMIP string `json:"VM IP"` + + // Virtual machine name + VMName string `json:"VM Name"` + + // Virtual machine port + VMPort uint64 `json:"VM Port"` + + // VINS ID + VINSID uint64 `json:"ViNS ID"` + + // VINS name + VINSName string `json:"ViNS Name"` +} + +// List PFWs +type ListPFW []ItemPFW + +// Main information about VINS +type ItemVINS struct { + // Account ID + AccountID uint64 `json:"accountId"` + + // Account name + AccountName string `json:"accountName"` + + // Computes + Computes uint64 `json:"computes"` + + // Created by + CreatedBy string `json:"createdBy"` + + // Created time + CreatedTime uint64 `json:"createdTime"` + + // Deleted by + DeletedBy string `json:"deletedBy"` + + // Deleted time + DeletedTime uint64 `json:"deletedTime"` + + // External IP + ExternalIP string `json:"externalIP"` + + // ID + ID uint64 `json:"id"` + + // Name + Name string `json:"name"` + + // Network + Network string `json:"network"` + + // PriVNFDev ID + PriVNFDevID uint64 `json:"priVnfDevId"` + + // Resource group ID + RGID uint64 `json:"rgId"` + + // Resource group name + RGName string `json:"rgName"` + + // Status + Status string `json:"status"` + + // Updated by + UpdatedBy string `json:"updatedBy"` + + // Updated time + UpdatedTime uint64 `json:"updatedTime"` +} + +// List VINSes +type ListVINS []ItemVINS + +// Server settings +type ServerSettings struct { + // Inter + Inter uint64 `json:"inter"` + + // GUID + GUID string `json:"guid"` + + // Down inter + DownInter uint64 `json:"downinter"` + + // Rise + Rise uint64 `json:"rise"` + + // Fall + Fall uint64 `json:"fall"` + + // Slow start + SlowStart uint64 `json:"slowstart"` + + // Max connections + MaxConn uint64 `json:"maxconn"` + + // Max queue + MaxQueue uint64 `json:"maxqueue"` + + // Weight + Weight uint64 `json:"weight"` +} + +// Main information about server +type ItemServer struct { + // Address + Address string `json:"address"` + + // Check + Check string `json:"check"` + + // GUID + GUID string `json:"guid"` + + // Name + Name string `json:"name"` + + // Port + Port uint64 `json:"port"` + + // Server settings + ServerSettings ServerSettings `json:"serverSettings"` +} + +// List of servers +type ListServers []ItemServer + +// Main information about backend +type ItemBackend struct { + // Algorithm + Algorithm string `json:"algorithm"` + + // GUID + GUID string `json:"guid"` + + // Name + Name string `json:"name"` + + // Server settings + ServerDefaultSettings ServerSettings `json:"serverDefaultSettings"` + + // List of servers + Servers ListServers `json:"servers"` +} + +// List of backends +type ListBackends []ItemBackend + +// Main information of binding +type ItemBinding struct { + // Address + Address string `json:"address"` + + // GUID + GUID string `json:"guid"` + + // Name + Name string `json:"name"` + + // Port + Port uint64 `json:"port"` +} + +// List of bindings +type ListBindings []ItemBinding + +// Main information about frontend +type ItemFrontend struct { + // Backend + Backend string `json:"backend"` + + // List of bindings + Bindings ListBindings `json:"bindings"` + + // GUID + GUID string `json:"guid"` + + // Name + Name string `json:"name"` +} + +// List of frontends +type ListFrontends []ItemFrontend + +// Main information about node +type RecordNode struct { + // Backend IP + BackendIP string `json:"backendIp"` + + // Compute ID + ComputeID uint64 `json:"computeId"` + + // Frontend IP + FrontendIP string `json:"frontendIp"` + + // GUID + GUID string `json:"guid"` + + // MGMT IP + MGMTIP string `json:"mgmtIp"` + + // Network ID + NetworkID uint64 `json:"networkId"` +} + +// Main information about load balancer +type ItemLB struct { + // HAMode + HAMode bool `json:"HAmode"` + + // List ACL + ACL ListACL `json:"acl"` + + // List backends + Backends ListBackends `json:"backends"` + + // Created by + CreatedBy string `json:"createdBy"` + + // Created time + CreatedTime uint64 `json:"createdTime"` + + // Deleted by + DeletedBy string `json:"deletedBy"` + + // Deleted time + DeletedTime uint64 `json:"deletedTime"` + + // Description + Description string `json:"desc"` + + // DPAPI user + DPAPIUser string `json:"dpApiUser"` + + // External network ID + ExtNetID uint64 `json:"extnetId"` + + // List of frontends + Frontends ListFrontends `json:"frontends"` + + // Grid ID + GID uint64 `json:"gid"` + + // GUID + GUID uint64 `json:"guid"` + + // ID + ID uint64 `json:"id"` + + // Image ID + ImageID uint64 `json:"imageId"` + + // Milestones + Milestones uint64 `json:"milestones"` + + // Name + Name string `json:"name"` + + // Primary node + PrimaryNode RecordNode `json:"primaryNode"` + + // Resource group ID + RGID uint64 `json:"rgId"` + + // Resource group name + RGName string `json:"rgName"` + + // Secondary node + SecondaryNode RecordNode `json:"secondaryNode"` + + // Status + Status string `json:"status"` + + // Tech status + TechStatus string `json:"techStatus"` + + // Updated by + UpdatedBy string `json:"updatedBy"` + + // Updated time + UpdatedTime uint64 `json:"updatedTime"` + + // VINS ID + VINSID uint64 `json:"vinsId"` +} + +// List load balancers +type ListLB []ItemLB + +// Main information about affinity group +type ItemAffinityGroupCompute struct { + // Compute ID + ComputeID uint64 `json:"computeId"` + + // Other node + OtherNode []uint64 `json:"otherNode"` + + // Other node indirect + OtherNodeIndirect []uint64 `json:"otherNodeIndirect"` + + // Other node indirect soft + OtherNodeIndirectSoft []uint64 `json:"otherNodeIndirectSoft"` + + // Other node soft + OtherNodeSoft []uint64 `json:"otherNodeSoft"` + + // Same node + SameNode []uint64 `json:"sameNode"` + + // Same node soft + SameNodeSoft []uint64 `json:"sameNodeSoft"` +} + +// List of affinity groups +type ListAffinityGroupCompute []ItemAffinityGroupCompute diff --git a/internal/service/cloudapi/rg/old_schemas.go b/internal/service/cloudapi/rg/old_schemas.go new file mode 100644 index 0000000..a6a4428 --- /dev/null +++ b/internal/service/cloudapi/rg/old_schemas.go @@ -0,0 +1,292 @@ +package rg + +import ( + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/validation" +) + +func resourceRGResourceV1() *schema.Resource { + return &schema.Resource{ + Schema: map[string]*schema.Schema{ + "account_id": { + Type: schema.TypeInt, + Required: true, + ValidateFunc: validation.IntAtLeast(1), + Description: "Unique ID of the account, which this resource group belongs to.", + }, + "gid": { + Type: schema.TypeInt, + Required: true, + ForceNew: true, + Description: "Unique ID of the grid, where this resource group is deployed.", + }, + "name": { + Type: schema.TypeString, + Required: true, + Description: "Name of this resource group. Names are case sensitive and unique within the context of a account.", + }, + "def_net_type": { + Type: schema.TypeString, + Optional: true, + Computed: true, + ValidateFunc: validation.StringInSlice([]string{"PRIVATE", "PUBLIC", "NONE"}, false), + Description: "Type of the network, which this resource group will use as default for its computes - PRIVATE or PUBLIC or NONE.", + }, + "def_net_id": { + Type: schema.TypeInt, + Computed: true, + Description: "ID of the default network for this resource group (if any).", + }, + "ipcidr": { + Type: schema.TypeString, + Optional: true, + Description: "Address of the netowrk inside the private network segment (aka ViNS) if def_net_type=PRIVATE", + }, + "ext_net_id": { + Type: schema.TypeInt, + Optional: true, + Default: 0, + Description: "ID of the external network for default ViNS. Pass 0 if def_net_type=PUBLIC or no external connection required for the defult ViNS when def_net_type=PRIVATE", + }, + "ext_ip": { + Type: schema.TypeString, + Optional: true, + Description: "IP address on the external netowrk to request when def_net_type=PRIVATE and ext_net_id is not 0", + }, + "quota": { + Type: schema.TypeList, + Optional: true, + MaxItems: 1, + Elem: &schema.Resource{ + Schema: map[string]*schema.Schema{ + "cpu": { + Type: schema.TypeInt, + Optional: true, + Default: -1, + Description: "Limit on the total number of CPUs in this resource group.", + }, + "ram": { + Type: schema.TypeFloat, // NB: API expects and returns this as float in units of MB! This may be changed in the future. + Optional: true, + Default: -1, + Description: "Limit on the total amount of RAM in this resource group, specified in MB.", + }, + "disk": { + Type: schema.TypeInt, + Optional: true, + Default: -1, + Description: "Limit on the total volume of storage resources in this resource group, specified in GB.", + }, + "ext_traffic": { + Type: schema.TypeInt, + Optional: true, + Default: -1, + Description: "Limit on the total ingress network traffic for this resource group, specified in GB.", + }, + "ext_ips": { + Type: schema.TypeInt, + Optional: true, + Default: -1, + Description: "Limit on the total number of external IP addresses this resource group can use.", + }, + "gpu_units": { + Type: schema.TypeInt, + Optional: true, + Default: -1, + Description: "Limit on the total number of virtual GPUs this resource group can use.", + }, + }, + }, + Description: "Quota settings for this resource group.", + }, + "access": { + Type: schema.TypeSet, + Optional: true, + Elem: &schema.Resource{ + Schema: map[string]*schema.Schema{ + "user": { + Type: schema.TypeString, + Required: true, + Description: "User or group name to grant access", + }, + "right": { + Type: schema.TypeString, + Required: true, + Description: "Access rights to set, one of 'R', 'RCX' or 'ARCXDU'", + }, + "reason": { + Type: schema.TypeString, + Optional: true, + Description: "Reason for action", + }, + }, + }, + }, + "def_net": { + Type: schema.TypeSet, + Optional: true, + MaxItems: 1, + Elem: &schema.Resource{ + Schema: map[string]*schema.Schema{ + "net_type": { + Type: schema.TypeString, + Required: true, + ValidateFunc: validation.StringInSlice([]string{"PRIVATE", "PUBLIC"}, false), + Description: "Network type to set. Must be on of 'PRIVATE' or 'PUBLIC'.", + }, + "net_id": { + Type: schema.TypeInt, + Optional: true, + Default: 0, + Description: "Network segment ID. If netType is PUBLIC and netId is 0 then default external network segment will be selected. If netType is PRIVATE and netId=0, the first ViNS defined for this RG will be selected. Otherwise, netId identifies either existing external network segment or ViNS.", + }, + "reason": { + Type: schema.TypeString, + Optional: true, + Description: "Reason for action", + }, + }, + }, + }, + "description": { + Type: schema.TypeString, + Optional: true, + Computed: true, + Description: "User-defined text description of this resource group.", + }, + "force": { + Type: schema.TypeBool, + Optional: true, + Default: false, + Description: "Set to True if you want force delete non-empty RG", + }, + "permanently": { + Type: schema.TypeBool, + Optional: true, + Default: false, + Description: "Set to True if you want force delete non-empty RG", + }, + "reason": { + Type: schema.TypeString, + Optional: true, + Description: "Set to True if you want force delete non-empty RG", + }, + "register_computes": { + Type: schema.TypeBool, + Optional: true, + Default: false, + Description: "Register computes in registration system", + }, + "enable": { + Type: schema.TypeBool, + Optional: true, + Default: true, + Description: "flag for enable/disable RG", + }, + "account_name": { + Type: schema.TypeString, + Computed: true, + Description: "Name of the account, which this resource group belongs to.", + }, + // "resources": { + // Type: schema.TypeList, + // Computed: true, + // Elem: &schema.Resource{ + // Schema: resourcesSchemaMake(), + // }, + // }, + + "acl": { + Type: schema.TypeList, + Computed: true, + Elem: &schema.Resource{ + Schema: aclSchemaMake(), + }, + }, + "deleted_by": { + Type: schema.TypeString, + Computed: true, + }, + "deleted_time": { + Type: schema.TypeInt, + Computed: true, + }, + "dirty": { + Type: schema.TypeBool, + Computed: true, + }, + "guid": { + Type: schema.TypeInt, + Computed: true, + }, + "rg_id": { + Type: schema.TypeInt, + Computed: true, + }, + "lock_status": { + Type: schema.TypeString, + Computed: true, + }, + "milestones": { + Type: schema.TypeInt, + Computed: true, + }, + "secret": { + Type: schema.TypeString, + Computed: true, + }, + "status": { + Type: schema.TypeString, + Computed: true, + Description: "Current status of this resource group.", + }, + "updated_by": { + Type: schema.TypeString, + Computed: true, + }, + "updated_time": { + Type: schema.TypeInt, + Computed: true, + }, + "vins": { + Type: schema.TypeList, + Computed: true, + Elem: &schema.Schema{ + Type: schema.TypeInt, + }, + Description: "List of VINs deployed in this resource group.", + }, + + "vms": { + Type: schema.TypeList, + Computed: true, + Elem: &schema.Schema{ + Type: schema.TypeInt, + }, + Description: "List of computes deployed in this resource group.", + }, + "res_types": { + Type: schema.TypeList, + Computed: true, + Elem: &schema.Schema{ + Type: schema.TypeString, + }, + }, + "uniq_pools": { + Type: schema.TypeList, + Computed: true, + Elem: &schema.Schema{ + Type: schema.TypeString, + }, + }, + "cpu_allocation_parameter": { + Type: schema.TypeString, + Computed: true, + }, + "cpu_allocation_ratio": { + Type: schema.TypeFloat, + Computed: true, + }, + }, + } +} diff --git a/internal/service/cloudapi/rg/quota_subresource.go b/internal/service/cloudapi/rg/quota_subresource.go index 338a114..398ac64 100644 --- a/internal/service/cloudapi/rg/quota_subresource.go +++ b/internal/service/cloudapi/rg/quota_subresource.go @@ -32,10 +32,6 @@ Documentation: https://repository.basistech.ru/BASIS/terraform-provider-decort/w package rg -import ( - "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" -) - func makeQuotaRecord(arg_list []interface{}) QuotaRecord { quota := QuotaRecord{ Cpu: -1, @@ -56,8 +52,8 @@ func makeQuotaRecord(arg_list []interface{}) QuotaRecord { quota.Disk = subres_data["disk"].(int) // Disk capacity ib GB } - if subres_data["ram"].(float64) > 0 { - quota.Ram = subres_data["ram"].(float64) // RAM volume in MB, as float64! + if subres_data["ram"].(int) > 0 { + quota.Ram = subres_data["ram"].(int) // RAM volume in MB } if subres_data["ext_traffic"].(int) > 0 { @@ -75,65 +71,18 @@ func makeQuotaRecord(arg_list []interface{}) QuotaRecord { return quota } -func parseQuota(quota QuotaRecord) []interface{} { - quota_map := make(map[string]interface{}) - - quota_map["cpu"] = quota.Cpu - quota_map["ram"] = quota.Ram // NB: this is float64, unlike the rest of values - quota_map["disk"] = quota.Disk - quota_map["ext_traffic"] = quota.ExtTraffic - quota_map["ext_ips"] = quota.ExtIPs - quota_map["gpu_units"] = quota.GpuUnits +// func parseQuota(quota QuotaRecord) []interface{} { +// quota_map := make(map[string]interface{}) - result := make([]interface{}, 1) - result[0] = quota_map +// quota_map["cpu"] = quota.Cpu +// quota_map["ram"] = quota.Ram // NB: this is float64, unlike the rest of values +// quota_map["disk"] = quota.Disk +// quota_map["ext_traffic"] = quota.ExtTraffic +// quota_map["ext_ips"] = quota.ExtIPs +// quota_map["gpu_units"] = quota.GpuUnits - return result // this result will be used to d.Set("quota,") of dataSourceResgroup schema -} +// result := make([]interface{}, 1) +// result[0] = quota_map -func quotaRgSubresourceSchemaMake() map[string]*schema.Schema { - rets := map[string]*schema.Schema{ - "cpu": { - Type: schema.TypeInt, - Optional: true, - Default: -1, - Description: "Limit on the total number of CPUs in this resource group.", - }, - - "ram": { - Type: schema.TypeFloat, // NB: API expects and returns this as float in units of MB! This may be changed in the future. - Optional: true, - Default: -1., - Description: "Limit on the total amount of RAM in this resource group, specified in MB.", - }, - - "disk": { - Type: schema.TypeInt, - Optional: true, - Default: -1, - Description: "Limit on the total volume of storage resources in this resource group, specified in GB.", - }, - - "ext_traffic": { - Type: schema.TypeInt, - Optional: true, - Default: -1, - Description: "Limit on the total ingress network traffic for this resource group, specified in GB.", - }, - - "ext_ips": { - Type: schema.TypeInt, - Optional: true, - Default: -1, - Description: "Limit on the total number of external IP addresses this resource group can use.", - }, - - "gpu_units": { - Type: schema.TypeInt, - Optional: true, - Default: -1, - Description: "Limit on the total number of virtual GPUs this resource group can use.", - }, - } - return rets -} +// return result // this result will be used to d.Set("quota,") of dataSourceResgroup schema +// } diff --git a/internal/service/cloudapi/rg/resource_rg.go b/internal/service/cloudapi/rg/resource_rg.go index 6be15ee..44fa8d6 100644 --- a/internal/service/cloudapi/rg/resource_rg.go +++ b/internal/service/cloudapi/rg/resource_rg.go @@ -42,7 +42,6 @@ import ( "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" - "repository.basistech.ru/BASIS/terraform-provider-decort/internal/location" "repository.basistech.ru/BASIS/terraform-provider-decort/internal/status" "github.com/hashicorp/terraform-plugin-sdk/v2/diag" @@ -54,7 +53,7 @@ import ( func resourceResgroupCreate(ctx context.Context, d *schema.ResourceData, m interface{}) diag.Diagnostics { rgName, ok := d.GetOk("name") if !ok { - return diag.FromErr(fmt.Errorf("Cannot create new RG: missing name.")) + return diag.FromErr(fmt.Errorf("cannot create new RG: missing name")) } log.Debugf("resourceResgroupCreate: called for RG name %s, account ID %d", @@ -86,26 +85,25 @@ func resourceResgroupCreate(ctx context.Context, d *schema.ResourceData, m inter } } c := m.(*controller.ControllerCfg) - req := rg.CreateRequest{} + req := rg.CreateRequest{ + Name: rgName.(string), + AccountID: uint64(d.Get("account_id").(int)), + GID: uint64(d.Get("gid").(int)), + // Owner: c.GetDecortUsername(), + } setQuota := false var quotaRecord QuotaRecord - argValue, ok := d.GetOk("quota") - if ok { + if argValue, ok := d.GetOk("quota"); ok { log.Debugf("resourceResgroupCreate: setting Quota on RG requested") quotaRecord = makeQuotaRecord(argValue.([]interface{})) setQuota = true } - log.Debugf("resourceResgroupCreate: called by user %q for RG name %s, account ID %d", - c.GetDecortUsername(), + log.Debugf("resourceResgroupCreate: called for RG name %s, account ID %d", + // c.GetDecortUsername(), rgName.(string), d.Get("account_id").(int)) - req.AccountID = uint64(d.Get("account_id").(int)) - req.Name = rgName.(string) - req.GID = uint64(location.DefaultGridID) - req.Owner = c.GetDecortUsername() - if setQuota { req.MaxCPUCapacity = int64(quotaRecord.Cpu) req.MaxVDiskCapacity = int64(quotaRecord.Disk) @@ -114,40 +112,37 @@ func resourceResgroupCreate(ctx context.Context, d *schema.ResourceData, m inter req.MaxNumPublicIP = int64(quotaRecord.ExtIPs) } - defNetType, ok := d.GetOk("def_net_type") - if ok { + if defNetType, ok := d.GetOk("def_net_type"); ok { req.DefNet = defNetType.(string) // NOTE: in API default network type is set by "def_net" parameter } else { d.Set("def_net_type", "PRIVATE") } - ipcidr, ok := d.GetOk("ipcidr") - if ok { + if owner, ok := d.GetOk("owner"); ok { + req.Owner = owner.(string) + } + + if ipcidr, ok := d.GetOk("ipcidr"); ok { req.IPCIDR = ipcidr.(string) } - description, ok := d.GetOk("description") - if ok { + if description, ok := d.GetOk("description"); ok { req.Description = description.(string) } - reason, ok := d.GetOk("reason") - if ok { + if reason, ok := d.GetOk("reason"); ok { req.Reason = reason.(string) } - extNetId, ok := d.GetOk("ext_net_id") - if ok { + if extNetId, ok := d.GetOk("ext_net_id"); ok { req.ExtNetID = uint64(extNetId.(int)) } - extIp, ok := d.GetOk("ext_ip") - if ok { + if extIp, ok := d.GetOk("ext_ip"); ok { req.ExtIP = extIp.(string) } - regComputes, ok := d.GetOk("register_computes") - if ok { + if regComputes, ok := d.GetOk("register_computes"); ok { req.RegisterComputes = regComputes.(bool) } @@ -217,8 +212,7 @@ func resourceResgroupCreate(ctx context.Context, d *schema.ResourceData, m inter } if enable, ok := d.GetOk("enable"); ok { - enable := enable.(bool) - if enable { + if enable.(bool) { req := rg.EnableRequest{ RGID: apiResp, } @@ -247,8 +241,7 @@ func resourceResgroupCreate(ctx context.Context, d *schema.ResourceData, m inter } } - defer resourceResgroupRead(ctx, d, m) - return w.Get() + return append(w.Get(), resourceResgroupRead(ctx, d, m)...) } func resourceResgroupRead(ctx context.Context, d *schema.ResourceData, m interface{}) diag.Diagnostics { @@ -352,19 +345,30 @@ func resourceResgroupUpdate(ctx context.Context, d *schema.ResourceData, m inter case status.Created: case status.Enabled: case status.Deleted: - restoreReq := rg.RestoreRequest{RGID: rgData.ID} - enableReq := rg.EnableRequest{RGID: rgData.ID} + if restore, ok := d.GetOk("restore"); ok && restore.(bool) { + restoreReq := rg.RestoreRequest{RGID: rgData.ID} - _, err := c.CloudAPI().RG().Restore(ctx, restoreReq) - if err != nil { - return diag.FromErr(err) - } + if reason, ok := d.GetOk("reason"); ok { + restoreReq.Reason = reason.(string) + } - _, err = c.CloudAPI().RG().Enable(ctx, enableReq) - if err != nil { - return diag.FromErr(err) - } + _, err := c.CloudAPI().RG().Restore(ctx, restoreReq) + if err != nil { + return diag.FromErr(err) + } + if enable, ok := d.GetOk("enable"); ok && enable.(bool) { + enableReq := rg.EnableRequest{RGID: rgData.ID} + + if reason, ok := d.GetOk("reason"); ok { + enableReq.Reason = reason.(string) + } + _, err = c.CloudAPI().RG().Enable(ctx, enableReq) + if err != nil { + return diag.FromErr(err) + } + } + } hasChanged = true case status.Deleting: case status.Destroyed: @@ -393,7 +397,7 @@ func resourceResgroupUpdate(ctx context.Context, d *schema.ResourceData, m inter The following code fragment checks if any of these have been changed and generates error. */ - if ok := d.HasChange("def_net"); ok { + if d.HasChange("def_net") { _, newDefNet := d.GetChange("def_net") if newDefNet.(*schema.Set).Len() == 0 { return diag.Errorf("resourceResgroupUpdate: block def_net must not be empty") @@ -412,171 +416,99 @@ func resourceResgroupUpdate(ctx context.Context, d *schema.ResourceData, m inter return diag.FromErr(fmt.Errorf("resourceResgroupUpdate: RG ID %s: changing ext_net_id for existing RG is not allowed", d.Id())) } - doGeneralUpdate := false - - req := rg.UpdateRequest{ - RGID: rgData.ID, - } - - nameNew, nameSet := d.GetOk("name") - if nameSet { - log.Debugf("resourceResgroupUpdate: name specified - looking for deltas from the old settings.") - nameOld, _ := d.GetChange("name") - if nameOld.(string) != nameNew.(string) { - req.Name = nameNew.(string) - - doGeneralUpdate = true - } - } - - quotaValue, quotaSet := d.GetOk("quota") - if quotaSet { - log.Debugf("resourceResgroupUpdate: quota specified - looking for deltas from the old quota.") - quotarecordNew := makeQuotaRecord(quotaValue.([]interface{})) - quotaValueOld, _ := d.GetChange("quota") - quotarecordOld := makeQuotaRecord(quotaValueOld.([]interface{})) - log.Debug(quotaValueOld, quotarecordNew) - - if quotarecordNew.Cpu != quotarecordOld.Cpu { - doGeneralUpdate = true - log.Debugf("resourceResgroupUpdate: Cpu diff %d <- %d", quotarecordNew.Cpu, quotarecordOld.Cpu) - req.MaxCPUCapacity = int64(quotarecordNew.Cpu) - } - - if quotarecordNew.Disk != quotarecordOld.Disk { - doGeneralUpdate = true - log.Debugf("resourceResgroupUpdate: Disk diff %d <- %d", quotarecordNew.Disk, quotarecordOld.Disk) - req.MaxVDiskCapacity = int64(quotarecordNew.Disk) - } - - if quotarecordNew.Ram != quotarecordOld.Ram { - doGeneralUpdate = true - log.Debugf("resourceResgroupUpdate: Ram diff %f <- %f", quotarecordNew.Ram, quotarecordOld.Ram) - req.MaxMemoryCapacity = int64(quotarecordNew.Ram) - } - - if quotarecordNew.ExtTraffic != quotarecordOld.ExtTraffic { - doGeneralUpdate = true - log.Debugf("resourceResgroupUpdate: ExtTraffic diff %d <- %d", quotarecordNew.ExtTraffic, quotarecordOld.ExtTraffic) - req.MaxNetworkPeerTransfer = int64(quotarecordNew.ExtTraffic) - } - - if quotarecordNew.ExtIPs != quotarecordOld.ExtIPs { - doGeneralUpdate = true - log.Debugf("resourceResgroupUpdate: ExtIPs diff %d <- %d", quotarecordNew.ExtIPs, quotarecordOld.ExtIPs) - req.MaxNumPublicIP = int64(quotarecordNew.ExtIPs) - } - } else { - doGeneralUpdate = true - req.MaxCPUCapacity = -1 - req.MaxVDiskCapacity = -1 - req.MaxMemoryCapacity = -1 - req.MaxNetworkPeerTransfer = -1 - req.MaxNumPublicIP = -1 - } - - descNew, descSet := d.GetOk("description") - if descSet { - log.Debugf("resourceResgroupUpdate: description specified - looking for deltas from the old settings.") - descOld, _ := d.GetChange("description") - if descOld.(string) != descNew.(string) { - doGeneralUpdate = true - req.Description = descNew.(string) - } - } - - if doGeneralUpdate { - log.Debugf("resourceResgroupUpdate: detected delta between new and old RG specs - updating the RG") - _, err := c.CloudAPI().RG().Update(ctx, req) - if err != nil { + if d.HasChanges("name", "quota", "description", "register_computes") { + if err := utilityUpdateRG(ctx, d, m, rgData.ID); err != nil { return diag.FromErr(err) } - } else { - log.Debugf("resourceResgroupUpdate: no difference between old and new state - no update on the RG will be done") } - enableOld, enableNew := d.GetChange("enable") - if enableOld.(bool) && !enableNew.(bool) { - req := rg.DisableRequest{RGID: rgData.ID} + if d.HasChange("enable") { + enableOld, enableNew := d.GetChange("enable") + if enableOld.(bool) && !enableNew.(bool) { + req := rg.DisableRequest{RGID: rgData.ID} - _, err := c.CloudAPI().RG().Disable(ctx, req) - if err != nil { - return diag.FromErr(err) - } - } else if !enableOld.(bool) && enableNew.(bool) { - req := rg.EnableRequest{RGID: rgData.ID} + _, err := c.CloudAPI().RG().Disable(ctx, req) + if err != nil { + return diag.FromErr(err) + } + } else if !enableOld.(bool) && enableNew.(bool) { + req := rg.EnableRequest{RGID: rgData.ID} - _, err := c.CloudAPI().RG().Enable(ctx, req) - if err != nil { - return diag.FromErr(err) + _, err := c.CloudAPI().RG().Enable(ctx, req) + if err != nil { + return diag.FromErr(err) + } } } - oldSet, newSet := d.GetChange("access") - - deletedAccess := (oldSet.(*schema.Set).Difference(newSet.(*schema.Set))).List() - for _, deletedInterface := range deletedAccess { - deletedItem := deletedInterface.(map[string]interface{}) - user := deletedItem["user"].(string) - req := rg.AccessRevokeRequest{ - RGID: rgData.ID, - User: user, - } - if reason, ok := d.GetOk("reason"); ok { - req.Reason = reason.(string) - } + if d.HasChange("access") { + oldSet, newSet := d.GetChange("access") + deletedAccess := (oldSet.(*schema.Set).Difference(newSet.(*schema.Set))).List() + for _, deletedInterface := range deletedAccess { + deletedItem := deletedInterface.(map[string]interface{}) + user := deletedItem["user"].(string) + req := rg.AccessRevokeRequest{ + RGID: rgData.ID, + User: user, + } + if reason, ok := d.GetOk("reason"); ok { + req.Reason = reason.(string) + } - _, err := c.CloudAPI().RG().AccessRevoke(ctx, req) - if err != nil { - return diag.FromErr(err) + _, err := c.CloudAPI().RG().AccessRevoke(ctx, req) + if err != nil { + return diag.FromErr(err) + } } - } - addedAccess := (newSet.(*schema.Set).Difference(oldSet.(*schema.Set))).List() - for _, addedInterface := range addedAccess { - addedItem := addedInterface.(map[string]interface{}) - user := addedItem["user"].(string) - right := addedItem["right"].(string) + addedAccess := (newSet.(*schema.Set).Difference(oldSet.(*schema.Set))).List() + for _, addedInterface := range addedAccess { + addedItem := addedInterface.(map[string]interface{}) + user := addedItem["user"].(string) + right := addedItem["right"].(string) - req := rg.AccessGrantRequest{ - RGID: rgData.ID, - User: user, - Right: right, - } + req := rg.AccessGrantRequest{ + RGID: rgData.ID, + User: user, + Right: right, + } - if reason, ok := d.GetOk("reason"); ok { - req.Reason = reason.(string) - } + if reason, ok := d.GetOk("reason"); ok { + req.Reason = reason.(string) + } - _, err := c.CloudAPI().RG().AccessGrant(ctx, req) - if err != nil { - return diag.FromErr(err) + _, err := c.CloudAPI().RG().AccessGrant(ctx, req) + if err != nil { + return diag.FromErr(err) + } } } - if ok := d.HasChange("def_net"); ok { - oldDefNet, newDefNet := d.GetChange("def_net") - if newDefNet.(*schema.Set).Len() > 0 { - changedDefNet := (newDefNet.(*schema.Set).Difference(oldDefNet.(*schema.Set))).List() - for _, changedDefNetInterface := range changedDefNet { - defNetItem := changedDefNetInterface.(map[string]interface{}) - netType := defNetItem["net_type"].(string) + if d.HasChange("def_net") { + if ok := d.HasChange("def_net"); ok { + oldDefNet, newDefNet := d.GetChange("def_net") + if newDefNet.(*schema.Set).Len() > 0 { + changedDefNet := (newDefNet.(*schema.Set).Difference(oldDefNet.(*schema.Set))).List() + for _, changedDefNetInterface := range changedDefNet { + defNetItem := changedDefNetInterface.(map[string]interface{}) + netType := defNetItem["net_type"].(string) - req := rg.SetDefNetRequest{ - RGID: rgData.ID, - NetType: netType, - } + req := rg.SetDefNetRequest{ + RGID: rgData.ID, + NetType: netType, + } - if netID, ok := defNetItem["net_id"]; ok { - req.NetID = uint64(netID.(int)) - } - if reason, ok := defNetItem["reason"]; ok { - req.Reason = reason.(string) - } + if netID, ok := defNetItem["net_id"]; ok { + req.NetID = uint64(netID.(int)) + } + if reason, ok := defNetItem["reason"]; ok { + req.Reason = reason.(string) + } - _, err := c.CloudAPI().RG().SetDefNet(ctx, req) - if err != nil { - return diag.FromErr(err) + _, err := c.CloudAPI().RG().SetDefNet(ctx, req) + if err != nil { + return diag.FromErr(err) + } } } } @@ -625,9 +557,9 @@ func ResourceRgSchemaMake() map[string]*schema.Schema { }, "gid": { - Type: schema.TypeInt, - Required: true, - ForceNew: true, + Type: schema.TypeInt, + Required: true, + // ForceNew: true, Description: "Unique ID of the grid, where this resource group is deployed.", }, @@ -670,12 +602,59 @@ func ResourceRgSchemaMake() map[string]*schema.Schema { Description: "IP address on the external netowrk to request when def_net_type=PRIVATE and ext_net_id is not 0", }, + "owner": { + Type: schema.TypeString, + Optional: true, + }, + "quota": { Type: schema.TypeList, Optional: true, MaxItems: 1, Elem: &schema.Resource{ - Schema: quotaRgSubresourceSchemaMake(), + Schema: map[string]*schema.Schema{ + "cpu": { + Type: schema.TypeInt, + Optional: true, + Default: -1, + Description: "Limit on the total number of CPUs in this resource group.", + }, + + "ram": { + Type: schema.TypeInt, // NB: API expects and returns this as float in units of MB! This may be changed in the future. + Optional: true, + Default: -1, + Description: "Limit on the total amount of RAM in this resource group, specified in MB.", + }, + + "disk": { + Type: schema.TypeInt, + Optional: true, + Default: -1, + Description: "Limit on the total volume of storage resources in this resource group, specified in GB.", + }, + + "ext_traffic": { + Type: schema.TypeInt, + Optional: true, + Default: -1, + Description: "Limit on the total ingress network traffic for this resource group, specified in GB.", + }, + + "ext_ips": { + Type: schema.TypeInt, + Optional: true, + Default: -1, + Description: "Limit on the total number of external IP addresses this resource group can use.", + }, + + "gpu_units": { + Type: schema.TypeInt, + Optional: true, + Default: -1, + Description: "Limit on the total number of virtual GPUs this resource group can use.", + }, + }, }, Description: "Quota settings for this resource group.", }, @@ -760,7 +739,11 @@ func ResourceRgSchemaMake() map[string]*schema.Schema { Default: false, Description: "Register computes in registration system", }, - + "restore": { + Type: schema.TypeBool, + Optional: true, + Default: false, + }, "enable": { Type: schema.TypeBool, Optional: true, @@ -878,7 +861,7 @@ func ResourceRgSchemaMake() map[string]*schema.Schema { func ResourceResgroup() *schema.Resource { return &schema.Resource{ - SchemaVersion: 1, + SchemaVersion: 2, CreateContext: resourceResgroupCreate, ReadContext: resourceResgroupRead, @@ -916,5 +899,12 @@ func ResourceResgroup() *schema.Resource { }, ), ), + StateUpgraders: []schema.StateUpgrader{ + { + Type: resourceRGResourceV1().CoreConfigSchema().ImpliedType(), + Upgrade: resourceRGStateUpgradeV1, + Version: 1, + }, + }, } } diff --git a/internal/service/cloudapi/rg/state_upgraders.go b/internal/service/cloudapi/rg/state_upgraders.go new file mode 100644 index 0000000..0eee669 --- /dev/null +++ b/internal/service/cloudapi/rg/state_upgraders.go @@ -0,0 +1,28 @@ +package rg + +import ( + "context" + + log "github.com/sirupsen/logrus" +) + +func resourceRGStateUpgradeV1(ctx context.Context, rawState map[string]interface{}, meta any) (map[string]interface{}, error) { + log.Debug("resourceRGStateUpgradeV1: upgrading state") + quota, ok := rawState["quota"] + if !ok || quota == nil { + rawState["quota"] = QuotaRecord{ + Cpu: -1, + Ram: -1, + Disk: -1, + ExtTraffic: -1, + ExtIPs: -1, + GpuUnits: -1, + } + return rawState, nil + } + + oldQuotaList := quota.([]interface{}) + oldQuota := oldQuotaList[0].(map[string]interface{}) + oldQuota["ram"] = int64(oldQuota["ram"].(float64)) + return rawState, nil +} diff --git a/internal/service/cloudapi/rg/utility_rg.go b/internal/service/cloudapi/rg/utility_rg.go index 70c0313..09a341f 100644 --- a/internal/service/cloudapi/rg/utility_rg.go +++ b/internal/service/cloudapi/rg/utility_rg.go @@ -36,10 +36,10 @@ import ( "context" "strconv" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" + log "github.com/sirupsen/logrus" "repository.basistech.ru/BASIS/decort-golang-sdk/pkg/cloudapi/rg" "repository.basistech.ru/BASIS/terraform-provider-decort/internal/controller" - - "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" ) func utilityResgroupCheckPresence(ctx context.Context, d *schema.ResourceData, m interface{}) (*rg.RecordResourceGroup, error) { @@ -63,3 +63,47 @@ func utilityResgroupCheckPresence(ctx context.Context, d *schema.ResourceData, m return rgData, nil } + +func utilityUpdateRG(ctx context.Context, d *schema.ResourceData, m interface{}, rgId uint64) error { + c := m.(*controller.ControllerCfg) + + req := rg.UpdateRequest{ + RGID: rgId, + } + + if d.HasChange("name") { + log.Debugf("resourceResgroupUpdate: name specified - looking for deltas from the old settings") + req.Name = d.Get("name").(string) + } + + if d.HasChange("quota") { + log.Debugf("resourceResgroupUpdate: quota specified - looking for deltas from the old quota.") + quotaList := d.Get("quota").([]interface{}) + quota := quotaList[0].(map[string]interface{}) + req.MaxCPUCapacity = int64(quota["cpu"].(int)) + req.MaxVDiskCapacity = int64(quota["disk"].(int)) + req.MaxMemoryCapacity = int64(quota["ram"].(int)) + req.MaxNetworkPeerTransfer = int64(quota["ext_traffic"].(int)) + req.MaxNumPublicIP = int64(quota["ext_ips"].(int)) + } + + if d.HasChange("description") { + log.Debugf("resourceResgroupUpdate: description specified - looking for deltas from the old settings.") + req.Description = d.Get("description").(string) + } + + if d.HasChange("register_computes") { + log.Debugf("resourceResgroupUpdate: register_computes specified - looking for deltas from the old settings.") + req.RegisterComputes = d.Get("register_computes").(bool) + } + + if reason, ok := d.GetOk("reason"); ok { + req.Reason = reason.(string) + } + + _, err := c.CloudAPI().RG().Update(ctx, req) + if err != nil { + return err + } + return nil +} diff --git a/internal/service/cloudapi/stack/data_source_stack.go b/internal/service/cloudapi/stack/data_source_stack.go index 48a9e04..10bd1bd 100644 --- a/internal/service/cloudapi/stack/data_source_stack.go +++ b/internal/service/cloudapi/stack/data_source_stack.go @@ -1,110 +1,110 @@ -/* -Copyright (c) 2019-2022 Digital Energy Cloud Solutions LLC. All Rights Reserved. -Authors: -Petr Krutov, -Stanislav Solovev, -Kasim Baybikov, - -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 stack - -import ( - "context" - "strconv" - - "repository.basistech.ru/BASIS/terraform-provider-decort/internal/constants" - - "github.com/hashicorp/terraform-plugin-sdk/v2/diag" - "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" -) - -func dataSourceStackSchemaMake() map[string]*schema.Schema { - res := map[string]*schema.Schema{ - "stack_id": { - Type: schema.TypeInt, - Required: true, - }, - "cpu_allocation_ratio": { - Type: schema.TypeInt, - Computed: true, - }, - "descr": { - Type: schema.TypeString, - Computed: true, - }, - "drivers": { - Type: schema.TypeList, - Computed: true, - Elem: &schema.Schema{ - Type: schema.TypeString, - }, - }, - "mem_allocation_ratio": { - Type: schema.TypeInt, - Computed: true, - }, - "name": { - Type: schema.TypeString, - Computed: true, - }, - "status": { - Type: schema.TypeString, - Computed: true, - }, - "type": { - Type: schema.TypeString, - Computed: true, - }, - } - return res -} - -func dataSourceStackRead(ctx context.Context, d *schema.ResourceData, m interface{}) diag.Diagnostics { - stack, err := utilityStackCheckPresence(ctx, d, m) - if err != nil { - d.SetId("") // ensure ID is empty in this case - return diag.FromErr(err) - } - d.SetId(strconv.Itoa(d.Get("stack_id").(int))) - flattenStack(d, *stack) - return nil -} - -func DataSourceStack() *schema.Resource { - return &schema.Resource{ - SchemaVersion: 1, - - ReadContext: dataSourceStackRead, - - Timeouts: &schema.ResourceTimeout{ - Read: &constants.Timeout30s, - Default: &constants.Timeout60s, - }, - - Schema: dataSourceStackSchemaMake(), - } -} +/* +Copyright (c) 2019-2022 Digital Energy Cloud Solutions LLC. All Rights Reserved. +Authors: +Petr Krutov, +Stanislav Solovev, +Kasim Baybikov, + +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 stack + +import ( + "context" + "strconv" + + "repository.basistech.ru/BASIS/terraform-provider-decort/internal/constants" + + "github.com/hashicorp/terraform-plugin-sdk/v2/diag" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" +) + +func dataSourceStackRead(ctx context.Context, d *schema.ResourceData, m interface{}) diag.Diagnostics { + stack, err := utilityStackCheckPresence(ctx, d, m) + if err != nil { + d.SetId("") // ensure ID is empty in this case + return diag.FromErr(err) + } + d.SetId(strconv.Itoa(d.Get("stack_id").(int))) + flattenStack(d, stack) + return nil +} + +func dataSourceStackSchemaMake() map[string]*schema.Schema { + res := map[string]*schema.Schema{ + "stack_id": { + Type: schema.TypeInt, + Required: true, + }, + "cpu_allocation_ratio": { + Type: schema.TypeFloat, + Computed: true, + }, + "descr": { + Type: schema.TypeString, + Computed: true, + }, + "drivers": { + Type: schema.TypeList, + Computed: true, + Elem: &schema.Schema{ + Type: schema.TypeString, + }, + }, + "mem_allocation_ratio": { + Type: schema.TypeFloat, + Computed: true, + }, + "name": { + Type: schema.TypeString, + Computed: true, + }, + "status": { + Type: schema.TypeString, + Computed: true, + }, + "type": { + Type: schema.TypeString, + Computed: true, + }, + } + return res +} + +func DataSourceStack() *schema.Resource { + return &schema.Resource{ + SchemaVersion: 1, + + ReadContext: dataSourceStackRead, + + Timeouts: &schema.ResourceTimeout{ + Read: &constants.Timeout30s, + Default: &constants.Timeout60s, + }, + + Schema: dataSourceStackSchemaMake(), + } +} diff --git a/internal/service/cloudapi/stack/data_source_stack_list.go b/internal/service/cloudapi/stack/data_source_stack_list.go index b949cce..a50988d 100644 --- a/internal/service/cloudapi/stack/data_source_stack_list.go +++ b/internal/service/cloudapi/stack/data_source_stack_list.go @@ -1,136 +1,137 @@ -/* -Copyright (c) 2019-2022 Digital Energy Cloud Solutions LLC. All Rights Reserved. -Authors: -Petr Krutov, -Stanislav Solovev, -Kasim Baybikov, - -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 stack - -import ( - "context" - - "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" -) - -func dataSourceStackListRead(ctx context.Context, d *schema.ResourceData, m interface{}) diag.Diagnostics { - stackList, err := utilityStackListCheckPresence(ctx, d, m) - if err != nil { - return diag.FromErr(err) - } - - id := uuid.New() - d.SetId(id.String()) - d.Set("items", flattenStackList(stackList)) - d.Set("entry_count", stackList.EntryCount) - - return nil -} - -func dataSourceStackListSchemaMake() map[string]*schema.Schema { - res := map[string]*schema.Schema{ - "by_id": { - Type: schema.TypeInt, - Optional: true, - Description: "Find by ID", - }, - "name": { - Type: schema.TypeString, - Optional: true, - Description: "Find by name", - }, - "type": { - Type: schema.TypeString, - Optional: true, - Description: "Find by type", - }, - "status": { - Type: schema.TypeString, - Optional: true, - Description: "Find by status", - }, - "page": { - Type: schema.TypeInt, - Optional: true, - Description: "Page number", - }, - "size": { - Type: schema.TypeInt, - Optional: true, - Description: "Page size", - }, - - "items": { - Type: schema.TypeList, - Computed: true, - Elem: &schema.Resource{ - Schema: map[string]*schema.Schema{ - "stack_id": { - Type: schema.TypeInt, - Computed: true, - }, - "name": { - Type: schema.TypeString, - Computed: true, - }, - "status": { - Type: schema.TypeString, - Computed: true, - }, - "type": { - Type: schema.TypeString, - Computed: true, - }, - }, - }, - }, - "entry_count": { - Type: schema.TypeInt, - Computed: true, - }, - } - return res -} - -func DataSourceStackList() *schema.Resource { - return &schema.Resource{ - SchemaVersion: 1, - - ReadContext: dataSourceStackListRead, - - Timeouts: &schema.ResourceTimeout{ - Read: &constants.Timeout30s, - Default: &constants.Timeout60s, - }, - - Schema: dataSourceStackListSchemaMake(), - } -} +/* +Copyright (c) 2019-2022 Digital Energy Cloud Solutions LLC. All Rights Reserved. +Authors: +Petr Krutov, +Stanislav Solovev, +Kasim Baybikov, + +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 stack + +import ( + "context" + + "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" +) + +func dataSourceStackListRead(ctx context.Context, d *schema.ResourceData, m interface{}) diag.Diagnostics { + stackList, err := utilityStackListCheckPresence(ctx, d, m) + if err != nil { + d.SetId("") + return diag.FromErr(err) + } + + id := uuid.New() + d.SetId(id.String()) + d.Set("items", flattenStackList(stackList)) + d.Set("entry_count", stackList.EntryCount) + + return nil +} + +func dataSourceStackListSchemaMake() map[string]*schema.Schema { + res := map[string]*schema.Schema{ + "by_id": { + Type: schema.TypeInt, + Optional: true, + Description: "Find by ID", + }, + "name": { + Type: schema.TypeString, + Optional: true, + Description: "Find by name", + }, + "type": { + Type: schema.TypeString, + Optional: true, + Description: "Find by type", + }, + "status": { + Type: schema.TypeString, + Optional: true, + Description: "Find by status", + }, + "page": { + Type: schema.TypeInt, + Optional: true, + Description: "Page number", + }, + "size": { + Type: schema.TypeInt, + Optional: true, + Description: "Page size", + }, + + "items": { + Type: schema.TypeList, + Computed: true, + Elem: &schema.Resource{ + Schema: map[string]*schema.Schema{ + "stack_id": { + Type: schema.TypeInt, + Computed: true, + }, + "name": { + Type: schema.TypeString, + Computed: true, + }, + "status": { + Type: schema.TypeString, + Computed: true, + }, + "type": { + Type: schema.TypeString, + Computed: true, + }, + }, + }, + }, + "entry_count": { + Type: schema.TypeInt, + Computed: true, + }, + } + return res +} + +func DataSourceStackList() *schema.Resource { + return &schema.Resource{ + SchemaVersion: 1, + + ReadContext: dataSourceStackListRead, + + Timeouts: &schema.ResourceTimeout{ + Read: &constants.Timeout30s, + Default: &constants.Timeout60s, + }, + + Schema: dataSourceStackListSchemaMake(), + } +} diff --git a/internal/service/cloudapi/stack/flattens.go b/internal/service/cloudapi/stack/flattens.go index d6c0805..5eb3327 100644 --- a/internal/service/cloudapi/stack/flattens.go +++ b/internal/service/cloudapi/stack/flattens.go @@ -1,69 +1,69 @@ -/* -Copyright (c) 2019-2022 Digital Energy Cloud Solutions LLC. All Rights Reserved. -Authors: -Petr Krutov, -Stanislav Solovev, -Kasim Baybikov, - -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 stack - -import ( - "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" - log "github.com/sirupsen/logrus" - "repository.basistech.ru/BASIS/decort-golang-sdk/pkg/cloudapi/stack" -) - -func flattenStackList(stackl *stack.ListStacks) []map[string]interface{} { - res := make([]map[string]interface{}, 0) - for _, stack := range stackl.Data { - temp := map[string]interface{}{ - "stack_id": stack.ID, - "name": stack.Name, - "status": stack.Status, - "type": stack.Type, - } - res = append(res, temp) - } - return res - -} - -func flattenStack(d *schema.ResourceData, details stack.InfoStack) error { - log.Debugf("flattenStack: decoded Stack name %q / ID %d", - details.Name, details.ID) - - d.Set("stack_id", details.ID) - d.Set("cpu_allocation_ratio", details.CPUAllocationRatio) - d.Set("name", details.Name) - d.Set("descr", details.Descr) - d.Set("mem_allocation_ratio", details.MemAllocationRatio) - d.Set("status", details.Status) - d.Set("type", details.Type) - d.Set("drivers", details.Drivers) - return nil -} +/* +Copyright (c) 2019-2022 Digital Energy Cloud Solutions LLC. All Rights Reserved. +Authors: +Petr Krutov, +Stanislav Solovev, +Kasim Baybikov, + +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 stack + +import ( + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" + log "github.com/sirupsen/logrus" + "repository.basistech.ru/BASIS/decort-golang-sdk/pkg/cloudapi/stack" +) + +func flattenStackList(stackl *stack.ListStacks) []map[string]interface{} { + res := make([]map[string]interface{}, 0) + for _, stack := range stackl.Data { + temp := map[string]interface{}{ + "stack_id": stack.ID, + "name": stack.Name, + "status": stack.Status, + "type": stack.Type, + } + res = append(res, temp) + } + return res + +} + +func flattenStack(d *schema.ResourceData, details *stack.InfoStack) error { + log.Debugf("flattenStack: decoded Stack name %q / ID %d", + details.Name, details.ID) + + d.Set("stack_id", details.ID) + d.Set("cpu_allocation_ratio", details.CPUAllocationRatio) + d.Set("name", details.Name) + d.Set("descr", details.Descr) + d.Set("mem_allocation_ratio", details.MemAllocationRatio) + d.Set("status", details.Status) + d.Set("type", details.Type) + d.Set("drivers", details.Drivers) + return nil +} diff --git a/internal/service/cloudapi/vins/data_source_static_route.go b/internal/service/cloudapi/vins/data_source_static_route.go index 3946f03..a54b67a 100644 --- a/internal/service/cloudapi/vins/data_source_static_route.go +++ b/internal/service/cloudapi/vins/data_source_static_route.go @@ -1,107 +1,108 @@ -/* -Copyright (c) 2019-2022 Digital Energy Cloud Solutions LLC. All Rights Reserved. -Authors: -Petr Krutov, -Stanislav Solovev, -Kasim Baybikov, - -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 vins - -import ( - "context" - "strconv" - - "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" -) - -func dataSourceStaticRouteRead(ctx context.Context, d *schema.ResourceData, m interface{}) diag.Diagnostics { - staticRoute, err := utilityDataStaticRouteCheckPresence(ctx, d, m) - if err != nil { - return diag.FromErr(err) - } - - d.SetId(strconv.FormatUint(staticRoute.ID, 10)) - flattenStaticRouteData(d, staticRoute) - return nil -} - -func dataSourceStaticRouteSchemaMake() map[string]*schema.Schema { - rets := map[string]*schema.Schema{ - "vins_id": { - Type: schema.TypeInt, - Required: true, - Description: "Unique ID of the ViNS", - }, - "route_id": { - Type: schema.TypeInt, - Required: true, - Description: "Unique ID of the static route", - }, - "compute_ids": { - Type: schema.TypeList, - Computed: true, - Elem: &schema.Schema{ - Type: schema.TypeInt, - }, - }, - "destination": { - Type: schema.TypeString, - Computed: true, - }, - "gateway": { - Type: schema.TypeString, - Computed: true, - }, - "guid": { - Type: schema.TypeString, - Computed: true, - }, - "netmask": { - Type: schema.TypeString, - Computed: true, - }, - } - return rets -} - -func DataSourceStaticRoute() *schema.Resource { - return &schema.Resource{ - SchemaVersion: 1, - - ReadContext: dataSourceStaticRouteRead, - - Timeouts: &schema.ResourceTimeout{ - Read: &constants.Timeout30s, - Default: &constants.Timeout60s, - }, - - Schema: dataSourceStaticRouteSchemaMake(), - } -} +/* +Copyright (c) 2019-2022 Digital Energy Cloud Solutions LLC. All Rights Reserved. +Authors: +Petr Krutov, +Stanislav Solovev, +Kasim Baybikov, + +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 vins + +import ( + "context" + "strconv" + + "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" +) + +func dataSourceStaticRouteRead(ctx context.Context, d *schema.ResourceData, m interface{}) diag.Diagnostics { + staticRoute, err := utilityDataStaticRouteCheckPresence(ctx, d, m) + if err != nil { + d.SetId("") + return diag.FromErr(err) + } + + d.SetId(strconv.FormatUint(staticRoute.ID, 10)) + flattenStaticRouteData(d, staticRoute) + return nil +} + +func dataSourceStaticRouteSchemaMake() map[string]*schema.Schema { + rets := map[string]*schema.Schema{ + "vins_id": { + Type: schema.TypeInt, + Required: true, + Description: "Unique ID of the ViNS", + }, + "route_id": { + Type: schema.TypeInt, + Required: true, + Description: "Unique ID of the static route", + }, + "compute_ids": { + Type: schema.TypeList, + Computed: true, + Elem: &schema.Schema{ + Type: schema.TypeInt, + }, + }, + "destination": { + Type: schema.TypeString, + Computed: true, + }, + "gateway": { + Type: schema.TypeString, + Computed: true, + }, + "guid": { + Type: schema.TypeString, + Computed: true, + }, + "netmask": { + Type: schema.TypeString, + Computed: true, + }, + } + return rets +} + +func DataSourceStaticRoute() *schema.Resource { + return &schema.Resource{ + SchemaVersion: 1, + + ReadContext: dataSourceStaticRouteRead, + + Timeouts: &schema.ResourceTimeout{ + Read: &constants.Timeout30s, + Default: &constants.Timeout60s, + }, + + Schema: dataSourceStaticRouteSchemaMake(), + } +} diff --git a/internal/service/cloudapi/vins/data_source_static_route_list.go b/internal/service/cloudapi/vins/data_source_static_route_list.go index 38a0697..f36106d 100644 --- a/internal/service/cloudapi/vins/data_source_static_route_list.go +++ b/internal/service/cloudapi/vins/data_source_static_route_list.go @@ -1,121 +1,122 @@ -/* -Copyright (c) 2019-2022 Digital Energy Cloud Solutions LLC. All Rights Reserved. -Authors: -Petr Krutov, -Stanislav Solovev, -Kasim Baybikov, - -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 vins - -import ( - "context" - - "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" -) - -func dataSourceStaticRouteListRead(ctx context.Context, d *schema.ResourceData, m interface{}) diag.Diagnostics { - staticRouteList, err := utilityStaticRouteListCheckPresence(ctx, d, m) - if err != nil { - return diag.FromErr(err) - } - - id := uuid.New() - d.SetId(id.String()) - d.Set("items", flattenStaticRouteList(staticRouteList)) - d.Set("entry_count", staticRouteList.EntryCount) - - return nil -} - -func dataSourceStaticRouteListSchemaMake() map[string]*schema.Schema { - res := map[string]*schema.Schema{ - "vins_id": { - Type: schema.TypeInt, - Required: true, - Description: "ID of VINS", - }, - "items": { - Type: schema.TypeList, - Computed: true, - Elem: &schema.Resource{ - Schema: map[string]*schema.Schema{ - "compute_ids": { - Type: schema.TypeList, - Computed: true, - Elem: &schema.Schema{ - Type: schema.TypeInt, - }, - }, - "destination": { - Type: schema.TypeString, - Computed: true, - }, - "gateway": { - Type: schema.TypeString, - Computed: true, - }, - "guid": { - Type: schema.TypeString, - Computed: true, - }, - "netmask": { - Type: schema.TypeString, - Computed: true, - }, - "route_id": { - Type: schema.TypeInt, - Computed: true, - }, - }, - }, - }, - "entry_count": { - Type: schema.TypeInt, - Computed: true, - }, - } - return res -} - -func DataSourceStaticRouteList() *schema.Resource { - return &schema.Resource{ - SchemaVersion: 1, - - ReadContext: dataSourceStaticRouteListRead, - - Timeouts: &schema.ResourceTimeout{ - Read: &constants.Timeout30s, - Default: &constants.Timeout60s, - }, - - Schema: dataSourceStaticRouteListSchemaMake(), - } -} +/* +Copyright (c) 2019-2022 Digital Energy Cloud Solutions LLC. All Rights Reserved. +Authors: +Petr Krutov, +Stanislav Solovev, +Kasim Baybikov, + +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 vins + +import ( + "context" + + "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" +) + +func dataSourceStaticRouteListRead(ctx context.Context, d *schema.ResourceData, m interface{}) diag.Diagnostics { + staticRouteList, err := utilityStaticRouteListCheckPresence(ctx, d, m) + if err != nil { + d.SetId("") + return diag.FromErr(err) + } + + id := uuid.New() + d.SetId(id.String()) + d.Set("items", flattenStaticRouteList(staticRouteList)) + d.Set("entry_count", staticRouteList.EntryCount) + + return nil +} + +func dataSourceStaticRouteListSchemaMake() map[string]*schema.Schema { + res := map[string]*schema.Schema{ + "vins_id": { + Type: schema.TypeInt, + Required: true, + Description: "ID of VINS", + }, + "items": { + Type: schema.TypeList, + Computed: true, + Elem: &schema.Resource{ + Schema: map[string]*schema.Schema{ + "compute_ids": { + Type: schema.TypeList, + Computed: true, + Elem: &schema.Schema{ + Type: schema.TypeInt, + }, + }, + "destination": { + Type: schema.TypeString, + Computed: true, + }, + "gateway": { + Type: schema.TypeString, + Computed: true, + }, + "guid": { + Type: schema.TypeString, + Computed: true, + }, + "netmask": { + Type: schema.TypeString, + Computed: true, + }, + "route_id": { + Type: schema.TypeInt, + Computed: true, + }, + }, + }, + }, + "entry_count": { + Type: schema.TypeInt, + Computed: true, + }, + } + return res +} + +func DataSourceStaticRouteList() *schema.Resource { + return &schema.Resource{ + SchemaVersion: 1, + + ReadContext: dataSourceStaticRouteListRead, + + Timeouts: &schema.ResourceTimeout{ + Read: &constants.Timeout30s, + Default: &constants.Timeout60s, + }, + + Schema: dataSourceStaticRouteListSchemaMake(), + } +} diff --git a/internal/service/cloudapi/vins/data_source_vins.go b/internal/service/cloudapi/vins/data_source_vins.go index 711ca39..2e02964 100644 --- a/internal/service/cloudapi/vins/data_source_vins.go +++ b/internal/service/cloudapi/vins/data_source_vins.go @@ -130,6 +130,10 @@ func vnfInterfaceSchemaMake() map[string]*schema.Schema { Type: schema.TypeString, Computed: true, }, + "enabled": { + Type: schema.TypeBool, + Computed: true, + }, "flipgroup_id": { Type: schema.TypeInt, Computed: true, @@ -486,6 +490,13 @@ func dhcpSchemaMake() map[string]*schema.Schema { Type: schema.TypeBool, Computed: true, }, + "routes": { + Type: schema.TypeList, + Computed: true, + Elem: &schema.Resource{ + Schema: routesSchemaMake(), + }, + }, "status": { Type: schema.TypeString, Computed: true, @@ -501,6 +512,39 @@ func dhcpSchemaMake() map[string]*schema.Schema { } } +func routesSchemaMake() map[string]*schema.Schema { + return map[string]*schema.Schema{ + "route_id": { + Type: schema.TypeInt, + Required: true, + Description: "Unique ID of the static route", + }, + "compute_ids": { + Type: schema.TypeList, + Computed: true, + Elem: &schema.Schema{ + Type: schema.TypeInt, + }, + }, + "destination": { + Type: schema.TypeString, + Computed: true, + }, + "gateway": { + Type: schema.TypeString, + Computed: true, + }, + "guid": { + Type: schema.TypeString, + Computed: true, + }, + "netmask": { + Type: schema.TypeString, + Computed: true, + }, + } +} + func gwConfigSchemaMake() map[string]*schema.Schema { return map[string]*schema.Schema{ "default_gw": { @@ -589,6 +633,13 @@ func gwSchemaMake() map[string]*schema.Schema { Type: schema.TypeBool, Computed: true, }, + "routes": { + Type: schema.TypeList, + Computed: true, + Elem: &schema.Resource{ + Schema: routesSchemaMake(), + }, + }, "status": { Type: schema.TypeString, Computed: true, @@ -721,6 +772,13 @@ func natSchemaMake() map[string]*schema.Schema { Type: schema.TypeBool, Computed: true, }, + "routes": { + Type: schema.TypeList, + Computed: true, + Elem: &schema.Resource{ + Schema: routesSchemaMake(), + }, + }, "status": { Type: schema.TypeString, Computed: true, diff --git a/internal/service/cloudapi/vins/data_source_vins_audits.go b/internal/service/cloudapi/vins/data_source_vins_audits.go index 6d870dd..b41428c 100644 --- a/internal/service/cloudapi/vins/data_source_vins_audits.go +++ b/internal/service/cloudapi/vins/data_source_vins_audits.go @@ -44,6 +44,7 @@ import ( func dataSourceVinsAuditsRead(ctx context.Context, d *schema.ResourceData, m interface{}) diag.Diagnostics { audits, err := utilityVinsAuditsCheckPresence(ctx, d, m) if err != nil { + d.SetId("") return diag.FromErr(err) } id := uuid.New() diff --git a/internal/service/cloudapi/vins/data_source_vins_ext_net_list.go b/internal/service/cloudapi/vins/data_source_vins_ext_net_list.go index 6f3fa22..6e5e82e 100644 --- a/internal/service/cloudapi/vins/data_source_vins_ext_net_list.go +++ b/internal/service/cloudapi/vins/data_source_vins_ext_net_list.go @@ -44,6 +44,7 @@ import ( func dataSourceVinsExtNetListRead(ctx context.Context, d *schema.ResourceData, m interface{}) diag.Diagnostics { extNetList, err := utilityVinsExtNetListCheckPresence(ctx, d, m) if err != nil { + d.SetId("") return diag.FromErr(err) } id := uuid.New() diff --git a/internal/service/cloudapi/vins/data_source_vins_ip_list.go b/internal/service/cloudapi/vins/data_source_vins_ip_list.go index 554656e..108d87b 100644 --- a/internal/service/cloudapi/vins/data_source_vins_ip_list.go +++ b/internal/service/cloudapi/vins/data_source_vins_ip_list.go @@ -44,6 +44,7 @@ import ( func dataSourceVinsIpListRead(ctx context.Context, d *schema.ResourceData, m interface{}) diag.Diagnostics { ips, err := utilityVinsIpListCheckPresence(ctx, d, m) if err != nil { + d.SetId("") return diag.FromErr(err) } id := uuid.New() diff --git a/internal/service/cloudapi/vins/data_source_vins_list.go b/internal/service/cloudapi/vins/data_source_vins_list.go index 526e631..08a7dba 100644 --- a/internal/service/cloudapi/vins/data_source_vins_list.go +++ b/internal/service/cloudapi/vins/data_source_vins_list.go @@ -44,6 +44,7 @@ import ( func dataSourceVinsListRead(ctx context.Context, d *schema.ResourceData, m interface{}) diag.Diagnostics { vinsList, err := utilityVinsListCheckPresence(ctx, d, m) if err != nil { + d.SetId("") return diag.FromErr(err) } diff --git a/internal/service/cloudapi/vins/data_source_vins_list_deleted.go b/internal/service/cloudapi/vins/data_source_vins_list_deleted.go index d240d3a..bfda239 100644 --- a/internal/service/cloudapi/vins/data_source_vins_list_deleted.go +++ b/internal/service/cloudapi/vins/data_source_vins_list_deleted.go @@ -44,6 +44,7 @@ import ( func dataSourceVinsListDeletedRead(ctx context.Context, d *schema.ResourceData, m interface{}) diag.Diagnostics { vinsList, err := utilityVinsListDeletedCheckPresence(ctx, d, m) if err != nil { + d.SetId("") return diag.FromErr(err) } diff --git a/internal/service/cloudapi/vins/data_source_vins_nat_rule_list.go b/internal/service/cloudapi/vins/data_source_vins_nat_rule_list.go index 16211a5..07753c5 100644 --- a/internal/service/cloudapi/vins/data_source_vins_nat_rule_list.go +++ b/internal/service/cloudapi/vins/data_source_vins_nat_rule_list.go @@ -44,6 +44,7 @@ import ( func dataSourceVinsNatRuleListRead(ctx context.Context, d *schema.ResourceData, m interface{}) diag.Diagnostics { natRules, err := utilityVinsNatRuleListCheckPresence(ctx, d, m) if err != nil { + d.SetId("") return diag.FromErr(err) } id := uuid.New() diff --git a/internal/service/cloudapi/vins/flattens.go b/internal/service/cloudapi/vins/flattens.go index d1ff95f..0fb1226 100644 --- a/internal/service/cloudapi/vins/flattens.go +++ b/internal/service/cloudapi/vins/flattens.go @@ -90,6 +90,7 @@ func flattenInterfaces(interfaces []vins.ItemVNFInterface) []map[string]interfac "conn_id": vnfInterface.ConnID, "conn_type": vnfInterface.ConnType, "def_gw": vnfInterface.DefGW, + "enabled": vnfInterface.Enabled, "flipgroup_id": vnfInterface.FLIPGroupID, "guid": vnfInterface.GUID, "ip_address": vnfInterface.IPAddress, @@ -226,6 +227,7 @@ func flattenDHCP(dhcp vins.RecordDHCP) []map[string]interface{} { "owner_id": dhcp.OwnerID, "owner_type": dhcp.OwnerType, "pure_virtual": dhcp.PureVirtual, + "routes": flattenStaticRoute(dhcp.Routes), "status": dhcp.Status, "tech_status": dhcp.TechStatus, "type": dhcp.Type, @@ -265,6 +267,7 @@ func flattenGW(gw vins.RecordGW) []map[string]interface{} { "owner_id": gw.OwnerID, "owner_type": gw.OwnerType, "pure_virtual": gw.PureVirtual, + "routes": flattenStaticRoute(gw.Routes), "status": gw.Status, "tech_status": gw.TechStatus, "type": gw.Type, @@ -321,6 +324,7 @@ func flattenNAT(nat vins.RecordNAT) []map[string]interface{} { "owner_id": nat.OwnerID, "owner_type": nat.OwnerType, "pure_virtual": nat.PureVirtual, + "routes": flattenStaticRoute(nat.Routes), "status": nat.Status, "tech_status": nat.TechStatus, "type": nat.Type, @@ -508,7 +512,7 @@ func flattenVinsList(vl *vins.ListVINS) []map[string]interface{} { // /4.4.0 func flattenStaticRouteList(sr *vins.ListStaticRoutes) []map[string]interface{} { - res := make([]map[string]interface{}, 0) + res := make([]map[string]interface{}, 0, len(sr.Data)) for _, staticRoute := range sr.Data { temp := map[string]interface{}{ "route_id": staticRoute.ID, @@ -533,6 +537,22 @@ func flattenStaticRouteData(d *schema.ResourceData, route *vins.ItemRoutes) { d.Set("route_id", route.ID) } +func flattenStaticRoute(sr vins.ListRoutes) []map[string]interface{} { + res := make([]map[string]interface{}, 0, len(sr)) + for _, staticRoute := range sr { + temp := map[string]interface{}{ + "route_id": staticRoute.ID, + "destination": staticRoute.Destination, + "gateway": staticRoute.Gateway, + "guid": staticRoute.GUID, + "netmask": staticRoute.Netmask, + "compute_ids": staticRoute.ComputeIds, + } + res = append(res, temp) + } + return res +} + /// func flattenVinsNatRuleList(natRules *vins.ListNATRules) []map[string]interface{} { diff --git a/internal/service/cloudapi/vins/resource_static_route.go b/internal/service/cloudapi/vins/resource_static_route.go index 6574530..1460792 100644 --- a/internal/service/cloudapi/vins/resource_static_route.go +++ b/internal/service/cloudapi/vins/resource_static_route.go @@ -1,276 +1,277 @@ -/* -Copyright (c) 2019-2022 Digital Energy Cloud Solutions LLC. All Rights Reserved. -Authors: -Petr Krutov, -Stanislav Solovev, -Kasim Baybikov, - -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 vins - -import ( - "context" - "fmt" - "strconv" - "strings" - - "repository.basistech.ru/BASIS/decort-golang-sdk/pkg/cloudapi/vins" - "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" - - "github.com/hashicorp/terraform-plugin-sdk/v2/diag" - "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" -) - -func resourceStaticRouteCreate(ctx context.Context, d *schema.ResourceData, m interface{}) diag.Diagnostics { - c := m.(*controller.ControllerCfg) - - if _, ok := d.GetOk("vins_id"); ok { - haveVinsID, err := existVinsID(ctx, d, m) - if err != nil { - return diag.FromErr(err) - } - - if !haveVinsID { - return diag.Errorf("resourceStaticRouteCreate: can't create Static Route because Vins ID %d is not allowed or does not exist", d.Get("vins_id").(int)) - } - } - - req := vins.StaticRouteAddRequest{ - VINSID: uint64(d.Get("vins_id").(int)), - Destination: d.Get("destination").(string), - Netmask: d.Get("netmask").(string), - Gateway: d.Get("gateway").(string), - } - - if computesIDS, ok := d.GetOk("compute_ids"); ok { - ids := computesIDS.([]interface{}) - - res := make([]uint64, 10) - - for _, id := range ids { - computeId := uint64(id.(int)) - res = append(res, computeId) - } - - req.ComputeIds = res - } - - _, err := c.CloudAPI().VINS().StaticRouteAdd(ctx, req) - if err != nil { - return diag.FromErr(err) - } - - staticRouteData, err := getStaticRouteData(ctx, d, m) - if err != nil { - return diag.FromErr(err) - } - - d.SetId(fmt.Sprintf("%d#%d", req.VINSID, staticRouteData.ID)) - - return resourceStaticRouteRead(ctx, d, m) -} - -func resourceStaticRouteRead(ctx context.Context, d *schema.ResourceData, m interface{}) diag.Diagnostics { - warnings := dc.Warnings{} - - staticRouteData, err := utilityDataStaticRouteCheckPresence(ctx, d, m) - if err != nil { - d.SetId("") - return diag.FromErr(err) - } - - flattenStaticRouteData(d, staticRouteData) - - return warnings.Get() -} - -func resourceStaticRouteUpdate(ctx context.Context, d *schema.ResourceData, m interface{}) diag.Diagnostics { - c := m.(*controller.ControllerCfg) - warnings := dc.Warnings{} - - if _, ok := d.GetOk("vins_id"); ok { - haveVinsID, err := existVinsID(ctx, d, m) - if err != nil { - return diag.FromErr(err) - } - - if !haveVinsID { - return diag.Errorf("resourceVinsUpdate: can't update Static Route because VinsID %d is not allowed or does not exist", d.Get("vins_id").(int)) - } - } - - staticRouteData, err := utilityDataStaticRouteCheckPresence(ctx, d, m) - if err != nil { - d.SetId("") - return diag.FromErr(err) - } - - if d.HasChange("compute_ids") { - deletedIds := make([]uint64, 0) - addedIds := make([]uint64, 0) - - oldComputeIds, newComputeIds := d.GetChange("compute_ids") - oldComputeIdsSlice := oldComputeIds.([]interface{}) - newComputeIdsSlice := newComputeIds.([]interface{}) - - for _, el := range oldComputeIdsSlice { - if !isContainsIds(newComputeIdsSlice, el) { - convertedEl := uint64(el.(int)) - deletedIds = append(deletedIds, convertedEl) - } - } - - for _, el := range newComputeIdsSlice { - if !isContainsIds(oldComputeIdsSlice, el) { - convertedEl := uint64(el.(int)) - addedIds = append(addedIds, convertedEl) - } - } - - if len(deletedIds) > 0 { - req := vins.StaticRouteAccessRevokeRequest{ - VINSID: uint64(d.Get("vins_id").(int)), - RouteId: staticRouteData.ID, - ComputeIds: deletedIds, - } - - _, err := c.CloudAPI().VINS().StaticRouteAccessRevoke(ctx, req) - if err != nil { - warnings.Add(err) - } - } - - if len(addedIds) > 0 { - req := vins.StaticRouteAccessGrantRequest{ - VINSID: uint64(d.Get("vins_id").(int)), - RouteId: staticRouteData.ID, - ComputeIds: addedIds, - } - - _, err := c.CloudAPI().VINS().StaticRouteAccessGrant(ctx, req) - if err != nil { - warnings.Add(err) - } - } - } - - return append(warnings.Get(), resourceStaticRouteRead(ctx, d, m)...) -} - -func resourceStaticRouteDelete(ctx context.Context, d *schema.ResourceData, m interface{}) diag.Diagnostics { - c := m.(*controller.ControllerCfg) - arr := strings.Split(d.Id(), "#") - if len(arr) != 2 { - return diag.FromErr(fmt.Errorf("broken state id")) - } - - vinsId, _ := strconv.ParseUint(arr[0], 10, 64) - routeId, _ := strconv.ParseUint(arr[1], 10, 64) - - req := vins.StaticRouteDelRequest{ - VINSID: vinsId, - RouteId: routeId, - } - - _, err := c.CloudAPI().VINS().StaticRouteDel(ctx, req) - if err != nil { - return diag.FromErr(err) - } - - d.SetId("") - - return nil -} - -func resourceStaticRouteSchemaMake() map[string]*schema.Schema { - rets := dataSourceStaticRouteSchemaMake() - rets["route_id"] = &schema.Schema{ - Type: schema.TypeInt, - Computed: true, - Optional: true, - } - rets["compute_ids"] = &schema.Schema{ - Type: schema.TypeList, - Optional: true, - Computed: true, - Elem: &schema.Schema{ - Type: schema.TypeInt, - }, - } - rets["destination"] = &schema.Schema{ - Type: schema.TypeString, - Required: true, - } - - rets["gateway"] = &schema.Schema{ - Type: schema.TypeString, - Required: true, - } - rets["netmask"] = &schema.Schema{ - Type: schema.TypeString, - Required: true, - } - - return rets -} - -func isContainsIds(els []interface{}, el interface{}) bool { - convEl := el.(int) - for _, elOld := range els { - if convEl == elOld.(int) { - return true - } - } - return false -} - -func ResourceStaticRoute() *schema.Resource { - return &schema.Resource{ - SchemaVersion: 1, - - CreateContext: resourceStaticRouteCreate, - ReadContext: resourceStaticRouteRead, - UpdateContext: resourceStaticRouteUpdate, - DeleteContext: resourceStaticRouteDelete, - - Importer: &schema.ResourceImporter{ - StateContext: schema.ImportStatePassthroughContext, - }, - - Timeouts: &schema.ResourceTimeout{ - Create: &constants.Timeout20m, - Read: &constants.Timeout600s, - Update: &constants.Timeout20m, - Delete: &constants.Timeout600s, - Default: &constants.Timeout600s, - }, - - Schema: resourceStaticRouteSchemaMake(), - } -} +/* +Copyright (c) 2019-2022 Digital Energy Cloud Solutions LLC. All Rights Reserved. +Authors: +Petr Krutov, +Stanislav Solovev, +Kasim Baybikov, + +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 vins + +import ( + "context" + "fmt" + "strconv" + "strings" + + "repository.basistech.ru/BASIS/decort-golang-sdk/pkg/cloudapi/vins" + "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" + + "github.com/hashicorp/terraform-plugin-sdk/v2/diag" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" +) + +func resourceStaticRouteCreate(ctx context.Context, d *schema.ResourceData, m interface{}) diag.Diagnostics { + c := m.(*controller.ControllerCfg) + + if _, ok := d.GetOk("vins_id"); ok { + haveVinsID, err := existVinsID(ctx, d, m) + if err != nil { + return diag.FromErr(err) + } + + if !haveVinsID { + return diag.Errorf("resourceStaticRouteCreate: can't create Static Route because Vins ID %d is not allowed or does not exist", d.Get("vins_id").(int)) + } + } + + req := vins.StaticRouteAddRequest{ + VINSID: uint64(d.Get("vins_id").(int)), + Destination: d.Get("destination").(string), + Netmask: d.Get("netmask").(string), + Gateway: d.Get("gateway").(string), + } + + if computesIDS, ok := d.GetOk("compute_ids"); ok { + ids := computesIDS.([]interface{}) + + res := make([]uint64, 10) + + for _, id := range ids { + computeId := uint64(id.(int)) + res = append(res, computeId) + } + + req.ComputeIds = res + } + + _, err := c.CloudAPI().VINS().StaticRouteAdd(ctx, req) + if err != nil { + return diag.FromErr(err) + } + + staticRouteData, err := getStaticRouteData(ctx, d, m) + if err != nil { + d.SetId("") + return diag.FromErr(err) + } + + d.SetId(fmt.Sprintf("%d#%d", req.VINSID, staticRouteData.ID)) + + return resourceStaticRouteRead(ctx, d, m) +} + +func resourceStaticRouteRead(ctx context.Context, d *schema.ResourceData, m interface{}) diag.Diagnostics { + warnings := dc.Warnings{} + + staticRouteData, err := utilityDataStaticRouteCheckPresence(ctx, d, m) + if err != nil { + d.SetId("") + return diag.FromErr(err) + } + + flattenStaticRouteData(d, staticRouteData) + + return warnings.Get() +} + +func resourceStaticRouteUpdate(ctx context.Context, d *schema.ResourceData, m interface{}) diag.Diagnostics { + c := m.(*controller.ControllerCfg) + warnings := dc.Warnings{} + + if _, ok := d.GetOk("vins_id"); ok { + haveVinsID, err := existVinsID(ctx, d, m) + if err != nil { + return diag.FromErr(err) + } + + if !haveVinsID { + return diag.Errorf("resourceVinsUpdate: can't update Static Route because VinsID %d is not allowed or does not exist", d.Get("vins_id").(int)) + } + } + + staticRouteData, err := utilityDataStaticRouteCheckPresence(ctx, d, m) + if err != nil { + d.SetId("") + return diag.FromErr(err) + } + + if d.HasChange("compute_ids") { + deletedIds := make([]uint64, 0) + addedIds := make([]uint64, 0) + + oldComputeIds, newComputeIds := d.GetChange("compute_ids") + oldComputeIdsSlice := oldComputeIds.([]interface{}) + newComputeIdsSlice := newComputeIds.([]interface{}) + + for _, el := range oldComputeIdsSlice { + if !isContainsIds(newComputeIdsSlice, el) { + convertedEl := uint64(el.(int)) + deletedIds = append(deletedIds, convertedEl) + } + } + + for _, el := range newComputeIdsSlice { + if !isContainsIds(oldComputeIdsSlice, el) { + convertedEl := uint64(el.(int)) + addedIds = append(addedIds, convertedEl) + } + } + + if len(deletedIds) > 0 { + req := vins.StaticRouteAccessRevokeRequest{ + VINSID: uint64(d.Get("vins_id").(int)), + RouteId: staticRouteData.ID, + ComputeIds: deletedIds, + } + + _, err := c.CloudAPI().VINS().StaticRouteAccessRevoke(ctx, req) + if err != nil { + warnings.Add(err) + } + } + + if len(addedIds) > 0 { + req := vins.StaticRouteAccessGrantRequest{ + VINSID: uint64(d.Get("vins_id").(int)), + RouteId: staticRouteData.ID, + ComputeIds: addedIds, + } + + _, err := c.CloudAPI().VINS().StaticRouteAccessGrant(ctx, req) + if err != nil { + warnings.Add(err) + } + } + } + + return append(warnings.Get(), resourceStaticRouteRead(ctx, d, m)...) +} + +func resourceStaticRouteDelete(ctx context.Context, d *schema.ResourceData, m interface{}) diag.Diagnostics { + c := m.(*controller.ControllerCfg) + arr := strings.Split(d.Id(), "#") + if len(arr) != 2 { + return diag.FromErr(fmt.Errorf("broken state id")) + } + + vinsId, _ := strconv.ParseUint(arr[0], 10, 64) + routeId, _ := strconv.ParseUint(arr[1], 10, 64) + + req := vins.StaticRouteDelRequest{ + VINSID: vinsId, + RouteId: routeId, + } + + _, err := c.CloudAPI().VINS().StaticRouteDel(ctx, req) + if err != nil { + return diag.FromErr(err) + } + + d.SetId("") + + return nil +} + +func resourceStaticRouteSchemaMake() map[string]*schema.Schema { + rets := dataSourceStaticRouteSchemaMake() + rets["route_id"] = &schema.Schema{ + Type: schema.TypeInt, + Computed: true, + Optional: true, + } + rets["compute_ids"] = &schema.Schema{ + Type: schema.TypeList, + Optional: true, + Computed: true, + Elem: &schema.Schema{ + Type: schema.TypeInt, + }, + } + rets["destination"] = &schema.Schema{ + Type: schema.TypeString, + Required: true, + } + + rets["gateway"] = &schema.Schema{ + Type: schema.TypeString, + Required: true, + } + rets["netmask"] = &schema.Schema{ + Type: schema.TypeString, + Required: true, + } + + return rets +} + +func isContainsIds(els []interface{}, el interface{}) bool { + convEl := el.(int) + for _, elOld := range els { + if convEl == elOld.(int) { + return true + } + } + return false +} + +func ResourceStaticRoute() *schema.Resource { + return &schema.Resource{ + SchemaVersion: 1, + + CreateContext: resourceStaticRouteCreate, + ReadContext: resourceStaticRouteRead, + UpdateContext: resourceStaticRouteUpdate, + DeleteContext: resourceStaticRouteDelete, + + Importer: &schema.ResourceImporter{ + StateContext: schema.ImportStatePassthroughContext, + }, + + Timeouts: &schema.ResourceTimeout{ + Create: &constants.Timeout20m, + Read: &constants.Timeout600s, + Update: &constants.Timeout20m, + Delete: &constants.Timeout600s, + Default: &constants.Timeout600s, + }, + + Schema: resourceStaticRouteSchemaMake(), + } +} diff --git a/internal/service/cloudapi/vins/resource_vins.go b/internal/service/cloudapi/vins/resource_vins.go index 7cb195a..840af9b 100644 --- a/internal/service/cloudapi/vins/resource_vins.go +++ b/internal/service/cloudapi/vins/resource_vins.go @@ -132,17 +132,18 @@ func resourceVinsCreate(ctx context.Context, d *schema.ResourceData, m interface if preReservationsNum, ok := d.GetOk("pre_reservations_num"); ok { req.PreReservationsNum = uint64(preReservationsNum.(int)) } - + id, err := c.CloudAPI().VINS().CreateInRG(ctx, req) if err != nil { + d.SetId("") return diag.FromErr(err) } d.SetId(strconv.FormatUint(id, 10)) } else if accountIdOk { req := vins.CreateInAccountRequest{ - Name: d.Get("name").(string), - AccountID: uint64(accountId.(int)), + Name: d.Get("name").(string), + AccountID: uint64(accountId.(int)), } if gid, ok := d.GetOk("gid"); ok { @@ -157,9 +158,10 @@ func resourceVinsCreate(ctx context.Context, d *schema.ResourceData, m interface if preReservationsNum, ok := d.GetOk("pre_reservations_num"); ok { req.PreReservationsNum = uint64(preReservationsNum.(int)) } - + id, err := c.CloudAPI().VINS().CreateInAccount(ctx, req) if err != nil { + d.SetId("") return diag.FromErr(err) } @@ -218,7 +220,6 @@ func resourceVinsCreate(ctx context.Context, d *schema.ResourceData, m interface } } - return append(warnings.Get(), resourceVinsRead(ctx, d, m)...) } @@ -387,22 +388,22 @@ func resourceVinsUpdate(ctx context.Context, d *schema.ResourceData, m interface return diag.Errorf("The resource cannot be updated because it has been destroyed") // return resourceVinsCreate(ctx, d, m) case status.Deleted: - hasChangeState = true - - req := vins.RestoreRequest{ - VINSID: vinsData.ID, - } + if restore, ok := d.GetOk("restore"); ok && restore.(bool) { + req := vins.RestoreRequest{ + VINSID: vinsData.ID, + } - _, err := c.CloudAPI().VINS().Restore(ctx, req) - if err != nil { - warnings.Add(err) + _, err := c.CloudAPI().VINS().Restore(ctx, req) + if err != nil { + warnings.Add(err) + } + hasChangeState = true } case status.Modeled: return diag.Errorf("ViNS are in status: %s, please, contact support for more information", vinsData.Status) case status.Created: case status.Enabled: if !isEnabled { - hasChangeState = true req := vins.DisableEnableRequest{ VINSID: vinsData.ID, } @@ -411,11 +412,11 @@ func resourceVinsUpdate(ctx context.Context, d *schema.ResourceData, m interface if err != nil { warnings.Add(err) } + hasChangeState = true } case status.Enabling: case status.Disabled: if isEnabled { - hasChangeState = true req := vins.DisableEnableRequest{ VINSID: vinsData.ID, } @@ -424,6 +425,7 @@ func resourceVinsUpdate(ctx context.Context, d *schema.ResourceData, m interface if err != nil { warnings.Add(err) } + hasChangeState = true } case status.Disabling: case status.Deleting: @@ -438,62 +440,64 @@ func resourceVinsUpdate(ctx context.Context, d *schema.ResourceData, m interface } } - enableOld, enableNew := d.GetChange("enable") - if enableOld.(bool) && !enableNew.(bool) { - req := vins.DisableEnableRequest{ - VINSID: vinsData.ID, - } - - _, err := c.CloudAPI().VINS().Disable(ctx, req) - if err != nil { - warnings.Add(err) - } - } else if !enableOld.(bool) && enableNew.(bool) { - req := vins.DisableEnableRequest{ - VINSID: vinsData.ID, - } - - _, err := c.CloudAPI().VINS().Enable(ctx, req) - if err != nil { - warnings.Add(err) - } - } - - //extnet v1 - oldExtNetId, newExtNedId := d.GetChange("ext_net_id") - if oldExtNetId.(int) != newExtNedId.(int) { - log.Debugf("resourceVinsUpdate: changing ViNS ID %s - ext_net_id %d -> %d", d.Id(), oldExtNetId.(int), newExtNedId.(int)) - - if oldExtNetId.(int) > 0 { - // there was preexisting external net connection - disconnect ViNS - req := vins.ExtNetDisconnectRequest{VINSID: vinsData.ID} + if d.HasChange("enable") { + enableOld, enableNew := d.GetChange("enable") + if enableOld.(bool) && !enableNew.(bool) { + req := vins.DisableEnableRequest{ + VINSID: vinsData.ID, + } - _, err := c.CloudAPI().VINS().ExtNetDisconnect(ctx, req) + _, err := c.CloudAPI().VINS().Disable(ctx, req) if err != nil { warnings.Add(err) } - } - - if newExtNedId.(int) > 0 { - // new external network connection requested - connect ViNS - req := vins.ExtNetConnectRequest{ + } else if !enableOld.(bool) && enableNew.(bool) { + req := vins.DisableEnableRequest{ VINSID: vinsData.ID, - NetID: uint64(newExtNedId.(int)), - IP: "", } - extNetIp, ok := d.GetOk("ext_net_ip") - if ok && extNetIp.(string) != "" { - req.IP = extNetIp.(string) - } - - _, err := c.CloudAPI().VINS().ExtNetConnect(ctx, req) + _, err := c.CloudAPI().VINS().Enable(ctx, req) if err != nil { warnings.Add(err) } } } + if d.HasChange("ext_net_id") { + //extnet v1 + oldExtNetId, newExtNedId := d.GetChange("ext_net_id") + if oldExtNetId.(int) != newExtNedId.(int) { + log.Debugf("resourceVinsUpdate: changing ViNS ID %s - ext_net_id %d -> %d", d.Id(), oldExtNetId.(int), newExtNedId.(int)) + + if oldExtNetId.(int) > 0 { + // there was preexisting external net connection - disconnect ViNS + req := vins.ExtNetDisconnectRequest{VINSID: vinsData.ID} + _, err := c.CloudAPI().VINS().ExtNetDisconnect(ctx, req) + if err != nil { + warnings.Add(err) + } + } + + if newExtNedId.(int) > 0 { + // new external network connection requested - connect ViNS + req := vins.ExtNetConnectRequest{ + VINSID: vinsData.ID, + NetID: uint64(newExtNedId.(int)), + IP: "", + } + + extNetIp, ok := d.GetOk("ext_net_ip") + if ok && extNetIp.(string) != "" { + req.IP = extNetIp.(string) + } + + _, err := c.CloudAPI().VINS().ExtNetConnect(ctx, req) + if err != nil { + warnings.Add(err) + } + } + } + } if d.HasChange("ip") { deletedIps := make([]interface{}, 0) addedIps := make([]interface{}, 0) @@ -619,25 +623,27 @@ func resourceVinsUpdate(ctx context.Context, d *schema.ResourceData, m interface } } - if oldRestart, newRestart := d.GetChange("vnfdev_restart"); oldRestart == false && newRestart == true { - req := vins.VNFDevRestartRequest{VINSID: vinsData.ID} + if d.HasChange("vnfdev_restart") { + if oldRestart, newRestart := d.GetChange("vnfdev_restart"); oldRestart == false && newRestart == true { + req := vins.VNFDevRestartRequest{VINSID: vinsData.ID} - _, err := c.CloudAPI().VINS().VNFDevRestart(ctx, req) - if err != nil { - warnings.Add(err) + _, err := c.CloudAPI().VINS().VNFDevRestart(ctx, req) + if err != nil { + warnings.Add(err) + } } } + if d.HasChange("vnfdev_redeploy") { + if oldRedeploy, newRedeploy := d.GetChange("vnfdev_redeploy"); oldRedeploy == false && newRedeploy == true { + req := vins.VNFDevRedeployRequest{VINSID: vinsData.ID} - if oldRedeploy, newRedeploy := d.GetChange("vnfdev_redeploy"); oldRedeploy == false && newRedeploy == true { - req := vins.VNFDevRedeployRequest{VINSID: vinsData.ID} - - _, err := c.CloudAPI().VINS().VNFDevRedeploy(ctx, req) - if err != nil { - warnings.Add(err) + _, err := c.CloudAPI().VINS().VNFDevRedeploy(ctx, req) + if err != nil { + warnings.Add(err) + } } } - - return append (warnings.Get(), resourceVinsRead(ctx, d, m)...) + return append(warnings.Get(), resourceVinsRead(ctx, d, m)...) } func resourceVinsDelete(ctx context.Context, d *schema.ResourceData, m interface{}) diag.Diagnostics { @@ -677,9 +683,9 @@ func extNetSchemaMake() map[string]*schema.Schema { func ipSchemaMake() map[string]*schema.Schema { return map[string]*schema.Schema{ "type": { - Type: schema.TypeString, - Required: true, - ValidateFunc: validation.StringInSlice([]string {"DHCP", "VIP", "EXCLUDE"}, false), + Type: schema.TypeString, + Required: true, + ValidateFunc: validation.StringInSlice([]string{"DHCP", "VIP", "EXCLUDE"}, false), }, "ip_addr": { Type: schema.TypeString, diff --git a/internal/service/cloudapi/vins/utility_vins.go b/internal/service/cloudapi/vins/utility_vins.go index 575d932..5e154f0 100644 --- a/internal/service/cloudapi/vins/utility_vins.go +++ b/internal/service/cloudapi/vins/utility_vins.go @@ -47,8 +47,8 @@ func utilityDataVinsCheckPresence(ctx context.Context, d *schema.ResourceData, m req := vins.GetRequest{} if d.Id() != "" { - rgId, _ := strconv.ParseUint(d.Id(), 10, 64) - req.VINSID = rgId + vinsId, _ := strconv.ParseUint(d.Id(), 10, 64) + req.VINSID = vinsId } else { req.VINSID = uint64(d.Get("vins_id").(int)) } @@ -60,4 +60,3 @@ func utilityDataVinsCheckPresence(ctx context.Context, d *schema.ResourceData, m return vins, nil } - diff --git a/internal/service/cloudapi/vins/utility_vins_audits.go b/internal/service/cloudapi/vins/utility_vins_audits.go index 15d9418..de3b801 100644 --- a/internal/service/cloudapi/vins/utility_vins_audits.go +++ b/internal/service/cloudapi/vins/utility_vins_audits.go @@ -46,8 +46,8 @@ func utilityVinsAuditsCheckPresence(ctx context.Context, d *schema.ResourceData, req := vins.AuditsRequest{} if d.Id() != "" { - rgId, _ := strconv.ParseUint(d.Id(), 10, 64) - req.VINSID = rgId + vinsId, _ := strconv.ParseUint(d.Id(), 10, 64) + req.VINSID = vinsId } else { req.VINSID = uint64(d.Get("vins_id").(int)) } diff --git a/internal/service/cloudapi/vins/utility_vins_ext_net_list.go b/internal/service/cloudapi/vins/utility_vins_ext_net_list.go index b57ce12..c6be583 100644 --- a/internal/service/cloudapi/vins/utility_vins_ext_net_list.go +++ b/internal/service/cloudapi/vins/utility_vins_ext_net_list.go @@ -48,8 +48,8 @@ func utilityVinsExtNetListCheckPresence(ctx context.Context, d *schema.ResourceD } if d.Id() != "" { - rgId, _ := strconv.ParseUint(d.Id(), 10, 64) - req.VINSID = rgId + vinsId, _ := strconv.ParseUint(d.Id(), 10, 64) + req.VINSID = vinsId } else { req.VINSID = uint64(d.Get("vins_id").(int)) } diff --git a/internal/service/cloudapi/vins/utility_vins_ip_list.go b/internal/service/cloudapi/vins/utility_vins_ip_list.go index 997c8ad..b0e5edb 100644 --- a/internal/service/cloudapi/vins/utility_vins_ip_list.go +++ b/internal/service/cloudapi/vins/utility_vins_ip_list.go @@ -46,8 +46,8 @@ func utilityVinsIpListCheckPresence(ctx context.Context, d *schema.ResourceData, req := vins.IPListRequest{} if d.Id() != "" { - rgId, _ := strconv.ParseUint(d.Id(), 10, 64) - req.VINSID = rgId + vinsId, _ := strconv.ParseUint(d.Id(), 10, 64) + req.VINSID = vinsId } else { req.VINSID = uint64(d.Get("vins_id").(int)) } diff --git a/internal/service/cloudapi/vins/utility_vins_nat_rule_list.go b/internal/service/cloudapi/vins/utility_vins_nat_rule_list.go index 5027591..c07014c 100644 --- a/internal/service/cloudapi/vins/utility_vins_nat_rule_list.go +++ b/internal/service/cloudapi/vins/utility_vins_nat_rule_list.go @@ -46,8 +46,8 @@ func utilityVinsNatRuleListCheckPresence(ctx context.Context, d *schema.Resource req := vins.NATRuleListRequest{} if d.Id() != "" { - rgId, _ := strconv.ParseUint(d.Id(), 10, 64) - req.VINSID = rgId + vinsId, _ := strconv.ParseUint(d.Id(), 10, 64) + req.VINSID = vinsId } else { req.VINSID = uint64(d.Get("vins_id").(int)) } diff --git a/internal/service/cloudbroker/kvmvm/utility_compute.go b/internal/service/cloudbroker/kvmvm/utility_compute.go index 256db47..5319de0 100644 --- a/internal/service/cloudbroker/kvmvm/utility_compute.go +++ b/internal/service/cloudbroker/kvmvm/utility_compute.go @@ -444,17 +444,6 @@ func utilityComputeNetworksConfigure(ctx context.Context, d *schema.ResourceData old_set, new_set := d.GetChange("network") - req := compute.StopRequest{ - ComputeID: computeID, - Force: true, - } - - log.Debugf("utilityComputeNetworksConfigure: stopping compute %d", computeID) - _, err := c.CloudBroker().Compute().Stop(ctx, req) - if err != nil { - return err - } - apiErrCount := 0 var lastSavedError error @@ -514,6 +503,17 @@ func utilityComputeNetworksConfigure(ctx context.Context, d *schema.ResourceData } } + needStart := false + + if d.Get("network").(*schema.Set).Len() == 1 || old_set.(*schema.Set).Len() < 1 { + computeId, _ := strconv.ParseUint(d.Id(), 10, 64) + if err := utilityComputeStop(ctx, computeId, m); err != nil { + apiErrCount++ + lastSavedError = err + } + needStart = true + } + 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() { @@ -538,13 +538,12 @@ func utilityComputeNetworksConfigure(ctx context.Context, d *schema.ResourceData } } - startReq := compute.StartRequest{ComputeID: computeID} - - log.Debugf("utilityComputeNetworksConfigure: starting compute %d", computeID) - _, err = c.CloudBroker().Compute().Start(ctx, startReq) - if err != nil { - apiErrCount++ - lastSavedError = err + if needStart { + computeId, _ := strconv.ParseUint(d.Id(), 10, 64) + if numErr, err := utilityComputeStart(ctx, computeId, m); err != nil { + apiErrCount += numErr + lastSavedError = err + } } if apiErrCount > 0 { @@ -1195,20 +1194,46 @@ func utilityComputeUpdateCustomFields(ctx context.Context, d *schema.ResourceDat if err != nil { return err } + } else { + req := compute.DeleteCustomFieldsRequest{ + ComputeID: computeId, + } + + _, err := c.CloudBroker().Compute().DeleteCustomFields(ctx, req) + if err != nil { + return err + } + } + return nil +} + +func utilityComputeStop(ctx context.Context, computeID uint64, m interface{}) error { + c := m.(*controller.ControllerCfg) + req := compute.StopRequest{ + ComputeID: computeID, + Force: true, } - // } else { - // // req := compute.DeleteCustomFieldsRequest{ - // // ComputeID: computeId, - // // } - // // _, err := c.CloudBroker().Compute().DeleteCustomFields(ctx, req) - // // if err != nil { - // // return err - // // } - // } + log.Debugf("utilityComputeNetworksConfigure: stopping compute %d", computeID) + _, err := c.CloudBroker().Compute().Stop(ctx, req) + if err != nil { + return err + } return nil } +func utilityComputeStart(ctx context.Context, computeID uint64, m interface{}) (int, error) { + c := m.(*controller.ControllerCfg) + startReq := compute.StartRequest{ComputeID: computeID} + + log.Debugf("utilityComputeNetworksConfigure: starting compute %d", computeID) + _, err := c.CloudBroker().Compute().Start(ctx, startReq) + if err != nil { + return 1, err + } + return 0, nil +} + func isChangeDisk(els []interface{}, el interface{}) bool { for _, elOld := range els { elOldConv := elOld.(map[string]interface{}) diff --git a/samples/cloudapi/data_account_consumed_units_by_type/main.tf b/samples/cloudapi/data_account_consumed_units_by_type/main.tf index 026885f..bcaf56e 100644 --- a/samples/cloudapi/data_account_consumed_units_by_type/main.tf +++ b/samples/cloudapi/data_account_consumed_units_by_type/main.tf @@ -40,13 +40,12 @@ data "decort_account_consumed_units_by_type" "acubt" { #обязательный параметр #тип - строка #значения: - #cu_c - кол-во виртуальных cpu ядер - #cu_m - кол-во RAM в МБ - #cu_d - кол-в используемой дисковой памяти, в ГБ - #cu_i - кол-во публичных ip адресов - #cu_np - кол-во полученного/отданного трафика, в ГБ - #gpu_units - кол-во gpu ядер - cu_type = "cu_с" + #CU_C - кол-во виртуальных cpu ядер + #CU_M - кол-во RAM в МБ + #CU_D - кол-в используемой дисковой памяти, в ГБ + #CU_I - кол-во публичных ip адресов + #CU_NP - кол-во полученного/отданного трафика, в ГБ + cu_type = "CU_C" } output "test" { diff --git a/samples/cloudapi/data_disk_list_types/main.tf b/samples/cloudapi/data_disk_list_types/main.tf index a7c160a..7c5e6f1 100644 --- a/samples/cloudapi/data_disk_list_types/main.tf +++ b/samples/cloudapi/data_disk_list_types/main.tf @@ -27,12 +27,6 @@ provider "decort" { } data "decort_disk_list_types" "dlt" { - #Нет входных параметров - - #Выходной параметр - #тип - лист строк - #types {} - #номер страницы для отображения #опциональный параметр #тип - число diff --git a/samples/cloudapi/data_disk_list_types_detailed/main.tf b/samples/cloudapi/data_disk_list_types_detailed/main.tf index 47b9d75..4f52de7 100644 --- a/samples/cloudapi/data_disk_list_types_detailed/main.tf +++ b/samples/cloudapi/data_disk_list_types_detailed/main.tf @@ -28,24 +28,6 @@ provider "decort" { data "decort_disk_list_types_detailed" "dltd" { - #Нет входных параметров - - #Выходной параметр - #тип - лист типов - # items {} - - #Выходной параметр - #Список пулов - # pools - - #Выходной параметр - #Имя - # name - - #Выходной параметр - #Список типов - #types - #номер страницы для отображения #опциональный параметр #тип - число diff --git a/samples/cloudapi/data_k8s_wg/main.tf b/samples/cloudapi/data_k8s_wg/main.tf index c08877f..950e0be 100644 --- a/samples/cloudapi/data_k8s_wg/main.tf +++ b/samples/cloudapi/data_k8s_wg/main.tf @@ -38,5 +38,5 @@ data "decort_k8s_wg" "k8s_wg" { } output "output_k8s_wg" { - value = data.decort_k8s.k8s + value = data.decort_k8s_wg.k8s_wg } diff --git a/samples/cloudapi/data_kvmvm/main.tf b/samples/cloudapi/data_kvmvm/main.tf index 603086c..36b3112 100644 --- a/samples/cloudapi/data_kvmvm/main.tf +++ b/samples/cloudapi/data_kvmvm/main.tf @@ -1,6 +1,6 @@ /* Пример использования -Получение данных о compute (виртулаьной машине) +Получение данных о compute (виртуальной машине) */ #Расскомментируйте этот код, #и внесите необходимые правки в версию и путь, diff --git a/samples/cloudapi/data_kvmvm_audits/main.tf b/samples/cloudapi/data_kvmvm_audits/main.tf index 45f8ec6..0ad21a8 100644 --- a/samples/cloudapi/data_kvmvm_audits/main.tf +++ b/samples/cloudapi/data_kvmvm_audits/main.tf @@ -1,6 +1,6 @@ /* Пример использования -Получение данных об аудитах compute (виртулаьной машине) +Получение данных об аудитах compute (виртуальной машине) */ #Расскомментируйте этот код, #и внесите необходимые правки в версию и путь, diff --git a/samples/cloudapi/data_kvmvm_get_audits/main.tf b/samples/cloudapi/data_kvmvm_get_audits/main.tf index c2ec8ec..0c01b89 100644 --- a/samples/cloudapi/data_kvmvm_get_audits/main.tf +++ b/samples/cloudapi/data_kvmvm_get_audits/main.tf @@ -1,6 +1,6 @@ /* Пример использования -Получение данных об аудитах compute (виртулаьной машине) +Получение данных об аудитах compute (виртуальной машине) */ #Расскомментируйте этот код, #и внесите необходимые правки в версию и путь, diff --git a/samples/cloudapi/data_kvmvm_get_console_url/main.tf b/samples/cloudapi/data_kvmvm_get_console_url/main.tf index 81d3b93..1009ebc 100644 --- a/samples/cloudapi/data_kvmvm_get_console_url/main.tf +++ b/samples/cloudapi/data_kvmvm_get_console_url/main.tf @@ -1,6 +1,6 @@ /* Пример использования -Получение url compute (виртулаьной машины) +Получение url compute (виртуальной машины) */ #Расскомментируйте этот код, #и внесите необходимые правки в версию и путь, diff --git a/samples/cloudapi/data_kvmvm_get_log/main.tf b/samples/cloudapi/data_kvmvm_get_log/main.tf index 2858b5f..15ae92c 100644 --- a/samples/cloudapi/data_kvmvm_get_log/main.tf +++ b/samples/cloudapi/data_kvmvm_get_log/main.tf @@ -1,6 +1,6 @@ /* Пример использования -Получение логов compute (виртулаьной машины) +Получение логов compute (виртуальной машины) */ #Расскомментируйте этот код, #и внесите необходимые правки в версию и путь, diff --git a/samples/cloudapi/data_kvmvm_list/main.tf b/samples/cloudapi/data_kvmvm_list/main.tf index 25926e1..b3d52be 100644 --- a/samples/cloudapi/data_kvmvm_list/main.tf +++ b/samples/cloudapi/data_kvmvm_list/main.tf @@ -1,6 +1,6 @@ /* Пример использования -Получение данных об списке compute (виртулаьных машин) +Получение данных об списке compute (виртуальных машин) */ #Расскомментируйте этот код, #и внесите необходимые правки в версию и путь, diff --git a/samples/cloudapi/data_kvmvm_pfw_list/main.tf b/samples/cloudapi/data_kvmvm_pfw_list/main.tf index b3cd17f..d03ebd1 100644 --- a/samples/cloudapi/data_kvmvm_pfw_list/main.tf +++ b/samples/cloudapi/data_kvmvm_pfw_list/main.tf @@ -1,6 +1,6 @@ /* Пример использования -Получение данных об списке port forwarding compute (виртулаьных машин) +Получение данных об списке port forwarding compute (виртуальных машин) */ #Расскомментируйте этот код, #и внесите необходимые правки в версию и путь, diff --git a/samples/cloudapi/data_kvmvm_user_list/main.tf b/samples/cloudapi/data_kvmvm_user_list/main.tf index 02723c1..ea1cec7 100644 --- a/samples/cloudapi/data_kvmvm_user_list/main.tf +++ b/samples/cloudapi/data_kvmvm_user_list/main.tf @@ -1,6 +1,6 @@ /* Пример использования -Получение данных об юзерах compute (виртулаьной машины) +Получение данных об юзерах compute (виртуальной машины) */ #Расскомментируйте этот код, #и внесите необходимые правки в версию и путь, diff --git a/samples/cloudapi/resource_account/main.tf b/samples/cloudapi/resource_account/main.tf index 9580a38..9a65271 100644 --- a/samples/cloudapi/resource_account/main.tf +++ b/samples/cloudapi/resource_account/main.tf @@ -53,12 +53,6 @@ resource "decort_account" "a" { #тип - число account_id = 11111 - #электронная почта, на которую будет отправлена информация о доступе - #необязательный параметр - #тип - строка - #применяется при создании аккаунта - emailaddress = "fff@fff.ff" - #отправлять ли на электронную почту письмо о доступе #необязательный параметр #тип - булев тип diff --git a/samples/cloudapi/resource_bservice/main.tf b/samples/cloudapi/resource_bservice/main.tf index f1585c6..c47189e 100644 --- a/samples/cloudapi/resource_bservice/main.tf +++ b/samples/cloudapi/resource_bservice/main.tf @@ -69,9 +69,6 @@ resource "decort_bservice" "b" { #по-умолчанию - false #восстановление происходит только при переключении с false на true rollback = false - } - snapshots { - label = "test_snapshot_1" } */ diff --git a/samples/cloudapi/resource_image/main.tf b/samples/cloudapi/resource_image/main.tf index d01cb97..eb5e555 100644 --- a/samples/cloudapi/resource_image/main.tf +++ b/samples/cloudapi/resource_image/main.tf @@ -96,6 +96,11 @@ resource "decort_image" "img" { # Опциональный параметр # string architecture = "PPC64_LE" + + # Флаг окончательного удаления + # Опциональный параметр + # булев тип + permanently = true } output "img_out" { diff --git a/samples/cloudapi/resource_image_virtual/main.tf b/samples/cloudapi/resource_image_virtual/main.tf index bc9e8c7..c001e58 100644 --- a/samples/cloudapi/resource_image_virtual/main.tf +++ b/samples/cloudapi/resource_image_virtual/main.tf @@ -1,13 +1,11 @@ /* Пример использования -Ресурса vins static routes +Ресурса image virtual Ресурс позволяет: -1. Создавать static routes -2. Удалять static routes -3. Получать информацию о всех static routes в данном Vins -4. Предоставлять доступ виртуальным машинам к static routes -5. Удалять доступ виртуальным машинам к static routes - +1. Создавать image virtual +2. Удалять image virtual +3. Переименовывать image virtual +4. Привязывать image virtual к другому образу */ #Расскомментируйте этот код, @@ -49,7 +47,7 @@ resource "decort_image_virtual" "iv" { #Флаг для удаления диска #опциональный параметр #тип - bool - #permanently = false + permanently = false } output "sr" { diff --git a/samples/cloudapi/resource_k8s/main.tf b/samples/cloudapi/resource_k8s/main.tf index dc5f826..74df529 100644 --- a/samples/cloudapi/resource_k8s/main.tf +++ b/samples/cloudapi/resource_k8s/main.tf @@ -63,7 +63,7 @@ resource "decort_k8s" "cluster" { # опциональный параметр # В скором времени параметры labels, annotations, taints будут полностью перенесены в блок workers # тип - массив строк - taints = ["key1=val1", "key2=val2"] + taints = ["key1=value1:NoSchedule", "key2=value2:NoExecute"] #настройка мастер node или nodes #опциональный параметр @@ -278,6 +278,10 @@ resource "decort_k8s" "cluster" { # тип - файл oidc_cert = file("ca.crt") + # запуск,остановка кластера + # опциональный параметр + # тип - булев тип + start = true } output "test_cluster" { diff --git a/samples/cloudapi/resource_kvmvm/main.tf b/samples/cloudapi/resource_kvmvm/main.tf index 5b0d227..8626d4d 100644 --- a/samples/cloudapi/resource_kvmvm/main.tf +++ b/samples/cloudapi/resource_kvmvm/main.tf @@ -352,6 +352,11 @@ resource "decort_kvmvm" "comp" { #тип - булев reset = true + #восстановить компьют из корзины + #опциональный параметр + #тип - булев + restore = true + #флаг для редеплоя компьюта #опциональный параметр #тип - булев diff --git a/samples/cloudapi/resource_rg/main.tf b/samples/cloudapi/resource_rg/main.tf index 4da35be..00a3d1d 100644 --- a/samples/cloudapi/resource_rg/main.tf +++ b/samples/cloudapi/resource_rg/main.tf @@ -82,6 +82,11 @@ resource "decort_resgroup" "rg" { #тип - булевый enable = true + #имя пользователя + #необязательный параметр + #тип - строка + owner = "name_user" + #блок для предоставления прав на ресурсную группу #необязательный параметр #тип - блок @@ -160,6 +165,12 @@ resource "decort_resgroup" "rg" { #тип - булевый permanently = true + #восстановление группы после удаления + #необязательный параметр + #тип - булев тип + #используется при редактировании ресурса + #по-умолачанию - false + restore = true }