1
0
mirror of https://github.com/newnius/YAO-scheduler.git synced 2025-06-07 14:21:55 +00:00
YAO-scheduler/src/collector.go

73 lines
1.4 KiB
Go
Raw Normal View History

2019-03-04 09:19:55 +00:00
package main
import (
"sync"
"github.com/Shopify/sarama"
"encoding/json"
2019-07-10 12:40:43 +00:00
"time"
2019-04-29 09:05:15 +00:00
)
2019-03-04 09:19:55 +00:00
2020-05-24 13:07:02 +00:00
var collectorInstance *Collector
var collectorInstanceLock sync.Mutex
2019-03-04 09:19:55 +00:00
2020-05-25 03:35:44 +00:00
func InstanceOfCollector() *Collector {
2020-05-24 13:07:02 +00:00
defer collectorInstanceLock.Unlock()
collectorInstanceLock.Lock()
2019-03-04 09:19:55 +00:00
2020-05-24 13:07:02 +00:00
if collectorInstance == nil {
collectorInstance = &Collector{}
2019-03-04 09:19:55 +00:00
}
2020-05-24 13:07:02 +00:00
return collectorInstance
}
type Collector struct {
wg sync.WaitGroup
}
func (collector *Collector) init(conf Configuration) {
go func() {
consumer, err := sarama.NewConsumer(conf.KafkaBrokers, nil)
for {
if err == nil {
break
}
log.Warn(err)
time.Sleep(time.Second * 5)
consumer, err = sarama.NewConsumer(conf.KafkaBrokers, nil)
}
2019-03-04 09:19:55 +00:00
2020-05-24 13:07:02 +00:00
partitionList, err := consumer.Partitions(conf.KafkaTopic)
2019-03-04 09:19:55 +00:00
if err != nil {
panic(err)
}
2020-05-24 13:07:02 +00:00
for partition := range partitionList {
pc, err := consumer.ConsumePartition(conf.KafkaTopic, int32(partition), sarama.OffsetNewest)
if err != nil {
panic(err)
2019-03-04 09:19:55 +00:00
}
2020-05-24 13:07:02 +00:00
defer pc.AsyncClose()
2019-03-04 09:19:55 +00:00
2020-05-24 13:07:02 +00:00
collector.wg.Add(1)
go func(sarama.PartitionConsumer) {
defer collector.wg.Done()
for msg := range pc.Messages() {
2020-05-26 01:42:06 +00:00
go func(msg *sarama.ConsumerMessage) {
var nodeStatus NodeStatus
err = json.Unmarshal([]byte(string(msg.Value)), &nodeStatus)
if err != nil {
log.Warn(err)
return
}
InstanceOfResourcePool().update(nodeStatus)
}(msg)
2020-05-24 13:07:02 +00:00
}
}(pc)
}
collector.wg.Wait()
consumer.Close()
}()
2019-03-04 09:19:55 +00:00
}