session_cache.go 1.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172
  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 auth
  15. import (
  16. "context"
  17. "sync"
  18. "time"
  19. "yunion.io/x/onecloud/pkg/mcclient"
  20. )
  21. type SessionCache struct {
  22. mu sync.RWMutex
  23. session *mcclient.ClientSession
  24. Region string
  25. // APIVersion string
  26. // EarlyRefresh tells the cache how early to fetch a new session before
  27. // actual expiration of the old
  28. EarlyRefresh time.Duration
  29. Token mcclient.TokenCredential
  30. UseAdminToken bool
  31. }
  32. func (sc *SessionCache) getToken() mcclient.TokenCredential {
  33. if sc.Token != nil {
  34. return sc.Token
  35. }
  36. if sc.UseAdminToken {
  37. return manager.adminCredential
  38. }
  39. return nil
  40. }
  41. func (sc *SessionCache) Get(ctx context.Context) *mcclient.ClientSession {
  42. mu := &sc.mu
  43. {
  44. mu.RLock()
  45. s := sc.session
  46. mu.RUnlock()
  47. if s != nil {
  48. token := s.GetToken()
  49. expires := token.GetExpires()
  50. if time.Now().Add(sc.EarlyRefresh).After(expires) {
  51. return s
  52. }
  53. }
  54. }
  55. mu.Lock()
  56. defer mu.Unlock()
  57. token := sc.getToken()
  58. sc.session = GetSession(ctx, token, sc.Region)
  59. return sc.session
  60. }