helper.go 2.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576
  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. "yunion.io/x/jsonutils"
  18. "yunion.io/x/pkg/errors"
  19. identityapi "yunion.io/x/onecloud/pkg/apis/identity"
  20. "yunion.io/x/onecloud/pkg/cloudcommon/consts"
  21. "yunion.io/x/onecloud/pkg/cloudcommon/db"
  22. "yunion.io/x/onecloud/pkg/mcclient/auth"
  23. "yunion.io/x/onecloud/pkg/mcclient/modules/identity"
  24. )
  25. func FetchAllRemoteDomainProjects(ctx context.Context) ([]*db.STenant, []*db.STenant, error) {
  26. s := auth.GetAdminSession(ctx, consts.GetRegion())
  27. projects := make([]*db.STenant, 0)
  28. domains := make([]*db.STenant, 0)
  29. var count int
  30. domainMap := make(map[string]string, 0)
  31. for {
  32. listParam := jsonutils.NewDict()
  33. listParam.Add(jsonutils.NewString("system"), "scope")
  34. listParam.Add(jsonutils.NewInt(20), "limit")
  35. listParam.Add(jsonutils.NewInt(int64(count)), "offset")
  36. listParam.Add(jsonutils.JSONTrue, "details")
  37. result, err := identity.Projects.List(s, listParam)
  38. if err != nil {
  39. return domains, projects, errors.Wrap(err, "list projects from keystone")
  40. }
  41. for _, data := range result.Data {
  42. item := db.SCachedTenant{}
  43. data.Unmarshal(&item)
  44. project, err := db.TenantCacheManager.Save(ctx, item, true)
  45. if err != nil {
  46. return nil, nil, errors.Wrapf(err, "save project %s to cache", data.String())
  47. }
  48. projects = append(projects, project)
  49. domainMap[item.DomainId] = item.ProjectDomain
  50. }
  51. total := result.Total
  52. count = count + len(result.Data)
  53. if count >= total {
  54. break
  55. }
  56. }
  57. for domainId, domainName := range domainMap {
  58. item := db.SCachedTenant{
  59. Id: domainId,
  60. Name: domainName,
  61. DomainId: identityapi.KeystoneDomainRoot,
  62. ProjectDomain: identityapi.KeystoneDomainRoot,
  63. }
  64. domain, err := db.TenantCacheManager.Save(ctx, item, false)
  65. if err != nil {
  66. return nil, nil, errors.Wrapf(err, "save domain %s:%s to cache", domainId, domainName)
  67. }
  68. domains = append(domains, domain)
  69. }
  70. return domains, projects, nil
  71. }