google.go 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384
  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. package regiondrivers
  15. import (
  16. "context"
  17. "fmt"
  18. "strings"
  19. "time"
  20. "yunion.io/x/cloudmux/pkg/cloudprovider"
  21. "yunion.io/x/jsonutils"
  22. "yunion.io/x/log"
  23. "yunion.io/x/pkg/errors"
  24. "yunion.io/x/pkg/util/secrules"
  25. "yunion.io/x/sqlchemy"
  26. "yunion.io/x/onecloud/pkg/apis"
  27. billing_api "yunion.io/x/onecloud/pkg/apis/billing"
  28. api "yunion.io/x/onecloud/pkg/apis/compute"
  29. "yunion.io/x/onecloud/pkg/cloudcommon/db"
  30. "yunion.io/x/onecloud/pkg/cloudcommon/db/taskman"
  31. "yunion.io/x/onecloud/pkg/cloudcommon/validators"
  32. "yunion.io/x/onecloud/pkg/compute/models"
  33. "yunion.io/x/onecloud/pkg/httperrors"
  34. "yunion.io/x/onecloud/pkg/mcclient"
  35. )
  36. type SGoogleRegionDriver struct {
  37. SManagedVirtualizationRegionDriver
  38. }
  39. func init() {
  40. driver := SGoogleRegionDriver{}
  41. models.RegisterRegionDriver(&driver)
  42. }
  43. func (self *SGoogleRegionDriver) GetProvider() string {
  44. return api.CLOUD_PROVIDER_GOOGLE
  45. }
  46. func (self *SGoogleRegionDriver) RequestCreateVpc(ctx context.Context, userCred mcclient.TokenCredential, region *models.SCloudregion, vpc *models.SVpc, task taskman.ITask) error {
  47. taskman.LocalTaskRun(task, func() (jsonutils.JSONObject, error) {
  48. provider := vpc.GetCloudprovider()
  49. if provider == nil {
  50. return nil, fmt.Errorf("failed to found vpc %s(%s) cloudprovider", vpc.Name, vpc.Id)
  51. }
  52. providerDriver, err := provider.GetProvider(ctx)
  53. if err != nil {
  54. return nil, errors.Wrap(err, "provider.GetProvider")
  55. }
  56. iregion, err := providerDriver.GetIRegionById(region.ExternalId)
  57. if err != nil {
  58. return nil, errors.Wrap(err, "vpc.GetIRegion")
  59. }
  60. gvpc, err := vpc.GetGlobalVpc()
  61. if err != nil {
  62. return nil, errors.Wrapf(err, "GetGlobalVpc")
  63. }
  64. opts := &cloudprovider.VpcCreateOptions{
  65. NAME: vpc.Name,
  66. CIDR: vpc.CidrBlock,
  67. GlobalVpcExternalId: gvpc.ExternalId,
  68. Desc: vpc.Description,
  69. }
  70. ivpc, err := iregion.CreateIVpc(opts)
  71. if err != nil {
  72. return nil, errors.Wrap(err, "iregion.CreateIVpc")
  73. }
  74. db.SetExternalId(vpc, userCred, ivpc.GetGlobalId())
  75. regions, err := provider.GetRegionByExternalIdPrefix(self.GetProvider())
  76. if err != nil {
  77. return nil, errors.Wrap(err, "GetRegionByExternalIdPrefix")
  78. }
  79. for _, region := range regions {
  80. iregion, err := providerDriver.GetIRegionById(region.ExternalId)
  81. if err != nil {
  82. return nil, errors.Wrap(err, "providerDrivder.GetIRegionById")
  83. }
  84. region.SyncVpcs(ctx, userCred, iregion, provider)
  85. }
  86. err = vpc.SyncWithCloudVpc(ctx, userCred, ivpc, nil)
  87. if err != nil {
  88. return nil, errors.Wrap(err, "vpc.SyncWithCloudVpc")
  89. }
  90. err = vpc.SyncRemoteWires(ctx, userCred)
  91. if err != nil {
  92. return nil, errors.Wrap(err, "vpc.SyncRemoteWires")
  93. }
  94. return nil, nil
  95. })
  96. return nil
  97. }
  98. func (self *SGoogleRegionDriver) IsSupportedDBInstance() bool {
  99. return true
  100. }
  101. func (self *SGoogleRegionDriver) ValidateDBInstanceRecovery(ctx context.Context, userCred mcclient.TokenCredential, instance *models.SDBInstance, backup *models.SDBInstanceBackup, input api.SDBInstanceRecoveryConfigInput) error {
  102. return nil
  103. }
  104. func (self *SGoogleRegionDriver) ValidateCreateDBInstanceData(ctx context.Context, userCred mcclient.TokenCredential, ownerId mcclient.IIdentityProvider, input api.DBInstanceCreateInput, skus []models.SDBInstanceSku, network *models.SNetwork) (api.DBInstanceCreateInput, error) {
  105. if input.BillingType == billing_api.BILLING_TYPE_PREPAID {
  106. return input, httperrors.NewInputParameterError("Google dbinstance not support prepaid billing type")
  107. }
  108. if input.DiskSizeGB < 10 || input.DiskSizeGB > 30720 {
  109. return input, httperrors.NewInputParameterError("disk size gb must in range 10 ~ 30720 Gb")
  110. }
  111. if input.Engine != api.DBINSTANCE_TYPE_MYSQL && len(input.Password) == 0 {
  112. return input, httperrors.NewMissingParameterError("password")
  113. }
  114. return input, nil
  115. }
  116. func (self *SGoogleRegionDriver) InitDBInstanceUser(ctx context.Context, instance *models.SDBInstance, task taskman.ITask, desc *cloudprovider.SManagedDBInstanceCreateConfig) error {
  117. user := "root"
  118. switch desc.Engine {
  119. case api.DBINSTANCE_TYPE_POSTGRESQL:
  120. user = "postgres"
  121. case api.DBINSTANCE_TYPE_SQLSERVER:
  122. user = "sqlserver"
  123. default:
  124. user = "root"
  125. }
  126. account := models.SDBInstanceAccount{}
  127. account.DBInstanceId = instance.Id
  128. account.Name = user
  129. account.Status = api.DBINSTANCE_USER_AVAILABLE
  130. account.SetModelManager(models.DBInstanceAccountManager, &account)
  131. err := models.DBInstanceAccountManager.TableSpec().Insert(ctx, &account)
  132. if err != nil {
  133. return err
  134. }
  135. return account.SetPassword(desc.Password)
  136. }
  137. func (self *SGoogleRegionDriver) ValidateCreateDBInstanceDatabaseData(ctx context.Context, userCred mcclient.TokenCredential, ownerId mcclient.IIdentityProvider, instance *models.SDBInstance, input api.DBInstanceDatabaseCreateInput) (api.DBInstanceDatabaseCreateInput, error) {
  138. return input, nil
  139. }
  140. func (self *SGoogleRegionDriver) ValidateCreateDBInstanceBackupData(ctx context.Context, userCred mcclient.TokenCredential, ownerId mcclient.IIdentityProvider, instance *models.SDBInstance, input api.DBInstanceBackupCreateInput) (api.DBInstanceBackupCreateInput, error) {
  141. return input, nil
  142. }
  143. func (self *SGoogleRegionDriver) ValidateCreateDBInstanceAccountData(ctx context.Context, userCred mcclient.TokenCredential, ownerId mcclient.IIdentityProvider, instance *models.SDBInstance, input api.DBInstanceAccountCreateInput) (api.DBInstanceAccountCreateInput, error) {
  144. return input, nil
  145. }
  146. func (self *SGoogleRegionDriver) RequestCreateDBInstanceBackup(ctx context.Context, userCred mcclient.TokenCredential, instance *models.SDBInstance, backup *models.SDBInstanceBackup, task taskman.ITask) error {
  147. taskman.LocalTaskRun(task, func() (jsonutils.JSONObject, error) {
  148. iRds, err := instance.GetIDBInstance(ctx)
  149. if err != nil {
  150. return nil, errors.Wrap(err, "instance.GetIDBInstance")
  151. }
  152. desc := &cloudprovider.SDBInstanceBackupCreateConfig{
  153. Name: backup.Name,
  154. Description: backup.Description,
  155. }
  156. _, err = iRds.CreateIBackup(desc)
  157. if err != nil {
  158. return nil, errors.Wrap(err, "iRds.CreateBackup")
  159. }
  160. backups, err := iRds.GetIDBInstanceBackups()
  161. if err != nil {
  162. return nil, errors.Wrap(err, "iRds.GetIDBInstanceBackups")
  163. }
  164. region, _ := backup.GetRegion()
  165. result := models.DBInstanceBackupManager.SyncDBInstanceBackups(ctx, userCred, backup.GetCloudprovider(), instance, region, backups, false)
  166. log.Infof("SyncDBInstanceBackups for dbinstance %s(%s) result: %s", instance.Name, instance.Id, result.Result())
  167. instance.SetStatus(ctx, userCred, api.DBINSTANCE_RUNNING, "")
  168. return nil, nil
  169. })
  170. return nil
  171. }
  172. func (self *SGoogleRegionDriver) ValidateCreateVpcData(ctx context.Context, userCred mcclient.TokenCredential, input api.VpcCreateInput) (api.VpcCreateInput, error) {
  173. var cidrV = validators.NewIPv4PrefixValidator("cidr_block")
  174. if err := cidrV.Validate(ctx, jsonutils.Marshal(input).(*jsonutils.JSONDict)); err != nil {
  175. return input, err
  176. }
  177. if cidrV.Value.MaskLen < 8 || cidrV.Value.MaskLen > 29 {
  178. return input, httperrors.NewInputParameterError("%s request the mask range should be between 8 and 29", self.GetProvider())
  179. }
  180. if len(input.GlobalvpcId) == 0 {
  181. _manager, err := validators.ValidateModel(ctx, userCred, models.CloudproviderManager, &input.CloudproviderId)
  182. if err != nil {
  183. return input, err
  184. }
  185. manager := _manager.(*models.SCloudprovider)
  186. globalVpcs, err := manager.GetGlobalVpcs()
  187. if err != nil {
  188. return input, errors.Wrapf(err, "GetGlobalVpcs")
  189. }
  190. if len(globalVpcs) != 1 {
  191. return input, httperrors.NewMissingParameterError("globalvpc_id")
  192. }
  193. input.GlobalvpcId = globalVpcs[0].Id
  194. }
  195. _, err := validators.ValidateModel(ctx, userCred, models.GlobalVpcManager, &input.GlobalvpcId)
  196. if err != nil {
  197. return input, err
  198. }
  199. return input, nil
  200. }
  201. func (self *SGoogleRegionDriver) ValidateCreateSecurityGroupInput(ctx context.Context, userCred mcclient.TokenCredential, input *api.SSecgroupCreateInput) (*api.SSecgroupCreateInput, error) {
  202. for i := range input.Rules {
  203. rule := input.Rules[i]
  204. if rule.Priority == nil {
  205. return nil, httperrors.NewMissingParameterError("priority")
  206. }
  207. if *rule.Priority < 0 || *rule.Priority > 65535 {
  208. return nil, httperrors.NewInputParameterError("invalid priority %d, range 0-65535", *rule.Priority)
  209. }
  210. if len(rule.Ports) > 0 && strings.Contains(input.Rules[i].Ports, ",") {
  211. return nil, httperrors.NewInputParameterError("invalid ports %s", input.Rules[i].Ports)
  212. }
  213. }
  214. return input, nil
  215. }
  216. func (self *SGoogleRegionDriver) RequestCreateSecurityGroup(
  217. ctx context.Context,
  218. userCred mcclient.TokenCredential,
  219. secgroup *models.SSecurityGroup,
  220. rules api.SSecgroupRuleResourceSet,
  221. ) error {
  222. vpc, err := secgroup.GetGlobalVpc()
  223. if err != nil {
  224. return errors.Wrapf(err, "GetVpc")
  225. }
  226. iVpc, err := vpc.GetICloudGlobalVpc(ctx)
  227. if err != nil {
  228. return errors.Wrapf(err, "GetICloudGlobalVpc")
  229. }
  230. opts := &cloudprovider.SecurityGroupCreateInput{
  231. Name: secgroup.Name,
  232. }
  233. opts.Tags, _ = secgroup.GetAllUserMetadata()
  234. iGroup, err := iVpc.CreateISecurityGroup(opts)
  235. if err != nil {
  236. return errors.Wrapf(err, "CreateISecurityGroup")
  237. }
  238. _, err = db.Update(secgroup, func() error {
  239. secgroup.ExternalId = iGroup.GetGlobalId()
  240. secgroup.VpcId = ""
  241. secgroup.CloudregionId = "-"
  242. return nil
  243. })
  244. if err != nil {
  245. return errors.Wrapf(err, "SetExternalId")
  246. }
  247. for i := range rules {
  248. opts := cloudprovider.SecurityGroupRuleCreateOptions{
  249. Desc: rules[i].Description,
  250. Direction: secrules.TSecurityRuleDirection(rules[i].Direction),
  251. Action: secrules.TSecurityRuleAction(rules[i].Action),
  252. Protocol: rules[i].Protocol,
  253. CIDR: rules[i].CIDR,
  254. Ports: rules[i].Ports,
  255. }
  256. _, err := iGroup.CreateRule(&opts)
  257. if err != nil {
  258. return errors.Wrapf(err, "CreateRule")
  259. }
  260. }
  261. iRules, err := iGroup.GetRules()
  262. if err != nil {
  263. return errors.Wrapf(err, "GetRules")
  264. }
  265. result := secgroup.SyncRules(ctx, userCred, iRules)
  266. if result.IsError() {
  267. return result.AllError()
  268. }
  269. secgroup.SetStatus(ctx, userCred, api.SECGROUP_STATUS_READY, "")
  270. return nil
  271. }
  272. func (self *SGoogleRegionDriver) ValidateUpdateSecurityGroupRuleInput(ctx context.Context, userCred mcclient.TokenCredential, input *api.SSecgroupRuleUpdateInput) (*api.SSecgroupRuleUpdateInput, error) {
  273. if input.Priority != nil && (*input.Priority < 0 || *input.Priority > 65535) {
  274. return nil, httperrors.NewInputParameterError("invalid priority %d, range 0-65535", *input.Priority)
  275. }
  276. if input.Ports != nil && strings.Contains(*input.Ports, ",") {
  277. return nil, httperrors.NewInputParameterError("invalid ports %s", *input.Ports)
  278. }
  279. return self.SManagedVirtualizationRegionDriver.ValidateUpdateSecurityGroupRuleInput(ctx, userCred, input)
  280. }
  281. func (self *SGoogleRegionDriver) GetSecurityGroupFilter(vpc *models.SVpc) (func(q *sqlchemy.SQuery) *sqlchemy.SQuery, error) {
  282. return func(q *sqlchemy.SQuery) *sqlchemy.SQuery {
  283. return q.Equals("globalvpc_id", vpc.GlobalvpcId)
  284. }, nil
  285. }
  286. func (self *SGoogleRegionDriver) RequestPrepareSecurityGroups(
  287. ctx context.Context,
  288. userCred mcclient.TokenCredential,
  289. ownerId mcclient.IIdentityProvider,
  290. secgroups []models.SSecurityGroup,
  291. vpc *models.SVpc,
  292. callback func(ids []string) error,
  293. task taskman.ITask,
  294. ) error {
  295. // 共享vpc不支持创建安全组
  296. if strings.HasPrefix(vpc.ExternalId, "projects/") {
  297. if callback != nil {
  298. err := callback([]string{})
  299. if err != nil {
  300. return errors.Wrapf(err, "callback")
  301. }
  302. }
  303. return task.ScheduleRun(nil)
  304. }
  305. return self.SManagedVirtualizationRegionDriver.RequestPrepareSecurityGroups(ctx, userCred, ownerId, secgroups, vpc, callback, task)
  306. }
  307. func (self *SGoogleRegionDriver) CreateDefaultSecurityGroup(
  308. ctx context.Context,
  309. userCred mcclient.TokenCredential,
  310. ownerId mcclient.IIdentityProvider,
  311. vpc *models.SVpc,
  312. ) (*models.SSecurityGroup, error) {
  313. newGroup := &models.SSecurityGroup{}
  314. newGroup.SetModelManager(models.SecurityGroupManager, newGroup)
  315. newGroup.Name = fmt.Sprintf("default-auto-%d", time.Now().Unix())
  316. newGroup.Description = "auto generage"
  317. newGroup.ManagerId = vpc.ManagerId
  318. newGroup.DomainId = ownerId.GetProjectDomainId()
  319. newGroup.ProjectSrc = string(apis.OWNER_SOURCE_LOCAL)
  320. newGroup.GlobalvpcId = vpc.GlobalvpcId
  321. newGroup.ProjectId = ownerId.GetProjectId()
  322. err := models.SecurityGroupManager.TableSpec().Insert(ctx, newGroup)
  323. if err != nil {
  324. return nil, errors.Wrapf(err, "insert")
  325. }
  326. region, err := vpc.GetRegion()
  327. if err != nil {
  328. return nil, errors.Wrapf(err, "GetRegion")
  329. }
  330. driver := region.GetDriver()
  331. err = driver.RequestCreateSecurityGroup(ctx, userCred, newGroup, api.SSecgroupRuleResourceSet{})
  332. if err != nil {
  333. return nil, errors.Wrapf(err, "RequestCreateSecurityGroup")
  334. }
  335. return newGroup, nil
  336. }