group_manager.go 1.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758
  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 cache
  15. import (
  16. "fmt"
  17. "yunion.io/x/log"
  18. )
  19. type GroupManager struct {
  20. Group map[string]Cache
  21. stopCh <-chan struct{}
  22. }
  23. func NewGroupManager(kind string, items []CachedItem, ch <-chan struct{}) *GroupManager {
  24. man := new(GroupManager)
  25. man.Group = make(map[string]Cache)
  26. man.stopCh = ch
  27. for _, item := range items {
  28. man.Group[item.Name()] = NewCache(kind, item)
  29. }
  30. return man
  31. }
  32. func (m *GroupManager) Run() {
  33. go func() {
  34. m.run()
  35. select {}
  36. }()
  37. }
  38. func (m *GroupManager) run() {
  39. for name, c := range m.Group {
  40. log.V(3).Infof("Start cache: %v", name)
  41. c.Start(m.stopCh)
  42. }
  43. }
  44. func (m *GroupManager) Get(name string) (Cache, error) {
  45. entity, ok := m.Group[name]
  46. if !ok {
  47. return nil, fmt.Errorf("DB cache item: %s not found", name)
  48. }
  49. return entity, nil
  50. }