prometheus/retrieval/targetpool.go

94 lines
1.7 KiB
Go
Raw Normal View History

package retrieval
import (
2013-01-04 05:41:47 -08:00
"container/heap"
"github.com/matttproud/prometheus/retrieval/format"
2013-01-04 05:41:47 -08:00
"log"
"time"
)
2013-01-04 05:41:47 -08:00
type TargetPool struct {
done chan bool
targets []Target
2013-01-04 05:41:47 -08:00
manager TargetManager
}
func NewTargetPool(m TargetManager) (p *TargetPool) {
return &TargetPool{
manager: m,
}
2013-01-04 05:41:47 -08:00
}
func (p TargetPool) Len() int {
2013-01-04 05:41:47 -08:00
return len(p.targets)
}
func (p TargetPool) Less(i, j int) bool {
return p.targets[i].scheduledFor().Before(p.targets[j].scheduledFor())
}
func (p *TargetPool) Pop() interface{} {
2013-01-04 05:41:47 -08:00
oldPool := p.targets
futureLength := p.Len() - 1
element := oldPool[futureLength]
futurePool := oldPool[0:futureLength]
2013-01-04 05:41:47 -08:00
p.targets = futurePool
return element
}
func (p *TargetPool) Push(element interface{}) {
p.targets = append(p.targets, element.(Target))
}
func (p TargetPool) Swap(i, j int) {
2013-01-04 05:41:47 -08:00
p.targets[i], p.targets[j] = p.targets[j], p.targets[i]
}
func (p *TargetPool) Run(results chan format.Result, interval time.Duration) {
2013-01-04 05:41:47 -08:00
ticker := time.Tick(interval)
for {
select {
case <-ticker:
p.runIteration(results)
case <-p.done:
log.Printf("TargetPool exiting...")
break
}
}
}
func (p TargetPool) Stop() {
p.done <- true
}
func (p *TargetPool) runSingle(earliest time.Time, results chan format.Result, t Target) {
2013-01-04 05:41:47 -08:00
p.manager.acquire()
defer p.manager.release()
t.Scrape(earliest, results)
2013-01-04 05:41:47 -08:00
}
func (p *TargetPool) runIteration(results chan format.Result) {
2013-01-04 05:41:47 -08:00
for i := 0; i < p.Len(); i++ {
target := heap.Pop(p).(Target)
2013-01-04 05:41:47 -08:00
if target == nil {
break
}
now := time.Now()
if target.scheduledFor().After(now) {
2013-01-04 05:41:47 -08:00
heap.Push(p, target)
break
}
go func() {
p.runSingle(now, results, target)
2013-01-04 05:41:47 -08:00
heap.Push(p, target)
}()
}
}