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