You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 

79 lines
2.2 KiB

  1. // Copyright 2019, OpenCensus Authors
  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 metricproducer
  15. import (
  16. "sync"
  17. )
  18. // Manager maintains a list of active producers. Producers can register
  19. // with the manager to allow readers to read all metrics provided by them.
  20. // Readers can retrieve all producers registered with the manager,
  21. // read metrics from the producers and export them.
  22. type Manager struct {
  23. mu sync.RWMutex
  24. producers map[Producer]struct{}
  25. }
  26. var prodMgr *Manager
  27. var once sync.Once
  28. // GlobalManager is a single instance of producer manager
  29. // that is used by all producers and all readers.
  30. func GlobalManager() *Manager {
  31. once.Do(func() {
  32. prodMgr = &Manager{}
  33. prodMgr.producers = make(map[Producer]struct{})
  34. })
  35. return prodMgr
  36. }
  37. // AddProducer adds the producer to the Manager if it is not already present.
  38. func (pm *Manager) AddProducer(producer Producer) {
  39. if producer == nil {
  40. return
  41. }
  42. pm.mu.Lock()
  43. defer pm.mu.Unlock()
  44. pm.producers[producer] = struct{}{}
  45. }
  46. // DeleteProducer deletes the producer from the Manager if it is present.
  47. func (pm *Manager) DeleteProducer(producer Producer) {
  48. if producer == nil {
  49. return
  50. }
  51. pm.mu.Lock()
  52. defer pm.mu.Unlock()
  53. delete(pm.producers, producer)
  54. }
  55. // GetAll returns a slice of all producer currently registered with
  56. // the Manager. For each call it generates a new slice. The slice
  57. // should not be cached as registration may change at any time. It is
  58. // typically called periodically by exporter to read metrics from
  59. // the producers.
  60. func (pm *Manager) GetAll() []Producer {
  61. pm.mu.Lock()
  62. defer pm.mu.Unlock()
  63. producers := make([]Producer, len(pm.producers))
  64. i := 0
  65. for producer := range pm.producers {
  66. producers[i] = producer
  67. i++
  68. }
  69. return producers
  70. }