github.com/aclisp/heapster@v0.19.2-0.20160613100040-51756f899a96/events/manager/manager.go (about) 1 // Copyright 2015 Google Inc. All Rights Reserved. 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 manager 16 17 import ( 18 "time" 19 20 "github.com/golang/glog" 21 "github.com/prometheus/client_golang/prometheus" 22 "k8s.io/heapster/events/core" 23 ) 24 25 var ( 26 // Last time of eventer housekeep since unix epoch in seconds 27 lastHousekeepTimestamp = prometheus.NewGauge( 28 prometheus.GaugeOpts{ 29 Namespace: "eventer", 30 Subsystem: "manager", 31 Name: "last_time_seconds", 32 Help: "Last time of eventer housekeep since unix epoch in seconds.", 33 }) 34 ) 35 36 func init() { 37 prometheus.MustRegister(lastHousekeepTimestamp) 38 } 39 40 type Manager interface { 41 Start() 42 Stop() 43 } 44 45 type realManager struct { 46 source core.EventSource 47 sink core.EventSink 48 frequency time.Duration 49 stopChan chan struct{} 50 } 51 52 func NewManager(source core.EventSource, sink core.EventSink, frequency time.Duration) (Manager, error) { 53 manager := realManager{ 54 source: source, 55 sink: sink, 56 frequency: frequency, 57 stopChan: make(chan struct{}), 58 } 59 60 return &manager, nil 61 } 62 63 func (rm *realManager) Start() { 64 go rm.Housekeep() 65 } 66 67 func (rm *realManager) Stop() { 68 rm.stopChan <- struct{}{} 69 } 70 71 func (rm *realManager) Housekeep() { 72 for { 73 // Try to infovke housekeep at fixed time. 74 now := time.Now() 75 start := now.Truncate(rm.frequency) 76 end := start.Add(rm.frequency) 77 timeToNextSync := end.Sub(now) 78 79 select { 80 case <-time.After(timeToNextSync): 81 rm.housekeep() 82 case <-rm.stopChan: 83 rm.sink.Stop() 84 return 85 } 86 } 87 } 88 89 func (rm *realManager) housekeep() { 90 defer lastHousekeepTimestamp.Set(float64(time.Now().Unix())) 91 92 // No parallelism. Assumes that the events are pushed to Heapster. Add paralellism 93 // when this stops to be true. 94 events := rm.source.GetNewEvents() 95 glog.V(0).Infof("Exporting %d events", len(events.Events)) 96 rm.sink.ExportEvents(events) 97 }