yunion.io/x/cloudmux@v0.3.10-0-alpha.1/pkg/multicloud/azure/dbinstance.go (about)

     1  // Copyright 2019 Yunion
     2  //
     3  // Licensed under the Apache License, Version 2.0 (the "License");
     4  // you may not use this file except in compliance with the License.
     5  // You may obtain a copy of the License at
     6  //
     7  //     http://www.apache.org/licenses/LICENSE-2.0
     8  //
     9  // Unless required by applicable law or agreed to in writing, software
    10  // distributed under the License is distributed on an "AS IS" BASIS,
    11  // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    12  // See the License for the specific language governing permissions and
    13  // limitations under the License.
    14  
    15  package azure
    16  
    17  import (
    18  	"fmt"
    19  	"net/url"
    20  	"strings"
    21  	"time"
    22  
    23  	"yunion.io/x/jsonutils"
    24  	"yunion.io/x/pkg/errors"
    25  
    26  	api "yunion.io/x/cloudmux/pkg/apis/compute"
    27  	"yunion.io/x/cloudmux/pkg/cloudprovider"
    28  	"yunion.io/x/cloudmux/pkg/multicloud"
    29  )
    30  
    31  type SDBInstanceVirtualNetworkRule struct {
    32  	ID         string                                  `json:"id"`
    33  	Name       string                                  `json:"name"`
    34  	Type       string                                  `json:"type"`
    35  	Properties SDBInstanceVirtualNetworkRuleProperties `json:"properties"`
    36  }
    37  
    38  type SDBInstanceVirtualNetworkRuleProperties struct {
    39  	IgnoreMissingVnetServiceEndpoint bool   `json:"ignoreMissingVnetServiceEndpoint"`
    40  	State                            string `json:"state"`
    41  	VirtualNetworkSubnetID           string `json:"virtualNetworkSubnetId"`
    42  }
    43  
    44  type SDBInstanceSku struct {
    45  	Name     string `json:"name"`
    46  	Tier     string `json:"tier"`
    47  	Family   string `json:"family"`
    48  	Capacity int    `json:"capacity"`
    49  }
    50  
    51  type SDBInstanceStorageProfile struct {
    52  	StorageMB           int    `json:"storageMB"`
    53  	BackupRetentionDays int    `json:"backupRetentionDays"`
    54  	StorageIops         int    `json:"storageIops"`
    55  	GeoRedundantBackup  string `json:"geoRedundantBackup"`
    56  }
    57  
    58  type SDBInstanceDelegatedSubnetArguments struct {
    59  	SubnetArmResourceId string `json:"subnetArmResourceId"`
    60  }
    61  
    62  type SDBInstanceProperties struct {
    63  	AdministratorLogin       string                    `json:"administratorLogin"`
    64  	StorageProfile           SDBInstanceStorageProfile `json:"storageProfile"`
    65  	Version                  string                    `json:"version"`
    66  	SslEnforcement           string                    `json:"sslEnforcement"`
    67  	UserVisibleState         string                    `json:"userVisibleState"`
    68  	FullyQualifiedDomainName string                    `json:"fullyQualifiedDomainName"`
    69  	EarliestRestoreDate      time.Time                 `json:"earliestRestoreDate"`
    70  
    71  	ReplicationRole          string                              `json:"replicationRole"`
    72  	MasterServerId           string                              `json:"masterServerId"`
    73  	ReplicaCapacity          int                                 `json:"replicaCapacity"`
    74  	DelegatedSubnetArguments SDBInstanceDelegatedSubnetArguments `json:"delegatedSubnetArguments"`
    75  }
    76  
    77  type SDBInstance struct {
    78  	region *SRegion
    79  	multicloud.SDBInstanceBase
    80  	AzureTags
    81  	Sku        SDBInstanceSku        `json:"sku"`
    82  	Properties SDBInstanceProperties `json:"properties"`
    83  	Location   string                `json:"location"`
    84  	ID         string                `json:"id"`
    85  	Name       string                `json:"name"`
    86  	Type       string                `json:"type"`
    87  }
    88  
    89  func (self *SRegion) GetIDBInstances() ([]cloudprovider.ICloudDBInstance, error) {
    90  	instanceTypes := []string{
    91  		"Microsoft.DBForMariaDB/servers",
    92  		"Microsoft.DBforMySQL/servers",
    93  		"Microsoft.DBforMySQL/flexibleServers",
    94  		"Microsoft.DBforPostgreSQL/servers",
    95  		"Microsoft.DBforPostgreSQL/flexibleServers",
    96  	}
    97  	DBInstances := []SDBInstance{}
    98  	for i := range instanceTypes {
    99  		instances, err := self.ListDBInstance(instanceTypes[i])
   100  		if err != nil {
   101  			if errors.Cause(err) != cloudprovider.ErrNotFound {
   102  				return nil, errors.Wrap(err, "self.ListDBInstance()")
   103  			}
   104  		}
   105  		DBInstances = append(DBInstances, instances...)
   106  	}
   107  	result := []cloudprovider.ICloudDBInstance{}
   108  	for i := range DBInstances {
   109  		DBInstances[i].region = self
   110  		result = append(result, &DBInstances[i])
   111  	}
   112  	sqlServers, err := self.ListSQLServer()
   113  	if err != nil {
   114  		return nil, errors.Wrapf(err, "ListSQLServer")
   115  	}
   116  	for i := range sqlServers {
   117  		sqlServers[i].region = self
   118  		result = append(result, &sqlServers[i])
   119  	}
   120  	managedSQLServers, err := self.ListManagedSQLServer()
   121  	if err != nil {
   122  		return nil, errors.Wrapf(err, "ListManagedSQLServer")
   123  	}
   124  	for i := range managedSQLServers {
   125  		managedSQLServers[i].region = self
   126  		result = append(result, &managedSQLServers[i])
   127  	}
   128  	return result, nil
   129  }
   130  
   131  func (self *SRegion) GetIDBInstanceById(instanceId string) (cloudprovider.ICloudDBInstance, error) {
   132  	if strings.Index(strings.ToLower(instanceId), "microsoft.sql/servers") > 0 {
   133  		return self.GetSQLServer(instanceId)
   134  	}
   135  	if strings.Index(strings.ToLower(instanceId), "microsoft.sql/managedinstances") > 0 {
   136  		return self.GetManagedSQLServer(instanceId)
   137  	}
   138  	rds, err := self.GetDBInstanceById(instanceId)
   139  	if err != nil {
   140  		return nil, errors.Wrapf(err, "self.get(%s, url.Values{}, &newrds)", instanceId)
   141  	}
   142  	return rds, nil
   143  }
   144  
   145  func (self *SRegion) GetDBInstanceById(instanceId string) (*SDBInstance, error) {
   146  	rds := SDBInstance{}
   147  	err := self.get(instanceId, url.Values{}, &rds)
   148  	if err != nil {
   149  		return nil, errors.Wrapf(err, "self.get(%s, url.Values{}, &newrds)", instanceId)
   150  	}
   151  	rds.region = self
   152  	return &rds, nil
   153  }
   154  
   155  func (self *SRegion) ListDBInstance(instanceType string) ([]SDBInstance, error) {
   156  	result := []SDBInstance{}
   157  	err := self.list(instanceType, url.Values{}, &result)
   158  	if err != nil {
   159  		return nil, errors.Wrapf(err, "list(%s)", instanceType)
   160  	}
   161  	for i := range result {
   162  		result[i].region = self
   163  	}
   164  	return result, nil
   165  }
   166  
   167  func (self *SRegion) ListDBInstanceReplica(Id string) ([]SDBInstance, error) {
   168  	type replicas struct {
   169  		Value []SDBInstance
   170  	}
   171  	result := replicas{}
   172  	err := self.get(fmt.Sprintf("%s/replicas", Id), url.Values{}, &result)
   173  	if err != nil {
   174  		return nil, errors.Wrapf(err, "get(%s)", Id)
   175  	}
   176  	for i := range result.Value {
   177  		result.Value[i].region = self
   178  	}
   179  	return result.Value, nil
   180  }
   181  
   182  func (self *SRegion) ListDBInstanceVirtualNetworkRule(Id string) ([]SDBInstanceVirtualNetworkRule, error) {
   183  	type networksRules struct {
   184  		Value []SDBInstanceVirtualNetworkRule
   185  	}
   186  	result := networksRules{}
   187  	err := self.get(fmt.Sprintf("%s/virtualNetworkRules", Id), url.Values{}, &result)
   188  	if err != nil {
   189  		return nil, errors.Wrapf(err, "get(%s)", Id)
   190  	}
   191  	return result.Value, nil
   192  }
   193  
   194  func (rds *SDBInstance) GetName() string {
   195  	return rds.Name
   196  }
   197  
   198  func (rds *SDBInstance) GetId() string {
   199  	return strings.ToLower(rds.ID)
   200  }
   201  
   202  func (rds *SDBInstance) GetGlobalId() string {
   203  	return rds.GetId()
   204  }
   205  
   206  func (rds *SDBInstance) GetStatus() string {
   207  	return api.DBINSTANCE_RUNNING
   208  }
   209  
   210  func (self *SDBInstance) GetProjectId() string {
   211  	return getResourceGroup(self.ID)
   212  }
   213  
   214  func (rds *SDBInstance) GetExpiredAt() time.Time {
   215  	return time.Time{}
   216  }
   217  
   218  func (rds *SDBInstance) GetStorageType() string {
   219  	switch rds.Sku.Tier {
   220  	case "Basic":
   221  		return api.STORAGE_AZURE_BASIC
   222  	case "General Purpose":
   223  		return api.STORAGE_AZURE_GENERAL_PURPOSE
   224  	case "Memory Optimized":
   225  		return api.STORAGE_AZURE_GENERAL_PURPOSE
   226  	default:
   227  		return api.STORAGE_AZURE_BASIC
   228  	}
   229  }
   230  
   231  func (rds *SDBInstance) Refresh() error {
   232  	newrds := SDBInstance{}
   233  	err := rds.region.get(rds.ID, url.Values{}, &newrds)
   234  	if err != nil {
   235  		return errors.Wrapf(err, "rds.region.get(%s, url.Values{}, &newdb)", rds.ID)
   236  	}
   237  
   238  	err = jsonutils.Update(rds, newrds)
   239  	if err != nil {
   240  		return err
   241  	}
   242  	rds.Tags = newrds.Tags
   243  	return nil
   244  }
   245  
   246  func (rds *SDBInstance) GetMasterInstanceId() string {
   247  	if len(rds.Properties.MasterServerId) > 0 {
   248  		return strings.ToLower(rds.Properties.MasterServerId)
   249  	}
   250  	return ""
   251  }
   252  
   253  func (rds *SDBInstance) GetPort() int {
   254  	switch rds.GetEngine() {
   255  	case api.DBINSTANCE_TYPE_POSTGRESQL:
   256  		return 5432
   257  	case api.DBINSTANCE_TYPE_MYSQL:
   258  		return 3306
   259  	case api.DBINSTANCE_TYPE_MARIADB:
   260  		return 3306
   261  	default:
   262  		return 0
   263  	}
   264  }
   265  
   266  func (rds *SDBInstance) GetEngine() string {
   267  	databaseType := strings.Split(rds.Type, "/")
   268  	switch databaseType[0] {
   269  	case "Microsoft.DBforPostgreSQL":
   270  		return api.DBINSTANCE_TYPE_POSTGRESQL
   271  	case "Microsoft.DBforMySQL":
   272  		return api.DBINSTANCE_TYPE_MYSQL
   273  	case "Microsoft.DBforMariaDB":
   274  		return api.DBINSTANCE_TYPE_MARIADB
   275  	default:
   276  		return ""
   277  	}
   278  }
   279  
   280  func (rds *SDBInstance) GetEngineVersion() string {
   281  	return rds.Properties.Version
   282  }
   283  
   284  func (rds *SDBInstance) GetInstanceType() string {
   285  	return rds.Sku.Name
   286  }
   287  
   288  func (rds *SDBInstance) GetVcpuCount() int {
   289  	return rds.Sku.Capacity
   290  }
   291  
   292  func (rds *SDBInstance) GetVmemSizeMB() int {
   293  	if strings.Contains(rds.Type, "server") {
   294  		switch rds.Sku.Tier {
   295  		case "Basic":
   296  			return rds.Sku.Capacity * 2 * 1024
   297  		case "General Purpose":
   298  			return rds.Sku.Capacity * 5 * 1024
   299  		case "GeneralPurpose":
   300  			return int(float32(rds.Sku.Capacity) * 5.2 * 1024)
   301  		case "Memory Optimized":
   302  			return rds.Sku.Capacity * 10 * 1024
   303  		default:
   304  			return 0
   305  		}
   306  	}
   307  	return 0
   308  }
   309  
   310  func (rds *SDBInstance) GetDiskSizeGB() int {
   311  	return rds.Properties.StorageProfile.StorageMB / 1024
   312  }
   313  
   314  func (rds *SDBInstance) GetCategory() string {
   315  	return rds.Sku.Tier
   316  }
   317  
   318  func (rds *SDBInstance) GetMaintainTime() string {
   319  	return ""
   320  }
   321  
   322  func (rds *SDBInstance) GetConnectionStr() string {
   323  	return rds.Properties.FullyQualifiedDomainName
   324  }
   325  
   326  // func (rds *SDBInstance) GetInternalConnectionStr() string
   327  
   328  func (rds *SDBInstance) GetIVpcId() string {
   329  	splited := strings.Split(rds.Properties.DelegatedSubnetArguments.SubnetArmResourceId, "/subnets")
   330  	return splited[0]
   331  }
   332  
   333  func (rds *SDBInstance) GetDBNetworks() ([]cloudprovider.SDBInstanceNetwork, error) {
   334  	result := []cloudprovider.SDBInstanceNetwork{}
   335  	delegateNet := cloudprovider.SDBInstanceNetwork{NetworkId: rds.Properties.DelegatedSubnetArguments.SubnetArmResourceId}
   336  	result = append(result, delegateNet)
   337  	return result, nil
   338  }
   339  
   340  func (rds *SDBInstance) GetZone1Id() string {
   341  	return ""
   342  }
   343  
   344  func (rds *SDBInstance) GetZone2Id() string {
   345  	return ""
   346  }
   347  
   348  func (rds *SDBInstance) GetZone3Id() string {
   349  	return ""
   350  }
   351  
   352  func (rds *SDBInstance) GetIDBInstanceParameters() ([]cloudprovider.ICloudDBInstanceParameter, error) {
   353  	configs, err := rds.region.ListDBInstanceConfiguration(rds.ID)
   354  	if err != nil {
   355  		return nil, errors.Wrapf(err, "rds.region.ListDBInstanceConfiguration(%s)", rds.ID)
   356  	}
   357  	result := []cloudprovider.ICloudDBInstanceParameter{}
   358  	for i := range configs {
   359  		result = append(result, &configs[i])
   360  	}
   361  	return result, nil
   362  }
   363  
   364  func (rds *SDBInstance) GetIDBInstanceDatabases() ([]cloudprovider.ICloudDBInstanceDatabase, error) {
   365  	db, err := rds.region.ListSDBInstanceDatabase(rds.ID)
   366  	if err != nil {
   367  		return nil, errors.Wrapf(err, "rds.region.ListSDBInstanceDatabase(%s)", rds.ID)
   368  	}
   369  	result := []cloudprovider.ICloudDBInstanceDatabase{}
   370  	for i := range db {
   371  		result = append(result, &db[i])
   372  	}
   373  	return result, nil
   374  }
   375  
   376  func (rds *SDBInstance) GetIDBInstanceAccounts() ([]cloudprovider.ICloudDBInstanceAccount, error) {
   377  	accounts := []cloudprovider.ICloudDBInstanceAccount{}
   378  	if len(rds.Properties.AdministratorLogin) > 0 {
   379  		account := &SDBInstanceAccount{instance: rds, AccountName: rds.Properties.AdministratorLogin}
   380  		accounts = append(accounts, account)
   381  	}
   382  	return accounts, nil
   383  }
   384  
   385  func (rds *SDBInstance) GetIDBInstanceBackups() ([]cloudprovider.ICloudDBInstanceBackup, error) {
   386  	return []cloudprovider.ICloudDBInstanceBackup{}, nil
   387  }
   388  
   389  func (rds *SDBInstance) Delete() error {
   390  	return cloudprovider.ErrNotImplemented
   391  }
   392  
   393  func (self *SDBInstance) SetTags(tags map[string]string, replace bool) error {
   394  	if !replace {
   395  		for k, v := range self.Tags {
   396  			if _, ok := tags[k]; !ok {
   397  				tags[k] = v
   398  			}
   399  		}
   400  	}
   401  	_, err := self.region.client.SetTags(self.ID, tags)
   402  	if err != nil {
   403  		return errors.Wrapf(err, "self.region.client.SetTags(%s,%s)", self.ID, jsonutils.Marshal(tags).String())
   404  	}
   405  	return nil
   406  }