forked from tuna/tunasync
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathworker.go
444 lines (389 loc) · 9.9 KB
/
worker.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
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
package worker
import (
"fmt"
"net/http"
"os"
"sync"
"syscall"
"time"
"github.com/gin-gonic/gin"
. "github.com/tuna/tunasync/internal"
)
var tunasyncWorker *Worker
// A Worker is a instance of tunasync worker
type Worker struct {
L sync.Mutex
cfg *Config
jobs map[string]*mirrorJob
managerChan chan jobMessage
semaphore chan empty
exit chan empty
schedule *scheduleQueue
httpEngine *gin.Engine
httpClient *http.Client
}
// GetTUNASyncWorker returns a singalton worker
func GetTUNASyncWorker(cfg *Config) *Worker {
if tunasyncWorker != nil {
return tunasyncWorker
}
w := &Worker{
cfg: cfg,
jobs: make(map[string]*mirrorJob),
managerChan: make(chan jobMessage, 32),
semaphore: make(chan empty, cfg.Global.Concurrent),
exit: make(chan empty),
schedule: newScheduleQueue(),
}
if cfg.Manager.CACert != "" {
httpClient, err := CreateHTTPClient(cfg.Manager.CACert)
if err != nil {
logger.Errorf("Error initializing HTTP client: %s", err.Error())
return nil
}
w.httpClient = httpClient
}
if cfg.Cgroup.Enable {
initCgroup(cfg.Cgroup.BasePath)
}
w.initJobs()
w.makeHTTPServer()
tunasyncWorker = w
return w
}
// Run runs worker forever
func (w *Worker) Run() {
w.registorWorker()
go w.runHTTPServer()
w.runSchedule()
}
// Halt stops all jobs
func (w *Worker) Halt() {
w.L.Lock()
logger.Notice("Stopping all the jobs")
for _, job := range w.jobs {
if job.State() != stateDisabled {
job.ctrlChan <- jobHalt
}
}
jobsDone.Wait()
logger.Notice("All the jobs are stopped")
w.L.Unlock()
close(w.exit)
}
// ReloadMirrorConfig refresh the providers and jobs
// from new mirror configs
// TODO: deleted job should be removed from manager-side mirror list
func (w *Worker) ReloadMirrorConfig(newMirrors []mirrorConfig) {
w.L.Lock()
defer w.L.Unlock()
logger.Info("Reloading mirror configs")
oldMirrors := w.cfg.Mirrors
difference := diffMirrorConfig(oldMirrors, newMirrors)
// first deal with deletion and modifications
for _, op := range difference {
if op.diffOp == diffAdd {
continue
}
name := op.mirCfg.Name
job, ok := w.jobs[name]
if !ok {
logger.Warningf("Job %s not found", name)
continue
}
switch op.diffOp {
case diffDelete:
w.disableJob(job)
delete(w.jobs, name)
logger.Noticef("Deleted job %s", name)
case diffModify:
jobState := job.State()
w.disableJob(job)
// set new provider
provider := newMirrorProvider(op.mirCfg, w.cfg)
if err := job.SetProvider(provider); err != nil {
logger.Errorf("Error setting job provider of %s: %s", name, err.Error())
continue
}
// re-schedule job according to its previous state
if jobState == stateDisabled {
job.SetState(stateDisabled)
} else if jobState == statePaused {
job.SetState(statePaused)
go job.Run(w.managerChan, w.semaphore)
} else {
job.SetState(stateNone)
go job.Run(w.managerChan, w.semaphore)
w.schedule.AddJob(time.Now(), job)
}
logger.Noticef("Reloaded job %s", name)
}
}
// for added new jobs, just start new jobs
for _, op := range difference {
if op.diffOp != diffAdd {
continue
}
provider := newMirrorProvider(op.mirCfg, w.cfg)
job := newMirrorJob(provider)
w.jobs[provider.Name()] = job
job.SetState(stateNone)
go job.Run(w.managerChan, w.semaphore)
w.schedule.AddJob(time.Now(), job)
logger.Noticef("New job %s", job.Name())
}
w.cfg.Mirrors = newMirrors
}
func (w *Worker) initJobs() {
for _, mirror := range w.cfg.Mirrors {
// Create Provider
provider := newMirrorProvider(mirror, w.cfg)
w.jobs[provider.Name()] = newMirrorJob(provider)
}
}
func (w *Worker) disableJob(job *mirrorJob) {
w.schedule.Remove(job.Name())
if job.State() != stateDisabled {
job.ctrlChan <- jobDisable
<-job.disabled
}
}
// Ctrl server receives commands from the manager
func (w *Worker) makeHTTPServer() {
s := gin.New()
s.Use(gin.Recovery())
s.POST("/", func(c *gin.Context) {
w.L.Lock()
defer w.L.Unlock()
var cmd WorkerCmd
if err := c.BindJSON(&cmd); err != nil {
c.JSON(http.StatusBadRequest, gin.H{"msg": "Invalid request"})
return
}
logger.Noticef("Received command: %v", cmd)
if cmd.MirrorID == "" {
// worker-level commands
switch cmd.Cmd {
case CmdReload:
// send myself a SIGHUP
pid := os.Getpid()
syscall.Kill(pid, syscall.SIGHUP)
default:
c.JSON(http.StatusNotAcceptable, gin.H{"msg": "Invalid Command"})
return
}
}
// job level comands
job, ok := w.jobs[cmd.MirrorID]
if !ok {
c.JSON(http.StatusNotFound, gin.H{"msg": fmt.Sprintf("Mirror ``%s'' not found", cmd.MirrorID)})
return
}
// No matter what command, the existing job
// schedule should be flushed
w.schedule.Remove(job.Name())
// if job disabled, start them first
switch cmd.Cmd {
case CmdStart, CmdRestart:
if job.State() == stateDisabled {
go job.Run(w.managerChan, w.semaphore)
}
}
switch cmd.Cmd {
case CmdStart:
job.ctrlChan <- jobStart
case CmdRestart:
job.ctrlChan <- jobRestart
case CmdStop:
// if job is disabled, no goroutine would be there
// receiving this signal
if job.State() != stateDisabled {
job.ctrlChan <- jobStop
}
case CmdDisable:
w.disableJob(job)
case CmdPing:
// empty
default:
c.JSON(http.StatusNotAcceptable, gin.H{"msg": "Invalid Command"})
return
}
c.JSON(http.StatusOK, gin.H{"msg": "OK"})
})
w.httpEngine = s
}
func (w *Worker) runHTTPServer() {
addr := fmt.Sprintf("%s:%d", w.cfg.Server.Addr, w.cfg.Server.Port)
httpServer := &http.Server{
Addr: addr,
Handler: w.httpEngine,
ReadTimeout: 10 * time.Second,
WriteTimeout: 10 * time.Second,
}
if w.cfg.Server.SSLCert == "" && w.cfg.Server.SSLKey == "" {
if err := httpServer.ListenAndServe(); err != nil {
panic(err)
}
} else {
if err := httpServer.ListenAndServeTLS(w.cfg.Server.SSLCert, w.cfg.Server.SSLKey); err != nil {
panic(err)
}
}
}
func (w *Worker) runSchedule() {
w.L.Lock()
mirrorList := w.fetchJobStatus()
unset := make(map[string]bool)
for name := range w.jobs {
unset[name] = true
}
// Fetch mirror list stored in the manager
// put it on the scheduled time
// if it's disabled, ignore it
for _, m := range mirrorList {
if job, ok := w.jobs[m.Name]; ok {
delete(unset, m.Name)
switch m.Status {
case Disabled:
job.SetState(stateDisabled)
continue
case Paused:
job.SetState(statePaused)
go job.Run(w.managerChan, w.semaphore)
continue
default:
job.SetState(stateNone)
go job.Run(w.managerChan, w.semaphore)
stime := m.LastUpdate.Add(job.provider.Interval())
logger.Debugf("Scheduling job %s @%s", job.Name(), stime.Format("2006-01-02 15:04:05"))
w.schedule.AddJob(stime, job)
}
}
}
// some new jobs may be added
// which does not exist in the
// manager's mirror list
for name := range unset {
job := w.jobs[name]
job.SetState(stateNone)
go job.Run(w.managerChan, w.semaphore)
w.schedule.AddJob(time.Now(), job)
}
w.L.Unlock()
tick := time.Tick(5 * time.Second)
for {
select {
case jobMsg := <-w.managerChan:
// got status update from job
w.L.Lock()
job, ok := w.jobs[jobMsg.name]
w.L.Unlock()
if !ok {
logger.Warningf("Job %s not found", jobMsg.name)
continue
}
if (job.State() != stateReady) && (job.State() != stateHalting) {
logger.Infof("Job %s state is not ready, skip adding new schedule", jobMsg.name)
continue
}
// syncing status is only meaningful when job
// is running. If it's paused or disabled
// a sync failure signal would be emitted
// which needs to be ignored
w.updateStatus(job, jobMsg)
// only successful or the final failure msg
// can trigger scheduling
if jobMsg.schedule {
schedTime := time.Now().Add(job.provider.Interval())
logger.Noticef(
"Next scheduled time for %s: %s",
job.Name(),
schedTime.Format("2006-01-02 15:04:05"),
)
w.schedule.AddJob(schedTime, job)
}
case <-tick:
// check schedule every 5 seconds
if job := w.schedule.Pop(); job != nil {
job.ctrlChan <- jobStart
}
case <-w.exit:
// flush status update messages
w.L.Lock()
defer w.L.Unlock()
for {
select {
case jobMsg := <-w.managerChan:
logger.Debugf("status update from %s", jobMsg.name)
job, ok := w.jobs[jobMsg.name]
if !ok {
continue
}
if jobMsg.status == Failed || jobMsg.status == Success {
w.updateStatus(job, jobMsg)
}
default:
return
}
}
}
}
}
// Name returns worker name
func (w *Worker) Name() string {
return w.cfg.Global.Name
}
// URL returns the url to http server of the worker
func (w *Worker) URL() string {
proto := "https"
if w.cfg.Server.SSLCert == "" && w.cfg.Server.SSLKey == "" {
proto = "http"
}
return fmt.Sprintf("%s://%s:%d/", proto, w.cfg.Server.Hostname, w.cfg.Server.Port)
}
func (w *Worker) registorWorker() {
url := fmt.Sprintf(
"%s/workers",
w.cfg.Manager.APIBase,
)
msg := WorkerStatus{
ID: w.Name(),
URL: w.URL(),
}
if _, err := PostJSON(url, msg, w.httpClient); err != nil {
logger.Errorf("Failed to register worker")
}
}
func (w *Worker) updateStatus(job *mirrorJob, jobMsg jobMessage) {
url := fmt.Sprintf(
"%s/workers/%s/jobs/%s",
w.cfg.Manager.APIBase,
w.Name(),
jobMsg.name,
)
p := job.provider
smsg := MirrorStatus{
Name: jobMsg.name,
Worker: w.cfg.Global.Name,
IsMaster: p.IsMaster(),
Status: jobMsg.status,
Upstream: p.Upstream(),
Size: "unknown",
ErrorMsg: jobMsg.msg,
}
if _, err := PostJSON(url, smsg, w.httpClient); err != nil {
logger.Errorf("Failed to update mirror(%s) status: %s", jobMsg.name, err.Error())
}
}
func (w *Worker) fetchJobStatus() []MirrorStatus {
var mirrorList []MirrorStatus
url := fmt.Sprintf(
"%s/workers/%s/jobs",
w.cfg.Manager.APIBase,
w.Name(),
)
if _, err := GetJSON(url, &mirrorList, w.httpClient); err != nil {
logger.Errorf("Failed to fetch job status: %s", err.Error())
}
return mirrorList
}