github.com/timstclair/heapster@v0.20.0-alpha1/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 "k8s.io/heapster/events/core" 21 22 "github.com/golang/glog" 23 ) 24 25 type Manager interface { 26 Start() 27 Stop() 28 } 29 30 type realManager struct { 31 source core.EventSource 32 sink core.EventSink 33 frequency time.Duration 34 stopChan chan struct{} 35 } 36 37 func NewManager(source core.EventSource, sink core.EventSink, frequency time.Duration) (Manager, error) { 38 manager := realManager{ 39 source: source, 40 sink: sink, 41 frequency: frequency, 42 stopChan: make(chan struct{}), 43 } 44 45 return &manager, nil 46 } 47 48 func (rm *realManager) Start() { 49 go rm.Housekeep() 50 } 51 52 func (rm *realManager) Stop() { 53 rm.stopChan <- struct{}{} 54 } 55 56 func (rm *realManager) Housekeep() { 57 for { 58 // Try to infovke housekeep at fixed time. 59 now := time.Now() 60 start := now.Truncate(rm.frequency) 61 end := start.Add(rm.frequency) 62 timeToNextSync := end.Sub(now) 63 64 select { 65 case <-time.After(timeToNextSync): 66 rm.housekeep() 67 case <-rm.stopChan: 68 rm.sink.Stop() 69 return 70 } 71 } 72 } 73 74 func (rm *realManager) housekeep() { 75 // No parallelism. Assumes that the events are pushed to Heapster. Add paralellism 76 // when this stops to be true. 77 events := rm.source.GetNewEvents() 78 glog.V(0).Infof("Exporting %d events", len(events.Events)) 79 rm.sink.ExportEvents(events) 80 }