fix(region): disk update tag (#23026)

This commit is contained in:
屈轩
2025-08-06 15:52:17 +08:00
committed by GitHub
parent 4d45708d11
commit 9a5b906d10
21 changed files with 353 additions and 49 deletions
+2 -2
View File
@@ -87,12 +87,12 @@ require (
k8s.io/client-go v0.19.3
k8s.io/cluster-bootstrap v0.19.3
moul.io/http2curl/v2 v2.3.0
yunion.io/x/cloudmux v0.3.10-0-alpha.1.0.20250721091657-0b9a131cbdfe
yunion.io/x/cloudmux v0.3.10-0-alpha.1.0.20250806071154-376c8716aafd
yunion.io/x/executor v0.0.0-20250518005516-5402e9e0bed0
yunion.io/x/jsonutils v1.0.1-0.20250507052344-1abcf4f443b1
yunion.io/x/log v1.0.1-0.20240305175729-7cf2d6cd5a91
yunion.io/x/ovsdb v0.0.0-20230306173834-f164f413a900
yunion.io/x/pkg v1.10.4-0.20250715170922-d5b8a92716b6
yunion.io/x/pkg v1.10.4-0.20250805171825-2431e10f90a9
yunion.io/x/s3cli v0.0.0-20241221171442-1c11599d28e1
yunion.io/x/sqlchemy v1.1.3-0.20250531010554-ce98f840b833
yunion.io/x/structarg v0.0.0-20231017124457-df4d5009457c
+4 -4
View File
@@ -1270,8 +1270,8 @@ sigs.k8s.io/structured-merge-diff/v4 v4.0.1/go.mod h1:bJZC9H9iH24zzfZ/41RGcq60oK
sigs.k8s.io/yaml v1.1.0/go.mod h1:UJmg0vDUVViEyp3mgSv9WPwZCDxu4rQW1olrI1uml+o=
sigs.k8s.io/yaml v1.2.0 h1:kr/MCeFWJWTwyaHoR9c8EjH9OumOmoF9YGiZd7lFm/Q=
sigs.k8s.io/yaml v1.2.0/go.mod h1:yfXDCHCao9+ENCvLSE62v9VSji2MKu5jeNfTrofGhJc=
yunion.io/x/cloudmux v0.3.10-0-alpha.1.0.20250721091657-0b9a131cbdfe h1:8PrHbl+AqTdN+yj84MO/7RMZ9mKzwqBNVptls8HyNRs=
yunion.io/x/cloudmux v0.3.10-0-alpha.1.0.20250721091657-0b9a131cbdfe/go.mod h1:FXxAEbdNfWXX9gjME3K2nJhkydHY5EKEUZb+RLEzVwQ=
yunion.io/x/cloudmux v0.3.10-0-alpha.1.0.20250806071154-376c8716aafd h1:nIOCPteVEdSJ6Agx3az+hJlfy4QryZQsSZ8Rjb7d5Eg=
yunion.io/x/cloudmux v0.3.10-0-alpha.1.0.20250806071154-376c8716aafd/go.mod h1:FXxAEbdNfWXX9gjME3K2nJhkydHY5EKEUZb+RLEzVwQ=
yunion.io/x/executor v0.0.0-20250518005516-5402e9e0bed0 h1:msG4SiDSVU7CrXH06WuHlNEZXIooTcmNbfrIGHuIHBU=
yunion.io/x/executor v0.0.0-20250518005516-5402e9e0bed0/go.mod h1:Uxuou9WQIeJXNpy7t2fPLL0BYLvLiMvGQwY7Qc6aSws=
yunion.io/x/jsonutils v0.0.0-20190625054549-a964e1e8a051/go.mod h1:4N0/RVzsYL3kH3WE/H1BjUQdFiWu50JGCFQuuy+Z634=
@@ -1285,8 +1285,8 @@ yunion.io/x/ovsdb v0.0.0-20230306173834-f164f413a900 h1:Hu/4ERvoWaN6aiFs4h4/yvVB
yunion.io/x/ovsdb v0.0.0-20230306173834-f164f413a900/go.mod h1:0vLkNEhlmA64HViPBAnSTUMrx5QP1CLsxXmxDKQ80tc=
yunion.io/x/pkg v0.0.0-20190620104149-945c25821dbf/go.mod h1:t6rEGG2sQ4J7DhFxSZVOTjNd0YO/KlfWQyK1W4tog+E=
yunion.io/x/pkg v0.0.0-20190628082551-f4033ba2ea30/go.mod h1:t6rEGG2sQ4J7DhFxSZVOTjNd0YO/KlfWQyK1W4tog+E=
yunion.io/x/pkg v1.10.4-0.20250715170922-d5b8a92716b6 h1:bcvKeB+j9oc1wS7/AjonkUlh+Dl6HSw/hfQuFI2JUXw=
yunion.io/x/pkg v1.10.4-0.20250715170922-d5b8a92716b6/go.mod h1:0Bwxqd9MA3ACi119/l02FprY/o9gHahmYC2bsSbnVpM=
yunion.io/x/pkg v1.10.4-0.20250805171825-2431e10f90a9 h1:8NuoKUPb3sHigChE6Mz6Nf9aZvM/TvORueIZAMYfPK0=
yunion.io/x/pkg v1.10.4-0.20250805171825-2431e10f90a9/go.mod h1:0Bwxqd9MA3ACi119/l02FprY/o9gHahmYC2bsSbnVpM=
yunion.io/x/s3cli v0.0.0-20241221171442-1c11599d28e1 h1:1KJ3YYinydPHpDEQRXdr/T8SYcKZ5Er+m489H+PnaQ4=
yunion.io/x/s3cli v0.0.0-20241221171442-1c11599d28e1/go.mod h1:0iFKpOs1y4lbCxeOmq3Xx/0AcQoewVPwj62eRluioEo=
yunion.io/x/sqlchemy v1.1.3-0.20250531010554-ce98f840b833 h1:XTFC1naKYkciCQDLm9izpzHXfTenmmtYsTpVKrsN5hE=
+4
View File
@@ -39,6 +39,10 @@ func (self *SBaseHostDriver) ValidateUpdateDisk(ctx context.Context, userCred mc
return input, nil
}
func (self *SBaseHostDriver) RequestRemoteUpdateDisk(ctx context.Context, userCred mcclient.TokenCredential, storage *models.SStorage, disk *models.SDisk, replaceTags bool) error {
return nil
}
func (self *SBaseHostDriver) ValidateResetDisk(ctx context.Context, userCred mcclient.TokenCredential, disk *models.SDisk, snapshot *models.SSnapshot, guests []models.SGuest, input *api.DiskResetInput) (*api.DiskResetInput, error) {
return nil, httperrors.NewNotImplementedError("Not Implement ValidateResetDisk")
}
+4
View File
@@ -52,6 +52,10 @@ func (self *SESXiHostDriver) ValidateDiskSize(storage *models.SStorage, sizeGb i
return nil
}
func (self *SESXiHostDriver) RequestRemoteUpdateDisk(ctx context.Context, userCred mcclient.TokenCredential, storage *models.SStorage, disk *models.SDisk, replaceTags bool) error {
return nil
}
func (self *SESXiHostDriver) CheckAndSetCacheImage(ctx context.Context, userCred mcclient.TokenCredential, host *models.SHost, storageCache *models.SStoragecache, task taskman.ITask) error {
params := task.GetParams()
imageId, err := params.GetString("image_id")
+49
View File
@@ -14,6 +14,55 @@
package hostdrivers
import (
"context"
"yunion.io/x/cloudmux/pkg/cloudprovider"
"yunion.io/x/pkg/errors"
"yunion.io/x/onecloud/pkg/compute/models"
"yunion.io/x/onecloud/pkg/mcclient"
"yunion.io/x/onecloud/pkg/util/logclient"
)
type SVirtualizationHostDriver struct {
SBaseHostDriver
}
func (self *SVirtualizationHostDriver) RequestRemoteUpdateDisk(ctx context.Context, userCred mcclient.TokenCredential, storage *models.SStorage, disk *models.SDisk, replaceTags bool) error {
iDisk, err := disk.GetIDisk(ctx)
if err != nil {
return errors.Wrap(err, "GetIDisk")
}
err = func() error {
oldTags, err := iDisk.GetTags()
if err != nil {
if errors.Cause(err) == cloudprovider.ErrNotSupported || errors.Cause(err) == cloudprovider.ErrNotImplemented {
return nil
}
return errors.Wrap(err, "iVM.GetTags()")
}
tags, err := disk.GetAllUserMetadata()
if err != nil {
return errors.Wrapf(err, "GetAllUserMetadata")
}
tagsUpdateInfo := cloudprovider.TagsUpdateInfo{OldTags: oldTags, NewTags: tags}
err = cloudprovider.SetTags(ctx, iDisk, storage.ManagerId, tags, replaceTags)
if err != nil {
if errors.Cause(err) == cloudprovider.ErrNotSupported || errors.Cause(err) == cloudprovider.ErrNotImplemented {
return nil
}
logclient.AddSimpleActionLog(disk, logclient.ACT_UPDATE_TAGS, err, userCred, false)
return errors.Wrap(err, "iVM.SetTags")
}
logclient.AddSimpleActionLog(disk, logclient.ACT_UPDATE_TAGS, tagsUpdateInfo, userCred, true)
return nil
}()
if err != nil {
return err
}
return nil
}
+27 -7
View File
@@ -718,12 +718,28 @@ func getDiskResourceRequirements(ctx context.Context, userCred mcclient.TokenCre
return req
}
/*func (manager *SDiskManager) convertToBatchCreateData(data jsonutils.JSONObject) *jsonutils.JSONDict {
diskConfig, _ := data.Get("disk")
newData := data.(*jsonutils.JSONDict).CopyExcludes("disk")
newData.Add(diskConfig, "disk.0")
return newData
}*/
func (disk *SDisk) OnMetadataUpdated(ctx context.Context, userCred mcclient.TokenCredential) {
if len(disk.ExternalId) == 0 || options.Options.KeepTagLocalization {
return
}
err := disk.StartRemoteUpdateTask(ctx, userCred, true, "")
if err != nil {
log.Errorf("StartRemoteUpdateTask fail: %s", err)
}
}
func (disk *SDisk) StartRemoteUpdateTask(ctx context.Context, userCred mcclient.TokenCredential, replaceTags bool, parentTaskId string) error {
data := jsonutils.NewDict()
if replaceTags {
data.Add(jsonutils.JSONTrue, "replace_tags")
}
task, err := taskman.TaskManager.NewTask(ctx, "DiskRemoteUpdateTask", disk, userCred, data, parentTaskId, "", nil)
if err != nil {
return errors.Wrap(err, "Start DiskRemoteUpdateTask")
}
disk.SetStatus(ctx, userCred, apis.STATUS_UPDATE_TAGS, "StartRemoteUpdateTask")
return task.ScheduleRun(nil)
}
func (disk *SDisk) PostCreate(ctx context.Context, userCred mcclient.TokenCredential, ownerId mcclient.IIdentityProvider, query jsonutils.JSONObject, data jsonutils.JSONObject) {
disk.SVirtualResourceBase.PostCreate(ctx, userCred, ownerId, query, data)
@@ -2323,7 +2339,11 @@ func (self *SDisk) PerformSyncstatus(ctx context.Context, userCred mcclient.Toke
return nil, httperrors.NewBadRequestError("Disk has %d task active, can't sync status", count)
}
return nil, StartResourceSyncStatusTask(ctx, userCred, self, "DiskSyncstatusTask", "")
return nil, self.StartSyncstatus(ctx, userCred, "")
}
func (disk *SDisk) StartSyncstatus(ctx context.Context, userCred mcclient.TokenCredential, parentTaskId string) error {
return StartResourceSyncStatusTask(ctx, userCred, disk, "DiskSyncstatusTask", parentTaskId)
}
func (self *SDisk) PerformPurge(ctx context.Context, userCred mcclient.TokenCredential, query jsonutils.JSONObject, data jsonutils.JSONObject) (jsonutils.JSONObject, error) {
+1 -1
View File
@@ -41,7 +41,7 @@ type IHostDriver interface {
// create disk
RequestAllocateDiskOnStorage(ctx context.Context, userCred mcclient.TokenCredential, host *SHost, storage *SStorage, disk *SDisk, task taskman.ITask, input api.DiskAllocateInput) error
RequestRebuildDiskOnStorage(ctx context.Context, host *SHost, storage *SStorage, disk *SDisk, task taskman.ITask, input api.DiskAllocateInput) error
RequestRemoteUpdateDisk(ctx context.Context, userCred mcclient.TokenCredential, storage *SStorage, disk *SDisk, replaceTags bool) error
// delete disk
RequestDeallocateDiskOnHost(ctx context.Context, host *SHost, storage *SStorage, disk *SDisk, cleanSnapshots bool, task taskman.ITask) error
RequestDeallocateBackupDiskOnHost(ctx context.Context, host *SHost, storage *SStorage, disk *SDisk, task taskman.ITask) error
@@ -0,0 +1,96 @@
// Copyright 2019 Yunion
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package tasks
import (
"context"
"yunion.io/x/jsonutils"
"yunion.io/x/pkg/errors"
"yunion.io/x/onecloud/pkg/apis"
api "yunion.io/x/onecloud/pkg/apis/compute"
"yunion.io/x/onecloud/pkg/cloudcommon/db"
"yunion.io/x/onecloud/pkg/cloudcommon/db/taskman"
"yunion.io/x/onecloud/pkg/compute/models"
"yunion.io/x/onecloud/pkg/util/logclient"
)
type DiskRemoteUpdateTask struct {
taskman.STask
}
func init() {
taskman.RegisterTask(DiskRemoteUpdateTask{})
}
func (self *DiskRemoteUpdateTask) taskFail(ctx context.Context, disk *models.SDisk, err error) {
disk.SetStatus(ctx, self.UserCred, apis.STATUS_UPDATE_TAGS_FAILED, err.Error())
self.SetStageFailed(ctx, jsonutils.NewString(err.Error()))
}
func (self *DiskRemoteUpdateTask) OnInit(ctx context.Context, obj db.IStandaloneModel, data jsonutils.JSONObject) {
disk := obj.(*models.SDisk)
var host *models.SHost
storage, _ := disk.GetStorage()
guest := disk.GetGuest()
if guest != nil {
host, _ = guest.GetHost()
} else {
host, _ = storage.GetMasterHost()
}
reason := "Cannot find host for disk"
if host == nil || host.HostStatus != api.HOST_ONLINE {
disk.SetStatus(ctx, self.GetUserCred(), api.DISK_READY, reason)
self.SetStageFailed(ctx, jsonutils.NewString(reason))
logclient.AddActionLogWithStartable(self, disk, logclient.ACT_UPDATE_TAGS, reason, self.UserCred, false)
return
}
self.StartRemoteUpdateTask(ctx, host, storage, disk)
}
func (self *DiskRemoteUpdateTask) StartRemoteUpdateTask(ctx context.Context, host *models.SHost, storage *models.SStorage, disk *models.SDisk) {
self.SetStage("OnRemoteUpdateComplete", nil)
replaceTags := jsonutils.QueryBoolean(self.Params, "replace_tags", false)
taskman.LocalTaskRun(self, func() (jsonutils.JSONObject, error) {
driver := host.GetHostDriver()
err := driver.RequestRemoteUpdateDisk(ctx, self.GetUserCred(), storage, disk, replaceTags)
if err != nil {
return nil, errors.Wrap(err, "RequestRemoteUpdateDisk")
}
return nil, nil
})
}
func (self *DiskRemoteUpdateTask) OnRemoteUpdateComplete(ctx context.Context, disk *models.SDisk, data jsonutils.JSONObject) {
self.SetStage("OnSyncStatusComplete", nil)
disk.StartSyncstatus(ctx, self.UserCred, self.GetTaskId())
}
func (self *DiskRemoteUpdateTask) OnRemoteUpdateCompleteFailed(ctx context.Context, disk *models.SDisk, data jsonutils.JSONObject) {
self.taskFail(ctx, disk, errors.Errorf(data.String()))
}
func (self *DiskRemoteUpdateTask) OnSyncStatusComplete(ctx context.Context, disk *models.SDisk, data jsonutils.JSONObject) {
self.SetStageComplete(ctx, nil)
}
func (self *DiskRemoteUpdateTask) OnSyncStatusCompleteFailed(ctx context.Context, disk *models.SDisk, data jsonutils.JSONObject) {
self.SetStageFailed(ctx, data)
}
+2 -2
View File
@@ -1576,7 +1576,7 @@ sigs.k8s.io/structured-merge-diff/v4/value
# sigs.k8s.io/yaml v1.2.0
## explicit; go 1.12
sigs.k8s.io/yaml
# yunion.io/x/cloudmux v0.3.10-0-alpha.1.0.20250721091657-0b9a131cbdfe
# yunion.io/x/cloudmux v0.3.10-0-alpha.1.0.20250806071154-376c8716aafd
## explicit; go 1.21
yunion.io/x/cloudmux/pkg/apis
yunion.io/x/cloudmux/pkg/apis/billing
@@ -1671,7 +1671,7 @@ yunion.io/x/log/hooks
yunion.io/x/ovsdb/cli_util
yunion.io/x/ovsdb/schema/ovn_nb
yunion.io/x/ovsdb/types
# yunion.io/x/pkg v1.10.4-0.20250715170922-d5b8a92716b6
# yunion.io/x/pkg v1.10.4-0.20250805171825-2431e10f90a9
## explicit; go 1.18
yunion.io/x/pkg/appctx
yunion.io/x/pkg/errors
+4 -1
View File
@@ -302,7 +302,7 @@ func _jsonRequest(client *sdk.Client, domain string, version string, apiName str
"List": requests.GET,
"Delete": requests.DELETE,
} {
if strings.HasPrefix(apiName, prefix) {
if strings.HasPrefix(apiName, prefix) && !strings.HasPrefix(domain, "mongodb") {
method = _method
break
}
@@ -331,6 +331,9 @@ func _jsonRequest(client *sdk.Client, domain string, version string, apiName str
req.PathPattern = pathPattern
req.Method = method
req.GetHeaders()["Content-Type"] = "application/json"
} else if strings.HasPrefix(domain, "mongodb") {
req.Method = requests.POST
req.GetHeaders()["Content-Type"] = "application/json"
}
resp, err := processCommonRequest(client, req)
+4
View File
@@ -164,6 +164,10 @@ func (self *SDisk) ChangeBillingType(billingType string) error {
return self.storage.zone.region.ChangeDiskChargeType(self.InstanceId, self.DiskId, billingType)
}
func (self *SDisk) SetTags(tags map[string]string, replace bool) error {
return self.storage.zone.region.SetResourceTags(ALIYUN_SERVICE_ECS, "disk", self.DiskId, tags, replace)
}
func (self *SRegion) ChangeDiskChargeType(vmId, diskId string, billingType string) error {
params := make(map[string]string)
params["RegionId"] = self.RegionId
+95 -1
View File
@@ -67,6 +67,39 @@ func (self *SRegion) GetMongoDBBackups(id string, start time.Time, end time.Time
func (self *SMongoDB) GetIBackups() ([]cloudprovider.SMongoDBBackup, error) {
backups := []SMongoDBBackup{}
err := self.Refresh()
if err != nil {
return nil, errors.Wrapf(err, "Refresh")
}
ret := []cloudprovider.SMongoDBBackup{}
if self.DBInstanceType == "sharding" {
backups, err := self.region.DescribeClusterBackups(self.DBInstanceId)
if err != nil {
return nil, errors.Wrapf(err, "DescribeClusterBackups")
}
for _, res := range backups {
backup := cloudprovider.SMongoDBBackup{}
backup.Name = res.ClusterBackupId
backup.StartTime = res.ClusterBackupStartTime
backup.EndTime = res.ClusterBackupEndTime
backup.BackupSizeKb = int(res.ClusterBackupSize / 1024)
switch res.ClusterBackupStatus {
case "OK":
backup.Status = cloudprovider.MongoDBBackupStatusAvailable
case "Failed":
backup.Status = cloudprovider.MongoDBBackupStatusFailed
default:
backup.Status = cloudprovider.TMongoDBBackupStatus(strings.ToLower(res.ClusterBackupStatus))
}
backup.BackupMethod = cloudprovider.TMongoDBBackupMethod(strings.ToLower(res.ClusterBackupMode))
backup.BackupType = cloudprovider.MongoDBBackupTypeAuto
if res.ClusterBackupMode == "Manual" {
backup.BackupType = cloudprovider.MongoDBBackupTypeManual
}
ret = append(ret, backup)
}
return ret, nil
}
now := time.Now().Add(time.Minute * -1)
for {
part, total, err := self.region.GetMongoDBBackups(self.DBInstanceId, self.CreationTime, now, 100, len(backups)/100)
@@ -78,7 +111,7 @@ func (self *SMongoDB) GetIBackups() ([]cloudprovider.SMongoDBBackup, error) {
break
}
}
ret := []cloudprovider.SMongoDBBackup{}
for _, res := range backups {
backup := cloudprovider.SMongoDBBackup{}
backup.Name = res.BackupId
@@ -102,3 +135,64 @@ func (self *SMongoDB) GetIBackups() ([]cloudprovider.SMongoDBBackup, error) {
}
return ret, nil
}
type SMongoDBClusterBackup struct {
AttachLogStatus string
BackupExpireTime time.Time
Backups []struct {
BackupEndTime time.Time
BackupId string
BackupName string
BackupSize string
BackupStartTime time.Time
BackupStatus string
ExtraInfo struct {
InstanceClass string
NodeId string
NodeType string
StorageSize string
}
InstanceName string
IsAvail int
}
ClusterBackupEndTime time.Time
ClusterBackupId string
ClusterBackupMode string
ClusterBackupSize int64
ClusterBackupStartTime time.Time
ClusterBackupStatus string
EngineVersion string
ExtraInfo struct{}
IsAvail int
}
func (region *SRegion) DescribeClusterBackups(id string) ([]SMongoDBClusterBackup, error) {
backups := []SMongoDBClusterBackup{}
pageNum := 1
params := map[string]string{
"DBInstanceId": id,
"PageSize": "50",
"PageNumber": fmt.Sprintf("%d", pageNum),
}
for {
resp, err := region.mongodbRequest("DescribeClusterBackups", params)
if err != nil {
return nil, errors.Wrapf(err, "DescribeClusterBackups")
}
part := struct {
MaxResults int
ClusterBackups []SMongoDBClusterBackup
}{}
err = resp.Unmarshal(&part)
if err != nil {
return nil, errors.Wrapf(err, "resp.Unmarshal")
}
backups = append(backups, part.ClusterBackups...)
if len(backups) >= part.MaxResults {
break
}
pageNum++
params["PageNumber"] = fmt.Sprintf("%d", pageNum)
}
return backups, nil
}
+4
View File
@@ -198,6 +198,10 @@ func (self *SDisk) Delete(ctx context.Context) error {
return self.storage.zone.region.DeleteDisk(self.VolumeId)
}
func (self *SDisk) SetTags(tags map[string]string, replace bool) error {
return self.storage.zone.region.setTags("volume", self.VolumeId, tags, replace)
}
func (self *SDisk) CreateISnapshot(ctx context.Context, name string, desc string) (cloudprovider.ICloudSnapshot, error) {
snapshot, err := self.storage.zone.region.CreateSnapshot(self.VolumeId, name, desc)
if err != nil {
+2 -2
View File
@@ -229,7 +229,7 @@ func (region *SRegion) CreateDisk(zone string, storageType string, opts *cloudpr
labels[encode.EncodeGoogleLabel(k)] = encode.EncodeGoogleLabel(v)
}
body := map[string]interface{}{
"name": opts.Name,
"name": normalizeString(opts.Name),
"description": opts.Desc,
// https://www.googleapis.com/compute/v1/projects/my-project-15390453537169/zones/us-west2-c/diskTypes/pd-standard
// projects/my-project-15390453537169/zones/us-west2-c/diskTypes/pd-standard
@@ -258,7 +258,7 @@ func (region *SRegion) ResizeDisk(id string, sizeGb int) error {
func (self *SRegion) CreateSnapshot(diskId string, name string, desc string) (*SSnapshot, error) {
body := map[string]string{
"name": name,
"name": normalizeString(name),
"description": desc,
}
err := self.Do(diskId, "createSnapshot", nil, jsonutils.Marshal(body))
+1 -1
View File
@@ -175,7 +175,7 @@ func (addr *SAddress) ChangeBandwidth(bw int) error {
func (region *SRegion) CreateEip(name string, desc string) (*SAddress, error) {
body := map[string]string{
"name": name,
"name": normalizeString(name),
"description": desc,
}
resource := fmt.Sprintf("regions/%s/addresses", region.Name)
+1 -1
View File
@@ -122,7 +122,7 @@ func (cli *SGoogleClient) GetGlobalNetworks(maxResults int, pageToken string) ([
func (self *SGoogleClient) CreateGlobalNetwork(name string, desc string) (*SGlobalNetwork, error) {
body := map[string]interface{}{
"name": name,
"name": normalizeString(name),
"description": desc,
"autoCreateSubnetworks": false,
"mtu": 1460,
+4 -17
View File
@@ -28,7 +28,6 @@ import (
"yunion.io/x/pkg/util/encode"
"yunion.io/x/pkg/util/fileutils"
"yunion.io/x/pkg/util/imagetools"
"yunion.io/x/pkg/util/pinyinutils"
"yunion.io/x/pkg/utils"
billing_api "yunion.io/x/cloudmux/pkg/apis/billing"
@@ -564,18 +563,6 @@ func (region *SRegion) _createVM(zone string, desc *cloudprovider.SManagedVMCrea
if len(desc.SysDisk.Name) == 0 {
desc.SysDisk.Name = fmt.Sprintf("vdisk-%s-%d", desc.Name, time.Now().UnixNano())
}
nameConv := func(name string) string {
name = strings.Replace(name, "_", "-", -1)
name = pinyinutils.Text2Pinyin(name)
name = strings.ToLower(name)
if len(name) > 63 {
name = name[:63]
}
if name[len(name)-1] == '-' {
name = name[:len(name)-1] + "1"
}
return name
}
labels := map[string]string{}
for k, v := range desc.Tags {
@@ -585,7 +572,7 @@ func (region *SRegion) _createVM(zone string, desc *cloudprovider.SManagedVMCrea
disks = append(disks, map[string]interface{}{
"boot": true,
"initializeParams": map[string]interface{}{
"diskName": nameConv(desc.SysDisk.Name),
"diskName": normalizeString(desc.SysDisk.Name),
"sourceImage": desc.ExternalImageId,
"diskSizeGb": desc.SysDisk.SizeGB,
"diskType": fmt.Sprintf("zones/%s/diskTypes/%s", zone, desc.SysDisk.StorageType),
@@ -600,7 +587,7 @@ func (region *SRegion) _createVM(zone string, desc *cloudprovider.SManagedVMCrea
disks = append(disks, map[string]interface{}{
"boot": false,
"initializeParams": map[string]interface{}{
"diskName": nameConv(disk.Name),
"diskName": normalizeString(disk.Name),
"diskSizeGb": disk.SizeGB,
"diskType": fmt.Sprintf("zones/%s/diskTypes/%s", zone, disk.StorageType),
"labels": labels,
@@ -616,7 +603,7 @@ func (region *SRegion) _createVM(zone string, desc *cloudprovider.SManagedVMCrea
networkInterface["networkIp"] = desc.IpAddr
}
params := map[string]interface{}{
"name": desc.NameEn,
"name": normalizeString(desc.NameEn),
"description": desc.Description,
"machineType": fmt.Sprintf("zones/%s/machineTypes/%s", zone, desc.InstanceType),
"networkInterfaces": []map[string]string{
@@ -840,7 +827,7 @@ func (region *SRegion) RebuildRoot(instanceId string, imageId string, sysDiskSiz
func (self *SRegion) SaveImage(diskId string, opts *cloudprovider.SaveImageOptions) (*SImage, error) {
params := map[string]interface{}{
"name": opts.Name,
"name": normalizeString(opts.Name),
"description": opts.Notes,
"sourceDisk": diskId,
}
+37 -2
View File
@@ -16,11 +16,13 @@ package google
import (
"fmt"
"regexp"
"strings"
"time"
"yunion.io/x/jsonutils"
"yunion.io/x/pkg/errors"
"yunion.io/x/pkg/util/pinyinutils"
"yunion.io/x/pkg/util/secrules"
api "yunion.io/x/cloudmux/pkg/apis/compute"
@@ -124,7 +126,7 @@ func (self *SSecurityGroup) GetRules() ([]cloudprovider.ISecurityGroupRule, erro
func (self *SGoogleClient) CreateSecurityGroupRule(globalnetworkId, tag string, opts *cloudprovider.SecurityGroupRuleCreateOptions) (*SFirewall, error) {
name := fmt.Sprintf("%s-%d-auto-%d", opts.String(), opts.Priority, time.Now().Unix())
body := map[string]interface{}{
"name": strings.ToLower(name),
"name": normalizeString(name),
"description": opts.Desc,
"priority": opts.Priority,
"network": globalnetworkId,
@@ -181,8 +183,41 @@ func (self *SSecurityGroup) CreateRule(opts *cloudprovider.SecurityGroupRuleCrea
return rule, nil
}
func normalizeString(input string) string {
// 1. 转换为小写
lowerStr := strings.ToLower(input)
lowerStr = strings.Replace(lowerStr, "_", "-", -1)
lowerStr = pinyinutils.Text2Pinyin(lowerStr)
// 2. 移除所有不符合要求的字符(只保留a-z、0-9和-)
reg := regexp.MustCompile(`[^a-z0-9-]`)
cleaned := reg.ReplaceAllString(lowerStr, "")
// 3. 处理开头:如果不以字母开头,添加一个默认字母a
if len(cleaned) == 0 || !regexp.MustCompile(`^[a-z]`).MatchString(cleaned) {
cleaned = "a" + cleaned
}
// 4. 处理结尾:如果以连字符结尾,移除
cleaned = regexp.MustCompile(`-$`).ReplaceAllString(cleaned, "")
// 5. 限制长度为63个字符(域名标签的最大长度)
if len(cleaned) > 63 {
cleaned = cleaned[:63]
// 确保截断后不以连字符结尾
cleaned = regexp.MustCompile(`-$`).ReplaceAllString(cleaned, "")
// 如果截断后为空,添加一个数字1
if len(cleaned) == 0 {
cleaned = "1"
}
}
return cleaned
}
func (self *SGlobalNetwork) CreateISecurityGroup(opts *cloudprovider.SecurityGroupCreateInput) (cloudprovider.ICloudSecurityGroup, error) {
secgroup := &SSecurityGroup{gvpc: self, Tag: strings.ToLower(opts.Name)}
tag := normalizeString(opts.Name)
secgroup := &SSecurityGroup{gvpc: self, Tag: tag}
groups, err := self.GetISecurityGroups()
if err != nil {
return nil, err
+1 -1
View File
@@ -122,7 +122,7 @@ func (vpc *SVpc) GetIWireById(id string) (cloudprovider.ICloudWire, error) {
func (self *SRegion) CreateVpc(name string, gvpcId string, cidr string, desc string) (*SVpc, error) {
body := map[string]interface{}{
"name": name,
"name": normalizeString(name),
"description": desc,
"network": gvpcId,
"ipCidrRange": cidr,
+4
View File
@@ -312,6 +312,10 @@ func (self *SDisk) GetExpiredAt() time.Time {
return self.DeadlineTime.Add(time.Hour * -8)
}
func (self *SDisk) SetTags(tags map[string]string, replace bool) error {
return self.storage.zone.region.SetResourceTags("cvm", "volume", []string{self.DiskId}, tags, replace)
}
func (self *SDisk) GetISnapshot(snapshotId string) (cloudprovider.ICloudSnapshot, error) {
snapshots, total, err := self.storage.zone.region.GetSnapshots("", "", "", []string{snapshotId}, 0, 1)
if err != nil {
+7 -7
View File
@@ -284,13 +284,13 @@ func GetAddrPort(urlStr string) (string, int, error) {
return "", 0, err
}
host := parts.Host
commaPos := strings.IndexByte(host, ':')
if commaPos > 0 {
port, err := strconv.ParseInt(host[commaPos+1:], 10, 32)
hostAddr, hostPortStr, err := net.SplitHostPort(host)
if err == nil {
hostPort, err := strconv.ParseInt(hostPortStr, 10, 32)
if err != nil {
return "", 0, err
return "", 0, errors.Wrapf(err, "strconv.ParseInt port string %s", hostPortStr)
} else {
return host[:commaPos], int(port), nil
return hostAddr, int(hostPort), nil
}
} else {
switch parts.Scheme {
@@ -299,7 +299,7 @@ func GetAddrPort(urlStr string) (string, int, error) {
case "https":
return parts.Host, 443, nil
default:
return "", 0, fmt.Errorf("Unknown schema %s", parts.Scheme)
return "", 0, errors.Wrapf(errors.ErrInvalidFormat, "Unknown schema %s", parts.Scheme)
}
}
}
@@ -515,7 +515,7 @@ func request(client sClient, ctx context.Context, method THttpMethod, urlStr str
var reqBody string
if bodySeeker, ok := body.(io.ReadSeeker); ok {
bodySeeker.Seek(0, io.SeekStart)
reqBodyBytes, _ := ioutil.ReadAll(bodySeeker)
reqBodyBytes, _ := io.ReadAll(bodySeeker)
if reqBodyBytes != nil {
reqBody = string(reqBodyBytes)
}