forked from bilibili/discovery
/
scheduler.go
77 lines (69 loc) · 1.47 KB
/
scheduler.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
package registry
import (
"context"
"strings"
"sync"
"github.com/bingochen87/discovery/model"
"github.com/go-kratos/kratos/pkg/conf/paladin"
)
// Scheduler info.
type scheduler struct {
schedulers map[string]*model.Scheduler
mutex sync.RWMutex
r *Registry
}
func newScheduler(r *Registry) *scheduler {
return &scheduler{
schedulers: make(map[string]*model.Scheduler),
r: r,
}
}
// Load load scheduler info.
func (s *scheduler) Load() {
for _, key := range paladin.Keys() {
if !strings.HasSuffix(key, ".json") {
continue
}
v := paladin.Get(key)
content, err := v.String()
if err != nil {
return
}
sch := new(model.Scheduler)
if err := sch.Set(content); err != nil {
continue
}
s.schedulers[appsKey(sch.AppID, sch.Env)] = sch
}
}
// Reload reload scheduler info.
func (s *scheduler) Reload() {
event := paladin.WatchEvent(context.Background())
for {
e := <-event
if !strings.HasSuffix(e.Key, ".json") {
continue
}
sch := new(model.Scheduler)
if err := sch.Set(e.Value); err != nil {
continue
}
s.mutex.Lock()
key := appsKey(sch.AppID, sch.Env)
s.r.aLock.Lock()
if a, ok := s.r.appm[key]; ok {
a.UpdateLatest(0)
}
s.r.aLock.Unlock()
s.schedulers[key] = sch
s.mutex.Unlock()
s.r.broadcast(sch.Env, sch.AppID)
}
}
// Get get scheduler info.
func (s *scheduler) Get(appid, env string) *model.Scheduler {
s.mutex.RLock()
sch := s.schedulers[appsKey(appid, env)]
s.mutex.RUnlock()
return sch
}