133 lines
2.5 KiB
Go
133 lines
2.5 KiB
Go
package long_poller_go
|
|
|
|
import (
|
|
"context"
|
|
"google.golang.org/grpc"
|
|
cm "loafle.com/overflow/agent_api/config_manager"
|
|
pb "loafle.com/overflow/crawler_go/grpc" //temp
|
|
s "loafle.com/overflow/scheduler_go"
|
|
"log"
|
|
"strconv"
|
|
"sync"
|
|
)
|
|
|
|
const (
|
|
POLLING_ID = "OVERFLOW_LONG_POLLING"
|
|
)
|
|
|
|
var (
|
|
instance *Poller
|
|
once sync.Once
|
|
)
|
|
|
|
type Poller struct {
|
|
once sync.Once
|
|
runStat chan bool
|
|
gconf *cm.GlobalConfig
|
|
scheduler *s.Scheduler
|
|
taskCh chan interface{}
|
|
}
|
|
|
|
func Start(conf *cm.GlobalConfig) (chan interface{}, error) {
|
|
p := GetInstance()
|
|
p.taskCh = make(chan interface{})
|
|
err := p.startPolling(conf)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
return p.taskCh, nil
|
|
}
|
|
|
|
func GetInstance() *Poller {
|
|
once.Do(func() {
|
|
instance = &Poller{}
|
|
})
|
|
return instance
|
|
}
|
|
|
|
func (p *Poller) startPolling(conf *cm.GlobalConfig) error {
|
|
p.gconf = conf
|
|
p.scheduler = &s.Scheduler{}
|
|
p.scheduler.Start()
|
|
|
|
err := p.scheduler.NewSchedule(POLLING_ID, uint64(p.gconf.IntervalSecond), p.polling)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
return nil
|
|
}
|
|
|
|
func (p *Poller) handleInterval(ch chan interface{}) {
|
|
go func() {
|
|
data := <-ch
|
|
interval := data.(string)
|
|
i, err := strconv.Atoi(interval)
|
|
if err != nil {
|
|
log.Println(err)
|
|
return
|
|
}
|
|
p.scheduler.UpdateInterval(POLLING_ID, uint64(i))
|
|
}()
|
|
}
|
|
|
|
func (p *Poller) Stop(ch chan interface{}) {
|
|
p.scheduler.Stop()
|
|
p.runStat <- false
|
|
}
|
|
|
|
func (p *Poller) polling(agentId string) {
|
|
|
|
addr := p.gconf.Central.Address + ":" + string(p.gconf.Central.Port)
|
|
conn, err := grpc.Dial(addr, grpc.WithInsecure())
|
|
if err != nil {
|
|
log.Println(err)
|
|
return
|
|
}
|
|
defer conn.Close()
|
|
|
|
//todo temporary
|
|
client := pb.NewStatusClient(conn)
|
|
|
|
//printStatusStream(client) //stream
|
|
|
|
out, err := client.Status(context.Background(), &pb.Empty{})
|
|
if err != nil {
|
|
log.Println(err)
|
|
}
|
|
p.dispatchNotify(out)
|
|
}
|
|
|
|
func (p *Poller) dispatchNotify(result interface{}) {
|
|
log.Printf("Polling result - %s ", result)
|
|
p.taskCh <- result
|
|
}
|
|
|
|
func (p *Poller) updateInterval(interval string) {
|
|
i, err := strconv.Atoi(interval)
|
|
if err != nil {
|
|
log.Println(err)
|
|
return
|
|
}
|
|
p.scheduler.UpdateInterval(POLLING_ID, uint64(i))
|
|
}
|
|
|
|
/*
|
|
func printStatusStream(client pb.StatusClient) {
|
|
stream, err := client.Status(context.Background(), &pb.Empty{})
|
|
if err != nil {
|
|
grpclog.Fatalf("%v.List(_) = _, %v", client, err)
|
|
}
|
|
for {
|
|
feature, err := stream.Recv()
|
|
if err == io.EOF {
|
|
break
|
|
}
|
|
if err != nil {
|
|
grpclog.Fatalf("%v.List(_) = _, %v", client, err)
|
|
}
|
|
grpclog.Println(feature)
|
|
}
|
|
grpclog.Println("--------------------------")
|
|
}
|
|
*/
|