elasticcache_acls.go 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459
  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 models
  15. import (
  16. "context"
  17. "fmt"
  18. "strings"
  19. "yunion.io/x/cloudmux/pkg/cloudprovider"
  20. "yunion.io/x/jsonutils"
  21. "yunion.io/x/log"
  22. "yunion.io/x/pkg/errors"
  23. "yunion.io/x/pkg/util/compare"
  24. "yunion.io/x/pkg/util/rbacscope"
  25. "yunion.io/x/sqlchemy"
  26. "yunion.io/x/onecloud/pkg/apis"
  27. api "yunion.io/x/onecloud/pkg/apis/compute"
  28. "yunion.io/x/onecloud/pkg/cloudcommon/db"
  29. "yunion.io/x/onecloud/pkg/cloudcommon/db/lockman"
  30. "yunion.io/x/onecloud/pkg/cloudcommon/db/taskman"
  31. "yunion.io/x/onecloud/pkg/cloudcommon/validators"
  32. "yunion.io/x/onecloud/pkg/httperrors"
  33. "yunion.io/x/onecloud/pkg/mcclient"
  34. "yunion.io/x/onecloud/pkg/util/stringutils2"
  35. )
  36. // +onecloud:swagger-gen-model-singular=elasticcacheacl
  37. // +onecloud:swagger-gen-model-plural=elasticcacheacls
  38. type SElasticcacheAclManager struct {
  39. db.SStandaloneResourceBaseManager
  40. db.SExternalizedResourceBaseManager
  41. SElasticcacheResourceBaseManager
  42. }
  43. var ElasticcacheAclManager *SElasticcacheAclManager
  44. func init() {
  45. ElasticcacheAclManager = &SElasticcacheAclManager{
  46. SStandaloneResourceBaseManager: db.NewStandaloneResourceBaseManager(
  47. SElasticcacheAcl{},
  48. "elasticcacheacls_tbl",
  49. "elasticcacheacl",
  50. "elasticcacheacls",
  51. ),
  52. }
  53. ElasticcacheAclManager.SetVirtualObject(ElasticcacheAclManager)
  54. }
  55. type SElasticcacheAcl struct {
  56. db.SStatusStandaloneResourceBase
  57. db.SExternalizedResourceBase
  58. SElasticcacheResourceBase `width:"36" charset:"ascii" nullable:"false" list:"user" create:"required" index:"true"`
  59. // ElasticcacheId string `width:"36" charset:"ascii" nullable:"false" list:"user" create:"required" index:"true"` // elastic cache instance id
  60. // Ip地址白名单列表
  61. IpList string `width:"256" charset:"ascii" nullable:"false" list:"user" update:"user" create:"required" json:"ip_list"`
  62. }
  63. func (manager *SElasticcacheAclManager) SyncElasticcacheAcls(ctx context.Context, userCred mcclient.TokenCredential, elasticcache *SElasticcache, cloudElasticcacheAcls []cloudprovider.ICloudElasticcacheAcl) compare.SyncResult {
  64. lockman.LockRawObject(ctx, "elastic-cache-acls", elasticcache.Id)
  65. defer lockman.ReleaseRawObject(ctx, "elastic-cache-acls", elasticcache.Id)
  66. syncResult := compare.SyncResult{}
  67. dbAcls, err := elasticcache.GetElasticcacheAcls()
  68. if err != nil {
  69. syncResult.Error(err)
  70. return syncResult
  71. }
  72. removed := make([]SElasticcacheAcl, 0)
  73. commondb := make([]SElasticcacheAcl, 0)
  74. commonext := make([]cloudprovider.ICloudElasticcacheAcl, 0)
  75. added := make([]cloudprovider.ICloudElasticcacheAcl, 0)
  76. if err := compare.CompareSets(dbAcls, cloudElasticcacheAcls, &removed, &commondb, &commonext, &added); err != nil {
  77. syncResult.Error(err)
  78. return syncResult
  79. }
  80. for i := 0; i < len(removed); i++ {
  81. err := removed[i].syncRemoveCloudElasticcacheAcl(ctx, userCred)
  82. if err != nil {
  83. syncResult.DeleteError(err)
  84. } else {
  85. syncResult.Delete()
  86. }
  87. }
  88. for i := 0; i < len(commondb); i++ {
  89. err := commondb[i].SyncWithCloudElasticcacheAcl(ctx, userCred, commonext[i])
  90. if err != nil {
  91. syncResult.UpdateError(err)
  92. continue
  93. }
  94. syncResult.Update()
  95. }
  96. for i := 0; i < len(added); i++ {
  97. _, err := manager.newFromCloudElasticcacheAcl(ctx, userCred, elasticcache, added[i])
  98. if err != nil {
  99. syncResult.AddError(err)
  100. continue
  101. }
  102. syncResult.Add()
  103. }
  104. return syncResult
  105. }
  106. func (self *SElasticcacheAcl) syncRemoveCloudElasticcacheAcl(ctx context.Context, userCred mcclient.TokenCredential) error {
  107. lockman.LockObject(ctx, self)
  108. defer lockman.ReleaseObject(ctx, self)
  109. err := self.ValidateDeleteCondition(ctx, nil)
  110. if err != nil {
  111. return errors.Wrapf(err, "newFromCloudElasticcacheAcl.Remove")
  112. }
  113. return self.Delete(ctx, userCred)
  114. }
  115. func (self *SElasticcacheAcl) SyncWithCloudElasticcacheAcl(ctx context.Context, userCred mcclient.TokenCredential, extAcl cloudprovider.ICloudElasticcacheAcl) error {
  116. _, err := db.UpdateWithLock(ctx, self, func() error {
  117. self.IpList = extAcl.GetIpList()
  118. self.Status = extAcl.GetStatus()
  119. return nil
  120. })
  121. if err != nil {
  122. return errors.Wrapf(err, "SyncWithCloudElasticcacheAcl.UpdateWithLock")
  123. }
  124. return nil
  125. }
  126. func (manager *SElasticcacheAclManager) newFromCloudElasticcacheAcl(ctx context.Context, userCred mcclient.TokenCredential, elasticcache *SElasticcache, extAcl cloudprovider.ICloudElasticcacheAcl) (*SElasticcacheAcl, error) {
  127. lockman.LockClass(ctx, manager, db.GetLockClassKey(manager, userCred))
  128. defer lockman.ReleaseClass(ctx, manager, db.GetLockClassKey(manager, userCred))
  129. acl := SElasticcacheAcl{}
  130. acl.SetModelManager(manager, &acl)
  131. acl.ElasticcacheId = elasticcache.GetId()
  132. acl.Status = extAcl.GetStatus()
  133. acl.Name = extAcl.GetName()
  134. acl.ExternalId = extAcl.GetGlobalId()
  135. acl.IpList = extAcl.GetIpList()
  136. err := manager.TableSpec().Insert(ctx, &acl)
  137. if err != nil {
  138. return nil, errors.Wrapf(err, "newFromCloudElasticcacheAcl.Insert")
  139. }
  140. return &acl, nil
  141. }
  142. func (self *SElasticcacheAcl) GetUniqValues() jsonutils.JSONObject {
  143. return jsonutils.Marshal(map[string]string{"elasticcache_id": self.ElasticcacheId})
  144. }
  145. func (manager *SElasticcacheAclManager) FetchUniqValues(ctx context.Context, data jsonutils.JSONObject) jsonutils.JSONObject {
  146. elasticcacheId := jsonutils.GetAnyString(data, []string{"elasticcache_id", "elasticcache"})
  147. return jsonutils.Marshal(map[string]string{"elasticcache_id": elasticcacheId})
  148. }
  149. func (manager *SElasticcacheAclManager) ResourceScope() rbacscope.TRbacScope {
  150. return rbacscope.ScopeProject
  151. }
  152. func (manager *SElasticcacheAclManager) FetchOwnerId(ctx context.Context, data jsonutils.JSONObject) (mcclient.IIdentityProvider, error) {
  153. return elasticcacheSubResourceFetchOwnerId(ctx, data)
  154. }
  155. func (manager *SElasticcacheAclManager) FilterByOwner(ctx context.Context, q *sqlchemy.SQuery, man db.FilterByOwnerProvider, userCred mcclient.TokenCredential, ownerId mcclient.IIdentityProvider, scope rbacscope.TRbacScope) *sqlchemy.SQuery {
  156. return elasticcacheSubResourceFetchOwner(ctx, q, ownerId, scope)
  157. }
  158. func (manager *SElasticcacheAclManager) FilterByUniqValues(q *sqlchemy.SQuery, values jsonutils.JSONObject) *sqlchemy.SQuery {
  159. cacheId, _ := values.GetString("elasticcache_id")
  160. if len(cacheId) > 0 {
  161. q = q.Equals("elasticcache_id", cacheId)
  162. }
  163. return q
  164. }
  165. func (manager *SElasticcacheAclManager) ValidateCreateData(ctx context.Context, userCred mcclient.TokenCredential, ownerId mcclient.IIdentityProvider, query jsonutils.JSONObject, data *jsonutils.JSONDict) (*jsonutils.JSONDict, error) {
  166. var region *SCloudregion
  167. if id, _ := data.GetString("elasticcache"); len(id) > 0 {
  168. ec, err := db.FetchByIdOrName(ctx, ElasticcacheManager, userCred, id)
  169. if err != nil {
  170. return nil, fmt.Errorf("getting elastic cache instance failed")
  171. }
  172. region, _ = ec.(*SElasticcache).GetRegion()
  173. if region == nil {
  174. return nil, fmt.Errorf("getting elastic cache region failed")
  175. }
  176. } else {
  177. return nil, httperrors.NewMissingParameterError("elasticcache")
  178. }
  179. input := apis.StandaloneResourceCreateInput{}
  180. var err error
  181. err = data.Unmarshal(&input)
  182. if err != nil {
  183. return nil, httperrors.NewInternalServerError("unmarshal StandaloneResourceCreateInput fail %s", err)
  184. }
  185. input, err = manager.SStandaloneResourceBaseManager.ValidateCreateData(ctx, userCred, ownerId, query, input)
  186. if err != nil {
  187. return nil, err
  188. }
  189. data.Update(jsonutils.Marshal(input))
  190. return region.GetDriver().ValidateCreateElasticcacheAclData(ctx, userCred, ownerId, data)
  191. }
  192. func (self *SElasticcacheAcl) GetOwnerId() mcclient.IIdentityProvider {
  193. return ElasticcacheManager.GetOwnerIdByElasticcacheId(self.ElasticcacheId)
  194. }
  195. func (self *SElasticcacheAcl) PostCreate(ctx context.Context, userCred mcclient.TokenCredential, ownerId mcclient.IIdentityProvider, query jsonutils.JSONObject, data jsonutils.JSONObject) {
  196. self.SStandaloneResourceBase.PostCreate(ctx, userCred, ownerId, query, data)
  197. self.SetStatus(ctx, userCred, api.ELASTIC_CACHE_ACL_STATUS_CREATING, "")
  198. if err := self.StartElasticcacheAclCreateTask(ctx, userCred, data.(*jsonutils.JSONDict), ""); err != nil {
  199. log.Errorf("Failed to create elastic cache acl error: %v", err)
  200. }
  201. }
  202. func (self *SElasticcacheAcl) StartElasticcacheAclCreateTask(ctx context.Context, userCred mcclient.TokenCredential, data *jsonutils.JSONDict, parentTaskId string) error {
  203. task, err := taskman.TaskManager.NewTask(ctx, "ElasticcacheAclCreateTask", self, userCred, jsonutils.NewDict(), parentTaskId, "", nil)
  204. if err != nil {
  205. return err
  206. }
  207. task.ScheduleRun(nil)
  208. return nil
  209. }
  210. func (self *SElasticcacheAcl) GetRegion() *SCloudregion {
  211. ieb, err := db.FetchById(ElasticcacheManager, self.ElasticcacheId)
  212. if err != nil {
  213. return nil
  214. }
  215. region, _ := ieb.(*SElasticcache).GetRegion()
  216. return region
  217. }
  218. func (self *SElasticcacheAcl) ValidateUpdateData(ctx context.Context, userCred mcclient.TokenCredential, query jsonutils.JSONObject, data *jsonutils.JSONDict) (*jsonutils.JSONDict, error) {
  219. ips, err := data.GetString("ip_list")
  220. if err != nil || ips == "" {
  221. return nil, httperrors.NewMissingParameterError("ip_list")
  222. }
  223. ipV := validators.NewIPv4AddrValidator("ip")
  224. cidrV := validators.NewIPv4PrefixValidator("ip")
  225. _ips := strings.Split(ips, ",")
  226. for _, ip := range _ips {
  227. params := jsonutils.NewDict()
  228. params.Set("ip", jsonutils.NewString(ip))
  229. if strings.Contains(ip, "/") {
  230. if err := cidrV.Validate(ctx, params); err != nil {
  231. return nil, err
  232. }
  233. } else {
  234. if err := ipV.Validate(ctx, params); err != nil {
  235. return nil, err
  236. }
  237. }
  238. }
  239. return data, nil
  240. }
  241. func (self *SElasticcacheAcl) PostUpdate(ctx context.Context, userCred mcclient.TokenCredential, query jsonutils.JSONObject, data jsonutils.JSONObject) {
  242. self.SetStatus(ctx, userCred, api.ELASTIC_CACHE_ACL_STATUS_UPDATING, "")
  243. if err := self.StartUpdateElasticcacheAclTask(ctx, userCred, data.(*jsonutils.JSONDict), ""); err != nil {
  244. log.Errorf("ElasticcacheAcl %s", err.Error())
  245. }
  246. return
  247. }
  248. func (self *SElasticcacheAcl) StartUpdateElasticcacheAclTask(ctx context.Context, userCred mcclient.TokenCredential, params *jsonutils.JSONDict, parentTaskId string) error {
  249. task, err := taskman.TaskManager.NewTask(ctx, "ElasticcacheAclUpdateTask", self, userCred, params, parentTaskId, "", nil)
  250. if err != nil {
  251. return err
  252. }
  253. task.ScheduleRun(nil)
  254. return nil
  255. }
  256. func (self *SElasticcacheAcl) ValidateDeleteCondition(ctx context.Context, info jsonutils.JSONObject) error {
  257. return nil
  258. }
  259. func (self *SElasticcacheAcl) CustomizeDelete(ctx context.Context, userCred mcclient.TokenCredential, query jsonutils.JSONObject, data jsonutils.JSONObject) error {
  260. self.SetStatus(ctx, userCred, api.ELASTIC_CACHE_ACL_STATUS_DELETING, "")
  261. return self.StartDeleteElasticcacheAclTask(ctx, userCred, jsonutils.NewDict(), "")
  262. }
  263. func (self *SElasticcacheAcl) StartDeleteElasticcacheAclTask(ctx context.Context, userCred mcclient.TokenCredential, params *jsonutils.JSONDict, parentTaskId string) error {
  264. task, err := taskman.TaskManager.NewTask(ctx, "ElasticcacheAclDeleteTask", self, userCred, params, parentTaskId, "", nil)
  265. if err != nil {
  266. return err
  267. }
  268. task.ScheduleRun(nil)
  269. return nil
  270. }
  271. func (self *SElasticcacheAcl) Delete(ctx context.Context, userCred mcclient.TokenCredential) error {
  272. return nil
  273. }
  274. // 弹性缓存ACL规则列表
  275. func (manager *SElasticcacheAclManager) ListItemFilter(
  276. ctx context.Context,
  277. q *sqlchemy.SQuery,
  278. userCred mcclient.TokenCredential,
  279. input api.ElasticcacheAclListInput,
  280. ) (*sqlchemy.SQuery, error) {
  281. var err error
  282. q, err = manager.SStandaloneResourceBaseManager.ListItemFilter(ctx, q, userCred, input.StandaloneResourceListInput)
  283. if err != nil {
  284. return nil, errors.Wrap(err, "SStandaloneResourceBaseManager.ListItemFilter")
  285. }
  286. q, err = manager.SExternalizedResourceBaseManager.ListItemFilter(ctx, q, userCred, input.ExternalizedResourceBaseListInput)
  287. if err != nil {
  288. return nil, errors.Wrap(err, "SExternalizedResourceBaseManager.ListItemFilter")
  289. }
  290. q, err = manager.SElasticcacheResourceBaseManager.ListItemFilter(ctx, q, userCred, input.ElasticcacheFilterListInput)
  291. if err != nil {
  292. return nil, errors.Wrap(err, "SElasticcacheResourceBaseManager.ListItemFilter")
  293. }
  294. if len(input.IpList) > 0 {
  295. q = q.Contains("ip_list", input.IpList)
  296. }
  297. return q, nil
  298. }
  299. func (manager *SElasticcacheAclManager) OrderByExtraFields(
  300. ctx context.Context,
  301. q *sqlchemy.SQuery,
  302. userCred mcclient.TokenCredential,
  303. input api.ElasticcacheAclListInput,
  304. ) (*sqlchemy.SQuery, error) {
  305. var err error
  306. q, err = manager.SStandaloneResourceBaseManager.OrderByExtraFields(ctx, q, userCred, input.StandaloneResourceListInput)
  307. if err != nil {
  308. return nil, errors.Wrap(err, "SStandaloneResourceBaseManager.OrderByExtraFields")
  309. }
  310. q, err = manager.SElasticcacheResourceBaseManager.OrderByExtraFields(ctx, q, userCred, input.ElasticcacheFilterListInput)
  311. if err != nil {
  312. return nil, errors.Wrap(err, "SElasticcacheResourceBaseManager.OrderByExtraFields")
  313. }
  314. return q, nil
  315. }
  316. func (manager *SElasticcacheAclManager) QueryDistinctExtraField(q *sqlchemy.SQuery, field string) (*sqlchemy.SQuery, error) {
  317. var err error
  318. q, err = manager.SStandaloneResourceBaseManager.QueryDistinctExtraField(q, field)
  319. if err == nil {
  320. return q, nil
  321. }
  322. q, err = manager.SElasticcacheResourceBaseManager.QueryDistinctExtraField(q, field)
  323. if err == nil {
  324. return q, nil
  325. }
  326. return q, httperrors.ErrNotFound
  327. }
  328. func (manager *SElasticcacheAclManager) FetchCustomizeColumns(
  329. ctx context.Context,
  330. userCred mcclient.TokenCredential,
  331. query jsonutils.JSONObject,
  332. objs []interface{},
  333. fields stringutils2.SSortedStrings,
  334. isList bool,
  335. ) []api.ElasticcacheAclDetails {
  336. rows := make([]api.ElasticcacheAclDetails, len(objs))
  337. stdRows := manager.SStandaloneResourceBaseManager.FetchCustomizeColumns(ctx, userCred, query, objs, fields, isList)
  338. elasticRows := manager.SElasticcacheResourceBaseManager.FetchCustomizeColumns(ctx, userCred, query, objs, fields, isList)
  339. cacheIds := make([]string, len(objs))
  340. for i := range rows {
  341. rows[i] = api.ElasticcacheAclDetails{
  342. StandaloneResourceDetails: stdRows[i],
  343. ElasticcacheResourceInfo: elasticRows[i],
  344. }
  345. acl := objs[i].(*SElasticcacheAcl)
  346. cacheIds[i] = acl.ElasticcacheId
  347. }
  348. caches := make(map[string]SElasticcache)
  349. err := db.FetchStandaloneObjectsByIds(ElasticcacheManager, cacheIds, &caches)
  350. if err != nil {
  351. log.Errorf("FetchStandaloneObjectsByIds fail: %v", err)
  352. return rows
  353. }
  354. virObjs := make([]interface{}, len(objs))
  355. for i := range rows {
  356. if cache, ok := caches[cacheIds[i]]; ok {
  357. virObjs[i] = &cache
  358. rows[i].ProjectId = cache.ProjectId
  359. }
  360. }
  361. projRows := ElasticcacheManager.SProjectizedResourceBaseManager.FetchCustomizeColumns(ctx, userCred, query, virObjs, fields, isList)
  362. for i := range rows {
  363. rows[i].ProjectizedResourceInfo = projRows[i]
  364. }
  365. return rows
  366. }
  367. func (manager *SElasticcacheAclManager) ListItemExportKeys(ctx context.Context,
  368. q *sqlchemy.SQuery,
  369. userCred mcclient.TokenCredential,
  370. keys stringutils2.SSortedStrings,
  371. ) (*sqlchemy.SQuery, error) {
  372. var err error
  373. q, err = manager.SStandaloneResourceBaseManager.ListItemExportKeys(ctx, q, userCred, keys)
  374. if err != nil {
  375. return nil, errors.Wrap(err, "SStatusStandaloneResourceBaseManager.ListItemExportKeys")
  376. }
  377. if keys.ContainsAny(manager.SElasticcacheResourceBaseManager.GetExportKeys()...) {
  378. q, err = manager.SElasticcacheResourceBaseManager.ListItemExportKeys(ctx, q, userCred, keys)
  379. if err != nil {
  380. return nil, errors.Wrap(err, "SElasticcacheResourceBaseManager.ListItemExportKeys")
  381. }
  382. }
  383. return q, nil
  384. }