Skip to content

Commit

Permalink
Merge pull request #79 from volcengine/feat/suooprt_project_change
Browse files Browse the repository at this point in the history
Feat/suooprt project change
  • Loading branch information
xuyaming0800 authored Mar 31, 2023
2 parents 76b42c8 + d4950a8 commit da4e19a
Show file tree
Hide file tree
Showing 29 changed files with 203 additions and 221 deletions.
10 changes: 9 additions & 1 deletion common/common_volcengine_callback.go
Original file line number Diff line number Diff line change
Expand Up @@ -33,6 +33,9 @@ type SdkCall struct {
LockId LockId
AfterLocked CallFunc
ServiceCategory ServiceCategory

//common inner use
refreshState func(*schema.ResourceData, []string, time.Duration, string) *resource.StateChangeConf
}

type StateRefresh struct {
Expand Down Expand Up @@ -215,7 +218,12 @@ func CallProcess(calls []SdkCall, d *schema.ResourceData, client *SdkClient, ser

// WaitForState
if doExecute && fn.Refresh != nil && err == nil {
stateConf := service.RefreshResourceState(d, fn.Refresh.Target, fn.Refresh.Timeout, d.Id())
var stateConf *resource.StateChangeConf
if fn.refreshState != nil {
stateConf = fn.refreshState(d, fn.Refresh.Target, fn.Refresh.Timeout, d.Id())
} else {
stateConf = service.RefreshResourceState(d, fn.Refresh.Target, fn.Refresh.Timeout, d.Id())
}
if stateConf != nil {
_, err = stateConf.WaitForState()
}
Expand Down
9 changes: 8 additions & 1 deletion common/common_volcengine_dispatcher.go
Original file line number Diff line number Diff line change
Expand Up @@ -98,7 +98,14 @@ func (d *Dispatcher) Update(resourceService ResourceService, resourceDate *schem
}
}
}
callbacks := resourceService.ModifyResource(resourceDate, resource)
var callbacks []Callback
if projectUpdateEnabled, ok := resourceService.(ProjectUpdateEnabled); ok {
projectUpdateCallback := NewProjectService(resourceService.GetClient()).ModifyProject(projectUpdateEnabled.ProjectTrn(),
resourceDate, resource, resourceService)
callbacks = append(callbacks, projectUpdateCallback...)
}
callbacks = append(callbacks, resourceService.ModifyResource(resourceDate, resource)...)

var calls []SdkCall
for _, callback := range callbacks {
if callback.Err != nil {
Expand Down
92 changes: 88 additions & 4 deletions common/common_volcengine_project.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,19 +2,27 @@ package common

import (
"fmt"
"time"

"github.com/hashicorp/terraform-plugin-sdk/helper/resource"
"github.com/hashicorp/terraform-plugin-sdk/helper/schema"
"github.com/volcengine/terraform-provider-volcengine/logger"
)

type ProjectUpdateEnabled interface {
ProjectTrn() *ProjectTrn
}

type Project struct {
Client *SdkClient
}

type ProjectTrn struct {
ResourceType string
ResourceID string
ServiceName string
ResourceType string
ResourceID string
ServiceName string
ProjectSchemaField string
ProjectResponseField string
}

func NewProjectService(c *SdkClient) *Project {
Expand All @@ -23,7 +31,83 @@ func NewProjectService(c *SdkClient) *Project {
}
}

func (p *Project) ModifyProject(trn ProjectTrn, resourceData *schema.ResourceData, resource *schema.Resource, key string, sr *StateRefresh) []Callback {
func (p *Project) ModifyProject(trn *ProjectTrn, resourceData *schema.ResourceData, r *schema.Resource, service ResourceService) []Callback {
var call []Callback
id := service.ReadResourceId(resourceData.Id())
if resourceData.HasChange(trn.ProjectSchemaField) {
modifyProject := Callback{
Call: SdkCall{
Action: "MoveProjectResource",
ConvertMode: RequestConvertInConvert,
Convert: map[string]RequestConvert{
trn.ProjectSchemaField: {
ConvertType: ConvertDefault,
TargetField: "TargetProjectName",
},
},
BeforeCall: func(d *schema.ResourceData, client *SdkClient, call SdkCall) (bool, error) {
if (*call.SdkParam)["TargetProjectName"] == nil || (*call.SdkParam)["TargetProjectName"] == "" {
return false, fmt.Errorf("Could set ProjectName to empty ")
}
//获取用户ID
input := map[string]interface{}{
"ProjectName": (*call.SdkParam)["TargetProjectName"],
}
logger.Debug(logger.ReqFormat, "GetProject", input)
out, err := p.Client.UniversalClient.DoCall(p.getUniversalInfo("GetProject"), &input)
if err != nil {
return false, err
}
accountId, err := ObtainSdkValue("Result.AccountID", *out)
if err != nil {
return false, err
}
trnStr := fmt.Sprintf("trn:%s:%s:%d:%s/%s", trn.ServiceName, p.Client.Region, int(accountId.(float64)),
trn.ResourceType, id)
(*call.SdkParam)["ResourceTrn.1"] = trnStr
return true, nil
},
ExecuteCall: func(d *schema.ResourceData, client *SdkClient, call SdkCall) (*map[string]interface{}, error) {
logger.Debug(logger.ReqFormat, call.Action, call.SdkParam)
return p.Client.UniversalClient.DoCall(p.getUniversalInfo(call.Action), call.SdkParam)
},
Refresh: &StateRefresh{
Target: []string{resourceData.Get(trn.ProjectSchemaField).(string)},
Timeout: resourceData.Timeout(schema.TimeoutCreate),
},
refreshState: func(data *schema.ResourceData, target []string, timeout time.Duration, id string) *resource.StateChangeConf {
return &resource.StateChangeConf{
Pending: []string{},
Delay: 1 * time.Second,
MinTimeout: 1 * time.Second,
Target: target,
Timeout: timeout,
Refresh: func() (result interface{}, state string, err error) {
var (
d map[string]interface{}
name interface{}
)
d, err = service.ReadResource(resourceData, service.ReadResourceId(id))
if err != nil {
return nil, "", err
}
name, err = ObtainSdkValue(trn.ProjectResponseField, d)
if err != nil {
return nil, "", err
}

return d, name.(string), err
},
}
},
},
}
call = append(call, modifyProject)
}
return call
}

func (p *Project) ModifyProjectOld(trn ProjectTrn, resourceData *schema.ResourceData, resource *schema.Resource, key string, sr *StateRefresh) []Callback {
var call []Callback
if resourceData.HasChange(key) {
modifyProject := Callback{
Expand Down
2 changes: 1 addition & 1 deletion common/common_volcengine_version.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,5 +2,5 @@ package common

const (
TerraformProviderName = "terraform-provider-volcengine"
TerraformProviderVersion = "0.0.64"
TerraformProviderVersion = "0.0.65"
)
7 changes: 5 additions & 2 deletions example/crTag/main.tf
Original file line number Diff line number Diff line change
@@ -1,4 +1,7 @@
# Tag cannot be created,please import by command `terraform import volcengine_cr_tag.default registry:namespace:repository:tag`
resource "volcengine_cr_tags" "default"{

resource "volcengine_cr_tag" "default" {
registry = "enterprise-1"
namespace = "langyu"
repository = "repo"
name = "v2"
}
5 changes: 5 additions & 0 deletions example/mongoDBInstance/main.tf
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,11 @@ resource "volcengine_mongodb_instance" "foo"{
instance_name="mongo-replica-be9995d32e4a"
charge_type="PostPaid"
super_account_password = "******"
project_name = "default"
tags {
key = "k1"
value = "v1"
}
# period_unit="Month"
# period=1
# auto_renew=false
Expand Down
2 changes: 1 addition & 1 deletion volcengine/clb/clb/service_volcengine_clb.go
Original file line number Diff line number Diff line change
Expand Up @@ -218,7 +218,7 @@ func (s *VolcengineClbService) ModifyResource(resourceData *schema.ResourceData,
var callbacks []ve.Callback

//project
projectCallback := ve.NewProjectService(s.Client).ModifyProject(ve.ProjectTrn{
projectCallback := ve.NewProjectService(s.Client).ModifyProjectOld(ve.ProjectTrn{
ResourceType: "clb",
ResourceID: resourceData.Id(),
ServiceName: "clb",
Expand Down
13 changes: 2 additions & 11 deletions volcengine/cr/cr_namespace/resource_volcengine_cr_namespace.go
Original file line number Diff line number Diff line change
Expand Up @@ -37,25 +37,25 @@ func ResourceVolcengineCrNamespace() *schema.Resource {
resource := &schema.Resource{
Create: resourceVolcengineCrNamespaceCreate,
Read: resourceVolcengineCrNamespaceRead,
Update: resourceVolcengineCrNamespaceUpdate,
Delete: resourceVolcengineCrNamespaceDelete,
Importer: &schema.ResourceImporter{
State: crNamespaceImporter,
},
Timeouts: &schema.ResourceTimeout{
Create: schema.DefaultTimeout(30 * time.Minute),
Update: schema.DefaultTimeout(30 * time.Minute),
Delete: schema.DefaultTimeout(30 * time.Minute),
},
Schema: map[string]*schema.Schema{
"registry": {
Type: schema.TypeString,
Required: true,
ForceNew: true,
Description: "The registry name.",
},
"name": {
Type: schema.TypeString,
Required: true,
ForceNew: true,
Description: "The name of CrNamespace.",
},
},
Expand All @@ -74,15 +74,6 @@ func resourceVolcengineCrNamespaceCreate(d *schema.ResourceData, meta interface{
return resourceVolcengineCrNamespaceRead(d, meta)
}

func resourceVolcengineCrNamespaceUpdate(d *schema.ResourceData, meta interface{}) (err error) {
service := NewCrNamespaceService(meta.(*ve.SdkClient))
err = ve.DefaultDispatcher().Update(service, d, ResourceVolcengineCrNamespace())
if err != nil {
return fmt.Errorf("error on updating CrNamespace %q, %s", d.Id(), err)
}
return resourceVolcengineCrNamespaceRead(d, meta)
}

func resourceVolcengineCrNamespaceDelete(d *schema.ResourceData, meta interface{}) (err error) {
service := NewCrNamespaceService(meta.(*ve.SdkClient))
err = ve.DefaultDispatcher().Delete(service, d, ResourceVolcengineCrNamespace())
Expand Down
3 changes: 2 additions & 1 deletion volcengine/cr/cr_registry/resource_volcengine_cr_registry.go
Original file line number Diff line number Diff line change
Expand Up @@ -36,13 +36,14 @@ func ResourceVolcengineCrRegistry() *schema.Resource {
"name": {
Type: schema.TypeString,
Required: true,
ForceNew: true,
Description: "The name of registry.",
},
"delete_immediately": {
Type: schema.TypeBool,
Optional: true,
Default: false,
Description: "Whether delete registry immediately.",
Description: "Whether delete registry immediately. Only effected in delete action.",
},
"password": {
Type: schema.TypeString,
Expand Down
45 changes: 8 additions & 37 deletions volcengine/cr/cr_registry/service_volcengine_cr_registry.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,9 +4,10 @@ import (
"encoding/base64"
"errors"
"fmt"
"github.com/google/uuid"
"time"

"github.com/google/uuid"

"github.com/hashicorp/terraform-plugin-sdk/helper/resource"
"github.com/hashicorp/terraform-plugin-sdk/helper/schema"
ve "github.com/volcengine/terraform-provider-volcengine/common"
Expand Down Expand Up @@ -151,14 +152,6 @@ func (s *VolcengineCrRegistryService) ReadResource(resourceData *schema.Resource
if len(data) == 0 {
return data, fmt.Errorf("CrRegistry %s is not exist", id)
}

deleteImmediately := resourceData.Get("delete_immediately")
if deleteImmediately == nil {
data["DeleteImmediately"] = false
} else {
data["DeleteImmediately"] = deleteImmediately
}

return data, err
}

Expand Down Expand Up @@ -238,20 +231,10 @@ func (s *VolcengineCrRegistryService) CreateResource(resourceData *schema.Resour
callback := ve.Callback{
Call: ve.SdkCall{
Action: action,
ConvertMode: ve.RequestConvertAll,
ConvertMode: ve.RequestConvertIgnore,
BeforeCall: func(d *schema.ResourceData, client *ve.SdkClient, call ve.SdkCall) (bool, error) {
registry := resourceData.Id()
password := password.(string)

if password == "" {
return false, nil
}

bytes := []byte(password)
passwdBase64 := base64.StdEncoding.EncodeToString(bytes)

(*call.SdkParam)["Registry"] = registry
(*call.SdkParam)["Password"] = passwdBase64
(*call.SdkParam)["Registry"] = resourceData.Get("name")
(*call.SdkParam)["Password"] = base64.StdEncoding.EncodeToString([]byte(password.(string)))
return true, nil
},
ExecuteCall: func(d *schema.ResourceData, client *ve.SdkClient, call ve.SdkCall) (*map[string]interface{}, error) {
Expand All @@ -274,18 +257,9 @@ func (s *VolcengineCrRegistryService) ModifyResource(resourceData *schema.Resour
Action: action,
ConvertMode: ve.RequestConvertIgnore,
BeforeCall: func(d *schema.ResourceData, client *ve.SdkClient, call ve.SdkCall) (bool, error) {
registry := resourceData.Id()
password := resourceData.Get("password").(string)

if password == "" {
return false, nil
}

bytes := []byte(password)
passwdBase64 := base64.StdEncoding.EncodeToString(bytes)

(*call.SdkParam)["Registry"] = registry
(*call.SdkParam)["Password"] = passwdBase64
bytes := []byte(resourceData.Get("password").(string))
(*call.SdkParam)["Registry"] = resourceData.Get("name")
(*call.SdkParam)["Password"] = base64.StdEncoding.EncodeToString(bytes)
return true, nil
},
ExecuteCall: func(d *schema.ResourceData, client *ve.SdkClient, call ve.SdkCall) (*map[string]interface{}, error) {
Expand All @@ -296,9 +270,6 @@ func (s *VolcengineCrRegistryService) ModifyResource(resourceData *schema.Resour
}
callbacks = append(callbacks, callback)
}
if resourceData.HasChange("delete_immediately") {
resourceData.Set("delete_immediately", resourceData.Get("delete_immediately"))
}
return callbacks
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -33,16 +33,15 @@ func crRegistryStateImporter(d *schema.ResourceData, m interface{}) ([]*schema.R

func ResourceVolcengineCrRegistryState() *schema.Resource {
return &schema.Resource{
Delete: resourceVolcengineCrRegistryStateDelete,
Create: resourceVolcengineCrRegistryStateCreate,
Read: resourceVolcengineCrRegistryStateRead,
Update: resourceVolcengineCrRegistryStateUpdate,
Read: resourceVolcengineCrRegistryStateRead,
Delete: resourceVolcengineCrRegistryStateDelete,
Importer: &schema.ResourceImporter{
State: crRegistryStateImporter,
},
Timeouts: &schema.ResourceTimeout{
Create: schema.DefaultTimeout(1 * time.Hour),
Update: schema.DefaultTimeout(1 * time.Hour),
Delete: schema.DefaultTimeout(1 * time.Hour),
},
Schema: map[string]*schema.Schema{
Expand All @@ -58,6 +57,7 @@ func ResourceVolcengineCrRegistryState() *schema.Resource {
"name": {
Type: schema.TypeString,
Required: true,
ForceNew: true,
Description: "The cr instance id.",
},
"status": {
Expand Down Expand Up @@ -95,6 +95,10 @@ func resourceVolcengineCrRegistryStateCreate(d *schema.ResourceData, meta interf
return resourceVolcengineCrRegistryStateRead(d, meta)
}

func resourceVolcengineCrRegistryStateUpdate(d *schema.ResourceData, meta interface{}) error {
return fmt.Errorf("this resource does not allow update operation")
}

func resourceVolcengineCrRegistryStateRead(d *schema.ResourceData, meta interface{}) error {
service := NewCrRegistryStateService(meta.(*ve.SdkClient))
if err := ve.DefaultDispatcher().Read(service, d, ResourceVolcengineCrRegistryState()); err != nil {
Expand All @@ -103,14 +107,6 @@ func resourceVolcengineCrRegistryStateRead(d *schema.ResourceData, meta interfac
return nil
}

func resourceVolcengineCrRegistryStateUpdate(d *schema.ResourceData, meta interface{}) error {
service := NewCrRegistryStateService(meta.(*ve.SdkClient))
if err := ve.DefaultDispatcher().Update(service, d, ResourceVolcengineCrRegistryState()); err != nil {
return fmt.Errorf("error on updating instance state %q, %w", d.Id(), err)
}
return resourceVolcengineCrRegistryStateRead(d, meta)
}

func resourceVolcengineCrRegistryStateDelete(d *schema.ResourceData, meta interface{}) error {
service := NewCrRegistryStateService(meta.(*ve.SdkClient))
if err := ve.DefaultDispatcher().Delete(service, d, ResourceVolcengineCrRegistryState()); err != nil {
Expand Down
Loading

0 comments on commit da4e19a

Please sign in to comment.