Debian Codegraph @

daemon/monitor.go

raw
1 // Copyright (c) 2014-2019 Ludovic Fauvet
2 // Licensed under the MIT license
3
4 package daemon
5
6 import (
7 "context"
8 "errors"
9 "fmt"
10 "math/rand"
11 "net"
12 "net/http"
13 "strconv"
14 "strings"
15 "sync"
16 "time"
17
18 . "github.com/etix/mirrorbits/config"
19 "github.com/etix/mirrorbits/core"
20 "github.com/etix/mirrorbits/database"
21 "github.com/etix/mirrorbits/mirrors"
22 "github.com/etix/mirrorbits/scan"
23 "github.com/etix/mirrorbits/utils"
24 "github.com/gomodule/redigo/redis"
25 "github.com/op/go-logging"
26 )
27
28 var (
29 healthCheckThreads = 10
30 userAgent = "Mirrorbits/" + core.VERSION + " PING CHECK"
31 clientTimeout = time.Duration(20 * time.Second)
32 clientDeadline = time.Duration(40 * time.Second)
33 errRedirect = errors.New("Redirect not allowed")
34 errMirrorNotScanned = errors.New("Mirror has not yet been scanned")
35
36 log = logging.MustGetLogger("main")
37 )
38
39 type monitor struct {
40 redis *database.Redis
41 cache *mirrors.Cache
42 mirrors map[int]*mirror
43 mapLock sync.Mutex
44 httpClient http.Client
45 httpTransport http.Transport
46 healthCheckChan chan int
47 syncChan chan int
48 stop chan struct{}
49 configNotifier chan bool
50 wg sync.WaitGroup
51 formatLongestID int
52
53 cluster *cluster
54 trace *scan.Trace
55 }
56
57 type mirror struct {
58 mirrors.Mirror
59 checking bool
60 scanning bool
61 lastCheck time.Time
62 }
63
64 func (m *mirror) NeedHealthCheck() bool {
65 return time.Since(m.lastCheck) > time.Duration(GetConfig().CheckInterval)*time.Minute
66 }
67
68 func (m *mirror) NeedSync() bool {
69 return time.Since(m.LastSync.Time) > time.Duration(GetConfig().ScanInterval)*time.Minute
70 }
71
72 func (m *mirror) IsScanning() bool {
73 return m.scanning
74 }
75
76 func (m *mirror) IsChecking() bool {
77 return m.checking
78 }
79
80 // NewMonitor returns a new instance of monitor
81 func NewMonitor(r *database.Redis, c *mirrors.Cache) *monitor {
82 m := new(monitor)
83 m.redis = r
84 m.cache = c
85 m.cluster = NewCluster(r)
86 m.mirrors = make(map[int]*mirror)
87 m.healthCheckChan = make(chan int, healthCheckThreads*5)
88 m.syncChan = make(chan int)
89 m.stop = make(chan struct{})
90 m.configNotifier = make(chan bool, 1)
91 m.trace = scan.NewTraceHandler(m.redis, m.stop)
92
93 SubscribeConfig(m.configNotifier)
94
95 rand.Seed(time.Now().UnixNano())
96
97 m.httpTransport = http.Transport{
98 DisableKeepAlives: true,
99 MaxIdleConnsPerHost: 0,
100 Dial: func(network, addr string) (net.Conn, error) {
101 deadline := time.Now().Add(clientDeadline)
102 c, err := net.DialTimeout(network, addr, clientTimeout)
103 if err != nil {
104 return nil, err
105 }
106 c.SetDeadline(deadline)
107 return c, nil
108 },
109 }
110
111 m.httpClient = http.Client{
112 CheckRedirect: checkRedirect,
113 Transport: &m.httpTransport,
114 }
115 return m
116 }
117
118 func (m *monitor) Stop() {
119 select {
120 case _, _ = <-m.stop:
121 return
122 default:
123 m.cluster.Stop()
124 close(m.stop)
125 }
126 }
127
128 func (m *monitor) Wait() {
129 m.wg.Wait()
130 }
131
132 // Return an error if the endpoint is an unauthorized redirect
133 func checkRedirect(req *http.Request, via []*http.Request) error {
134 redirects := req.Context().Value(core.ContextAllowRedirects).(mirrors.Redirects)
135
136 if redirects.Allowed() {
137 return nil
138 }
139
140 name := req.Context().Value(core.ContextMirrorName)
141 for _, r := range via {
142 if r.URL != nil {
143 log.Warningf("Unauthorized redirection for %s: %s => %s", name, r.URL.String(), req.URL.String())
144 }
145 }
146 return errRedirect
147 }
148
149 // Main monitor loop
150 func (m *monitor) MonitorLoop() {
151 m.wg.Add(1)
152 defer m.wg.Done()
153
154 mirrorUpdateEvent := m.cache.GetMirrorInvalidationEvent()
155
156 // Wait until the database is ready to be used
157 for {
158 r := m.redis.Get()
159 if r.Err() != nil {
160 if _, ok := r.Err().(database.NetReadyError); ok {
161 time.Sleep(100 * time.Millisecond)
162 continue
163 }
164 }
165 break
166 }
167
168 // Scan the local repository
169 m.retry(func(i uint) error {
170 err := m.scanRepository()
171 if err != nil {
172 if i == 0 {
173 log.Errorf("%+v", fmt.Errorf("unable to scan the local repository: %w", err))
174 }
175 return err
176 }
177 return nil
178 }, 1*time.Second)
179
180 // Synchronize the list of all known mirrors
181 m.retry(func(i uint) error {
182 ids, err := m.mirrorsID()
183 if err != nil {
184 if i == 0 {
185 log.Errorf("%+v", fmt.Errorf("unable to retrieve the mirror list: %w", err))
186 }
187 return err
188 }
189 err = m.syncMirrorList(ids...)
190 if err != nil {
191 if i == 0 {
192 log.Errorf("%+v", fmt.Errorf("unable to sync the list of mirrors: %w", err))
193 }
194 return err
195 }
196 return nil
197 }, 500*time.Millisecond)
198
199 if utils.IsStopped(m.stop) {
200 return
201 }
202
203 // Start the cluster manager
204 m.cluster.Start()
205
206 // Start the health check routines
207 for i := 0; i < healthCheckThreads; i++ {
208 m.wg.Add(1)
209 go m.healthCheckLoop()
210 }
211
212 // Start the mirror sync routines
213 for i := 0; i < GetConfig().ConcurrentSync; i++ {
214 m.wg.Add(1)
215 go m.syncLoop()
216 }
217
218 // Setup recurrent tasks
219 var repositoryScanTicker <-chan time.Time
220 repositoryScanInterval := -1
221 mirrorCheckTicker := time.NewTicker(1 * time.Second)
222
223 // Disable the mirror check while stopping to avoid spurious events
224 go func() {
225 select {
226 case <-m.stop:
227 mirrorCheckTicker.Stop()
228 }
229 }()
230
231 // Force a first configuration reload to setup the timers
232 select {
233 case m.configNotifier <- true:
234 default:
235 }
236
237 for {
238 select {
239 case <-m.stop:
240 return
241 case v := <-mirrorUpdateEvent:
242 id, err := strconv.Atoi(v)
243 if err == nil {
244 m.syncMirrorList(id)
245 }
246 case <-m.configNotifier:
247 if repositoryScanInterval != GetConfig().RepositoryScanInterval {
248 repositoryScanInterval = GetConfig().RepositoryScanInterval
249
250 if repositoryScanInterval == 0 {
251 repositoryScanTicker = nil
252 } else {
253 repositoryScanTicker = time.Tick(time.Duration(repositoryScanInterval) * time.Minute)
254 }
255 }
256 case <-repositoryScanTicker:
257 m.scanRepository()
258 case <-mirrorCheckTicker.C:
259 if m.redis.Failure() {
260 continue
261 }
262 m.mapLock.Lock()
263 for id, v := range m.mirrors {
264 if !v.Enabled {
265 // Ignore disabled mirrors
266 continue
267 }
268 if !m.cluster.IsHandled(id) {
269 continue
270 }
271 if v.NeedHealthCheck() && !v.IsChecking() {
272 select {
273 case m.healthCheckChan <- id:
274 m.mirrors[id].checking = true
275 default:
276 }
277 }
278 if v.NeedSync() && !v.IsScanning() {
279 select {
280 case m.syncChan <- id:
281 m.mirrors[id].scanning = true
282 default:
283 }
284 }
285 }
286 m.mapLock.Unlock()
287 }
288 }
289 }
290
291 // Returns a list of all mirrors ID
292 func (m *monitor) mirrorsID() ([]int, error) {
293 var ids []int
294 list, err := m.redis.GetListOfMirrors()
295 if err != nil {
296 return nil, err
297 }
298 for id := range list {
299 ids = append(ids, id)
300 }
301 return ids, nil
302 }
303
304 // Sync the remote mirror struct with the local dataset
305 func (m *monitor) syncMirrorList(mirrorsIDs ...int) error {
306 for _, id := range mirrorsIDs {
307 mir, err := m.cache.GetMirror(id)
308 if err != nil && err != redis.ErrNil {
309 log.Errorf("Fetching mirror %s failed: %s", id, err.Error())
310 continue
311 } else if err == redis.ErrNil {
312 // Mirror has been deleted
313 m.mapLock.Lock()
314 delete(m.mirrors, id)
315 m.mapLock.Unlock()
316 m.cluster.RemoveMirrorID(id)
317 continue
318 }
319
320 // Compute the space required to display the mirror names in the logs
321 if len(mir.Name) > m.formatLongestID {
322 m.formatLongestID = len(mir.Name)
323 }
324
325 m.cluster.AddMirror(&mir)
326
327 m.mapLock.Lock()
328 if _, ok := m.mirrors[mir.ID]; ok {
329 // Update existing mirror
330 tmp := m.mirrors[mir.ID]
331 tmp.Mirror = mir
332 m.mirrors[mir.ID] = tmp
333 } else {
334 // Add new mirror
335 m.mirrors[mir.ID] = &mirror{
336 Mirror: mir,
337 }
338 }
339 m.mapLock.Unlock()
340 }
341
342 log.Debugf("%d mirror%s updated", len(mirrorsIDs), utils.Plural(len(mirrorsIDs)))
343 return nil
344 }
345
346 // Main health check loop
347 // TODO merge with the monitorLoop?
348 func (m *monitor) healthCheckLoop() {
349 defer m.wg.Done()
350 for {
351 select {
352 case <-m.stop:
353 return
354 case id := <-m.healthCheckChan:
355 if utils.IsStopped(m.stop) {
356 return
357 }
358
359 var mptr *mirror
360 var mirror mirror
361 var ok bool
362
363 m.mapLock.Lock()
364 if mptr, ok = m.mirrors[id]; !ok {
365 m.mapLock.Unlock()
366 continue
367 }
368
369 // Copy the mirror struct for read-only access
370 mirror = *mptr
371 m.mapLock.Unlock()
372
373 err := m.healthCheck(mirror.Mirror)
374
375 if err == errMirrorNotScanned {
376 // Not removing the 'checking' lock is intended here so the mirror won't
377 // be checked again until the rsync/ftp scan is finished.
378 continue
379 }
380
381 m.mapLock.Lock()
382 if mirror, ok := m.mirrors[id]; ok {
383 if !database.RedisIsLoading(err) {
384 mirror.lastCheck = time.Now().UTC()
385 }
386 mirror.checking = false
387 }
388 m.mapLock.Unlock()
389 }
390 }
391 }
392
393 // Main sync loop
394 // TODO merge with the monitorLoop?
395 func (m *monitor) syncLoop() {
396 defer m.wg.Done()
397 for {
398 select {
399 case <-m.stop:
400 return
401 case id := <-m.syncChan:
402
403 var mir mirror
404 var mirrorPtr *mirror
405 var ok bool
406
407 m.mapLock.Lock()
408 if mirrorPtr, ok = m.mirrors[id]; !ok {
409 m.mapLock.Unlock()
410 continue
411 }
412 mir = *mirrorPtr
413 m.mapLock.Unlock()
414
415 conn := m.redis.Get()
416 scanning, err := scan.IsScanning(conn, id)
417 if err != nil {
418 conn.Close()
419 if !database.RedisIsLoading(err) {
420 log.Warningf("syncloop: %s", err.Error())
421 }
422 goto end
423 } else if scanning {
424 log.Debugf("[%s] scan already in progress on another node", mir.Name)
425 conn.Close()
426 goto end
427 }
428 conn.Close()
429
430 log.Debugf("Scanning %s", mir.Name)
431
432 // Start fetching the latest trace
433 go func() {
434 err := m.trace.GetLastUpdate(mir.Mirror)
435 if err != nil && err != scan.ErrNoTrace {
436 var numError *strconv.NumError
437 if errors.As(err, &numError) {
438 if numError.Err == strconv.ErrSyntax {
439 log.Warningf("[%s] parsing trace file failed: %s is not a valid timestamp", mir.Name, strconv.Quote(numError.Num))
440 return
441 }
442 } else {
443 log.Warningf("[%s] fetching trace file failed: %s", mir.Name, err)
444 }
445 }
446 }()
447
448 err = scan.ErrNoSyncMethod
449
450 // First try to scan with rsync
451 if mir.RsyncURL != "" {
452 _, err = scan.Scan(core.RSYNC, m.redis, m.cache, mir.RsyncURL, id, m.stop)
453 }
454 // If it failed or rsync wasn't supported
455 // fallback to FTP
456 if err != nil && err != scan.ErrScanAborted && mir.FtpURL != "" {
457 _, err = scan.Scan(core.FTP, m.redis, m.cache, mir.FtpURL, id, m.stop)
458 }
459
460 if err == scan.ErrScanInProgress {
461 log.Warningf("%-30.30s Scan already in progress", mir.Name)
462 goto end
463 }
464
465 if err == nil && mir.Enabled == true && mir.IsUp() == false {
466 m.healthCheckChan <- id
467 }
468
469 end:
470 m.mapLock.Lock()
471 if mirrorPtr, ok = m.mirrors[id]; ok {
472 mirrorPtr.scanning = false
473 }
474 m.mapLock.Unlock()
475 }
476 }
477 }
478
479 // Do an actual health check against a given mirror
480 func (m *monitor) healthCheck(mirror mirrors.Mirror) error {
481 // Get the URL to a random file available on this mirror
482 file, size, err := m.getRandomFile(mirror.ID)
483 if err != nil {
484 if err == redis.ErrNil {
485 return errMirrorNotScanned
486 } else if !database.RedisIsLoading(err) {
487 log.Warningf("%s: Error: Cannot obtain a random file: %s", mirror.Name, err)
488 }
489 return err
490 }
491
492 // Perform health check(s)
493 if utils.HasAnyPrefix(mirror.HttpURL, "http://", "https://") {
494 err = m.healthCheckDo(&mirror, mirror.HttpURL, file, size)
495 } else {
496 err = m.healthCheckDo(&mirror, "http://"+mirror.HttpURL, file, size)
497 err2 := m.healthCheckDo(&mirror, "https://"+mirror.HttpURL, file, size)
498 if err2 != nil {
499 err = err2
500 }
501 }
502
503 return err
504 }
505
506 func (m *monitor) healthCheckDo(mirror *mirrors.Mirror, url string, file string, size int64) error {
507 // Get protocol
508 proto := mirrors.HTTP
509 if strings.HasPrefix(url, "https://") {
510 proto = mirrors.HTTPS
511 }
512
513 // Format log output
514 format := "%-" + fmt.Sprintf("%d.%ds %-5s ", m.formatLongestID+4, m.formatLongestID+4, proto)
515
516 // Prepare the HTTP request
517 req, err := http.NewRequest("HEAD", strings.TrimRight(url, "/")+file, nil)
518 req.Header.Set("User-Agent", userAgent)
519 req.Close = true
520
521 ctx, cancel := context.WithTimeout(req.Context(), clientDeadline)
522 ctx = context.WithValue(ctx, core.ContextMirrorID, mirror.ID)
523 ctx = context.WithValue(ctx, core.ContextMirrorName, mirror.Name)
524 ctx = context.WithValue(ctx, core.ContextAllowRedirects, mirror.AllowRedirects)
525 req = req.WithContext(ctx)
526 defer cancel()
527
528 go func() {
529 select {
530 case <-m.stop:
531 log.Debugf("Aborting health-check for %s", url)
532 cancel()
533 case <-ctx.Done():
534 }
535 }()
536
537 var contentLength string
538 var statusCode int
539 elapsed, err := m.httpDo(ctx, req, func(resp *http.Response, err error) error {
540 if err != nil {
541 return err
542 }
543 defer resp.Body.Close()
544 statusCode = resp.StatusCode
545 contentLength = resp.Header.Get("Content-Length")
546 return nil
547 })
548
549 if utils.IsStopped(m.stop) {
550 return nil
551 }
552
553 if err != nil {
554 var opErr *net.OpError
555 if errors.As(err, &opErr) {
556 log.Debugf("Op: %s | Net: %s | Addr: %s | Err: %s | Temporary: %t", opErr.Op, opErr.Net, opErr.Addr, opErr.Error(), opErr.Temporary())
557 }
558 reason := "Unreachable"
559 if strings.Contains(err.Error(), errRedirect.Error()) {
560 reason = "Unauthorized redirect"
561 }
562 markErr := mirrors.MarkMirrorDown(m.redis, mirror.ID, proto, reason)
563 if markErr != nil {
564 log.Errorf(format+"Unable to mark mirror as down: %s", mirror.Name, markErr)
565 }
566 log.Errorf(format+"Error: %s (%dms)", mirror.Name, err.Error(), elapsed/time.Millisecond)
567 return err
568 }
569
570 switch statusCode {
571 case 200:
572 err = mirrors.MarkMirrorUp(m.redis, mirror.ID, proto)
573 if err != nil {
574 log.Errorf(format+"Unable to mark mirror as up: %s", mirror.Name, err)
575 }
576 rsize, err := strconv.ParseInt(contentLength, 10, 64)
577 if err == nil && rsize != size {
578 log.Warningf(format+"File size mismatch! [%s] (%dms)", mirror.Name, file, elapsed/time.Millisecond)
579 } else {
580 log.Noticef(format+"Up! (%dms)", mirror.Name, elapsed/time.Millisecond)
581 }
582 case 404:
583 err = mirrors.MarkMirrorDown(m.redis, mirror.ID, proto, fmt.Sprintf("File not found %s (error 404)", file))
584 if err != nil {
585 log.Errorf(format+"Unable to mark mirror as down: %s", mirror.Name, err)
586 }
587 if GetConfig().DisableOnMissingFile {
588 err = mirrors.DisableMirror(m.redis, mirror.ID)
589 if err != nil {
590 log.Errorf(format+"Unable to disable mirror: %s", mirror.Name, err)
591 }
592 }
593 log.Errorf(format+"Error: File %s not found (error 404)", mirror.Name, file)
594 default:
595 err = mirrors.MarkMirrorDown(m.redis, mirror.ID, proto, fmt.Sprintf("Got status code %d", statusCode))
596 if err != nil {
597 log.Errorf(format+"Unable to mark mirror as down: %s", mirror.Name, err)
598 }
599 log.Warningf(format+"Down! Status: %d", mirror.Name, statusCode)
600 }
601 return nil
602 }
603
604 func (m *monitor) httpDo(ctx context.Context, req *http.Request, f func(*http.Response, error) error) (time.Duration, error) {
605 var elapsed time.Duration
606 c := make(chan error, 1)
607
608 go func() {
609 start := time.Now()
610 err := f(m.httpClient.Do(req))
611 elapsed = time.Since(start)
612 c <- err
613 }()
614
615 select {
616 case <-ctx.Done():
617 m.httpTransport.CancelRequest(req)
618 <-c // Wait for f to return.
619 return elapsed, ctx.Err()
620 case err := <-c:
621 return elapsed, err
622 }
623 }
624
625 // Get a random filename known to be served by the given mirror
626 func (m *monitor) getRandomFile(id int) (file string, size int64, err error) {
627 sinterKey := fmt.Sprintf("HANDLEDFILES_%d", id)
628
629 rconn := m.redis.Get()
630 defer rconn.Close()
631
632 file, err = redis.String(rconn.Do("SRANDMEMBER", sinterKey))
633 if err != nil {
634 return
635 }
636
637 size, err = redis.Int64(rconn.Do("HGET", fmt.Sprintf("FILE_%s", file), "size"))
638 if err != nil {
639 return
640 }
641
642 return
643 }
644
645 // Trigger a sync of the local repository
646 func (m *monitor) scanRepository() error {
647 err := scan.ScanSource(m.redis, false, m.stop)
648 if err != nil {
649 log.Errorf("Scanning source failed: %s", err.Error())
650 }
651 return err
652 }
653
654 // Retry a function until no errors is returned while still allowing
655 // the process to be stopped.
656 func (m *monitor) retry(fn func(iteration uint) error, delay time.Duration) {
657 var i uint
658 for {
659 err := fn(i)
660 i++
661 if err == nil {
662 break
663 }
664 select {
665 case <-m.stop:
666 return
667 case <-time.After(delay):
668 }
669 }
670 }