default_admin.go 2.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677
  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/log"
  18. api "yunion.io/x/onecloud/pkg/apis/identity"
  19. "yunion.io/x/onecloud/pkg/keystone/options"
  20. "yunion.io/x/onecloud/pkg/mcclient"
  21. )
  22. var (
  23. defaultAdminCred mcclient.TokenCredential
  24. defaultClient *mcclient.Client = nil
  25. )
  26. func GetDefaultClient() *mcclient.Client {
  27. if defaultClient == nil {
  28. defaultClient = mcclient.NewClient("", 300, options.Options.DebugClient, true, "", "")
  29. refreshDefaultClientServiceCatalog()
  30. }
  31. return defaultClient
  32. }
  33. func refreshDefaultClientServiceCatalog() {
  34. cata, err := EndpointManager.FetchAll()
  35. if err != nil {
  36. log.Fatalf("fail to fetch endpoints")
  37. }
  38. defaultClient.SetServiceCatalog(cata.GetKeystoneCatalogV3())
  39. }
  40. func GetDefaultAdminCred() mcclient.TokenCredential {
  41. if defaultAdminCred == nil {
  42. defaultAdminCred = getDefaultAdminCred()
  43. }
  44. return defaultAdminCred
  45. }
  46. func getDefaultAdminCred() *mcclient.SSimpleToken {
  47. token := mcclient.SSimpleToken{}
  48. usr, _ := UserManager.FetchUserExtended("", api.SystemAdminUser, api.DEFAULT_DOMAIN_ID, "")
  49. token.UserId = usr.Id
  50. token.User = usr.Name
  51. token.DomainId = usr.DomainId
  52. token.Domain = usr.DomainName
  53. prj, _ := ProjectManager.FetchProject("", api.SystemAdminProject, api.DEFAULT_DOMAIN_ID, "")
  54. token.ProjectId = prj.Id
  55. token.Project = prj.Name
  56. token.ProjectDomainId = prj.DomainId
  57. token.ProjectDomain = prj.GetDomain().Name
  58. rol, _ := RoleManager.FetchRole("", api.SystemAdminRole, api.DEFAULT_DOMAIN_ID, "")
  59. token.Roles = rol.Name
  60. token.SystemAccount = true
  61. token.RoleIds = rol.Id
  62. return &token
  63. }
  64. func GetDefaultClientSession(ctx context.Context, token mcclient.TokenCredential, region string) *mcclient.ClientSession {
  65. return GetDefaultClient().NewSession(ctx, region, "", "", token)
  66. }