Debian Codegraph @

scan/scan.go

raw
1 // Copyright (c) 2014-2019 Ludovic Fauvet
2 // Licensed under the MIT license
3
4 package scan
5
6 import (
7 "errors"
8 "fmt"
9 "os"
10 "path/filepath"
11 "strconv"
12 "time"
13
14 . "github.com/etix/mirrorbits/config"
15 "github.com/etix/mirrorbits/core"
16 "github.com/etix/mirrorbits/database"
17 "github.com/etix/mirrorbits/filesystem"
18 "github.com/etix/mirrorbits/mirrors"
19 "github.com/etix/mirrorbits/network"
20 "github.com/etix/mirrorbits/utils"
21 "github.com/gomodule/redigo/redis"
22 "github.com/op/go-logging"
23 )
24
25 var (
26 // ErrScanAborted is returned when a scan is aborted by the user
27 ErrScanAborted = errors.New("scan aborted")
28 // ErrScanInProgress is returned when a scan is started while another is already in progress
29 ErrScanInProgress = errors.New("scan already in progress")
30 // ErrNoSyncMethod is returned when no sync protocol is available
31 ErrNoSyncMethod = errors.New("no suitable URL for the scan")
32
33 log = logging.MustGetLogger("main")
34 )
35
36 // Scanner is the interface that all scanners must implement
37 type Scanner interface {
38 Scan(url, identifier string, conn redis.Conn, stop <-chan struct{}) (core.Precision, error)
39 }
40
41 type filedata struct {
42 path string
43 sha1 string
44 sha256 string
45 md5 string
46 size int64
47 modTime time.Time
48 }
49
50 type scan struct {
51 redis *database.Redis
52 cache *mirrors.Cache
53
54 conn redis.Conn
55 mirrorid int
56 filesTmpKey string
57 count int64
58 }
59
60 type ScanResult struct {
61 MirrorID int
62 MirrorName string
63 FilesIndexed int64
64 KnownIndexed int64
65 Removed int64
66 TZOffsetMs int64
67 }
68
69 // IsScanning returns true is a scan is already in progress for the given mirror
70 func IsScanning(conn redis.Conn, id int) (bool, error) {
71 return redis.Bool(conn.Do("EXISTS", fmt.Sprintf("SCANNING_%d", id)))
72 }
73
74 // Scan starts a scan of the given mirror
75 func Scan(typ core.ScannerType, r *database.Redis, c *mirrors.Cache, url string, id int, stop <-chan struct{}) (*ScanResult, error) {
76 // Connect to the database
77 conn := r.Get()
78 defer conn.Close()
79
80 s := &scan{
81 redis: r,
82 mirrorid: id,
83 conn: conn,
84 cache: c,
85 }
86
87 var scanner Scanner
88 switch typ {
89 case core.RSYNC:
90 scanner = &RsyncScanner{
91 scan: s,
92 }
93 case core.FTP:
94 scanner = &FTPScanner{
95 scan: s,
96 }
97 default:
98 panic(fmt.Sprintf("Unknown scanner"))
99 }
100
101 // Get the mirror name
102 name, err := redis.String(conn.Do("HGET", "MIRRORS", id))
103 if err != nil {
104 return nil, err
105 }
106
107 // Try to acquire a lock so we don't have a scanning race
108 // from different nodes.
109 // Also make the key expire automatically in case our process
110 // gets killed.
111 lock := network.NewClusterLock(s.redis, fmt.Sprintf("SCANNING_%d", id), name)
112
113 done, err := lock.Get()
114 if err != nil {
115 return nil, err
116 } else if done == nil {
117 return nil, ErrScanInProgress
118 }
119
120 defer lock.Release()
121
122 s.setLastSync(conn, id, typ, 0, false)
123
124 mirrors.PushLog(r, mirrors.NewLogScanStarted(id, typ))
125 defer func(err *error) {
126 if err != nil && *err != nil {
127 mirrors.PushLog(r, mirrors.NewLogError(id, *err))
128 }
129 }(&err)
130
131 conn.Send("MULTI")
132
133 filesKey := fmt.Sprintf("MIRRORFILES_%d", id)
134 s.filesTmpKey = fmt.Sprintf("MIRRORFILESTMP_%d", id)
135
136 // Remove any left over
137 conn.Send("DEL", s.filesTmpKey)
138
139 var precision core.Precision
140 precision, err = scanner.Scan(url, name, conn, stop)
141 if err != nil {
142 // Discard MULTI
143 s.ScannerDiscard()
144
145 // Remove the temporary key
146 conn.Do("DEL", s.filesTmpKey)
147
148 log.Errorf("[%s] %s", name, err.Error())
149 return nil, err
150 }
151
152 log.Infof("[%s] Indexing the files...", name)
153
154 // Exec multi
155 s.ScannerCommit()
156
157 // Get the list of files no more present on this mirror
158 var toremove []any
159 toremove, err = redis.Values(conn.Do("SDIFF", filesKey, s.filesTmpKey))
160 if err != nil {
161 return nil, err
162 }
163
164 // Remove this mirror from the given file SET
165 if len(toremove) > 0 {
166 conn.Send("MULTI")
167 for _, e := range toremove {
168 log.Debugf("[%s] Removing %s from mirror", name, e)
169 conn.Send("SREM", fmt.Sprintf("FILEMIRRORS_%s", e), id)
170 conn.Send("DEL", fmt.Sprintf("FILEINFO_%d_%s", id, e))
171 // Publish update
172 database.SendPublish(conn, database.MIRROR_FILE_UPDATE, fmt.Sprintf("%d %s", id, e))
173
174 }
175 _, err = conn.Do("EXEC")
176 if err != nil {
177 return nil, err
178 }
179 }
180
181 // Finally rename the temporary sets containing the list
182 // of files for this mirror to the production key
183 if s.count > 0 {
184 _, err = conn.Do("RENAME", s.filesTmpKey, filesKey)
185 if err != nil {
186 return nil, err
187 }
188 }
189
190 sinterKey := fmt.Sprintf("HANDLEDFILES_%d", id)
191
192 // Count the number of files known on the remote end
193 common, _ := redis.Int64(conn.Do("SINTERSTORE", sinterKey, "FILES", filesKey))
194
195 if err != nil {
196 return nil, err
197 }
198
199 s.setLastSync(conn, id, typ, precision, true)
200
201 var tzoffset int64
202 tzoffset, err = s.adjustTZOffset(name, precision)
203 if err != nil {
204 log.Warningf("Unable to check timezone shifts: %s", err)
205 }
206
207 log.Infof("[%s] Indexed %d files (%d known), %d removed", name, s.count, common, len(toremove))
208 res := &ScanResult{
209 MirrorID: id,
210 MirrorName: name,
211 FilesIndexed: s.count,
212 KnownIndexed: common,
213 Removed: int64(len(toremove)),
214 TZOffsetMs: tzoffset,
215 }
216
217 mirrors.PushLog(r, mirrors.NewLogScanCompleted(
218 res.MirrorID,
219 res.FilesIndexed,
220 res.KnownIndexed,
221 res.Removed,
222 res.TZOffsetMs))
223
224 return res, nil
225 }
226
227 func (s *scan) ScannerAddFile(f filedata) {
228 s.count++
229
230 // Add all the files to a temporary key
231 s.conn.Send("SADD", s.filesTmpKey, f.path)
232
233 // Mark the file as being supported by this mirror
234 rk := fmt.Sprintf("FILEMIRRORS_%s", f.path)
235 s.conn.Send("SADD", rk, s.mirrorid)
236
237 // Save the size of the current file found on this mirror
238 ik := fmt.Sprintf("FILEINFO_%d_%s", s.mirrorid, f.path)
239 s.conn.Send("HSET", ik, "size", f.size, "modTime", f.modTime)
240
241 // Publish update
242 database.SendPublish(s.conn, database.MIRROR_FILE_UPDATE, fmt.Sprintf("%d %s", s.mirrorid, f.path))
243 }
244
245 func (s *scan) ScannerDiscard() {
246 s.conn.Do("DISCARD")
247 }
248
249 func (s *scan) ScannerCommit() error {
250 _, err := s.conn.Do("EXEC")
251 return err
252 }
253
254 func (s *scan) setLastSync(conn redis.Conn, id int, protocol core.ScannerType, precision core.Precision, successful bool) error {
255 now := time.Now().UTC().Unix()
256
257 conn.Send("MULTI")
258
259 // Set the last sync time
260 conn.Send("HSET", fmt.Sprintf("MIRROR_%d", id), "lastSync", now)
261
262 // Set the last successful sync time
263 if successful {
264 if precision == 0 {
265 precision = core.Precision(time.Second)
266 }
267
268 conn.Send("HSET", fmt.Sprintf("MIRROR_%d", id),
269 "lastSuccessfulSync", now,
270 "lastSuccessfulSyncProtocol", protocol,
271 "lastSuccessfulSyncPrecision", precision)
272 }
273
274 _, err := conn.Do("EXEC")
275
276 // Publish an update on redis
277 database.Publish(conn, database.MIRROR_UPDATE, strconv.Itoa(id))
278
279 return err
280 }
281
282 func (s *scan) adjustTZOffset(name string, precision core.Precision) (ms int64, err error) {
283 type pair struct {
284 local filesystem.FileInfo
285 remote filesystem.FileInfo
286 }
287
288 var filepaths []string
289 var pairs []pair
290 var offsetmap map[int64]int
291 var commonOffsetFound bool
292
293 if s.cache == nil {
294 log.Error("Skipping timezone check: missing cache in instance")
295 return
296 }
297
298 if GetConfig().FixTimezoneOffsets == false {
299 // We need to reset any previous value already
300 // stored in the database.
301 goto finish
302 }
303
304 // Get 100 random files from the mirror
305 filepaths, err = redis.Strings(s.conn.Do("SRANDMEMBER", fmt.Sprintf("HANDLEDFILES_%d", s.mirrorid), 100))
306 if err != nil {
307 return
308 }
309
310 pairs = make([]pair, 0, 100)
311
312 // Get the metadata of each file
313 for _, path := range filepaths {
314 p := pair{}
315
316 p.local, err = s.cache.GetFileInfo(path)
317 if err != nil {
318 return
319 }
320
321 p.remote, err = s.cache.GetFileInfoMirror(s.mirrorid, path)
322 if err != nil {
323 return
324 }
325
326 if p.remote.ModTime.IsZero() {
327 // Invalid mod time
328 continue
329 }
330
331 if p.local.Size != p.remote.Size {
332 // File differ: comparing the modfile will fail
333 continue
334 }
335
336 // Add the file to valid pairs
337 pairs = append(pairs, p)
338 }
339
340 if len(pairs) < 10 || len(pairs) < len(filepaths)/2 {
341 // Less than half the files we got have a size
342 // match, this is very suspicious. Skip the
343 // check and reset the offset in the db.
344 goto warn
345 }
346
347 // Compute the diff between local and remote for those files
348 offsetmap = make(map[int64]int)
349 for _, p := range pairs {
350 // Convert to millisecond since unix timestamp truncating to the available precision
351 local := p.local.ModTime.Truncate(precision.Duration()).UnixNano() / int64(time.Millisecond)
352 remote := p.remote.ModTime.Truncate(precision.Duration()).UnixNano() / int64(time.Millisecond)
353
354 diff := local - remote
355 offsetmap[diff]++
356 }
357
358 for k, v := range offsetmap {
359 // Find the common offset (if any) of at least 90% of our subset
360 if v >= int(float64(len(pairs))/100*90) {
361 ms = k
362 commonOffsetFound = true
363 break
364 }
365 }
366
367 warn:
368 if !commonOffsetFound {
369 log.Warningf("[%s] Unable to guess the timezone offset", name)
370 }
371
372 finish:
373 // Store the offset in the database
374 key := fmt.Sprintf("MIRROR_%d", s.mirrorid)
375 _, err = s.conn.Do("HSET", key, "tzoffset", ms)
376 if err != nil {
377 return
378 }
379
380 // Publish update
381 database.Publish(s.conn, database.MIRROR_UPDATE, strconv.Itoa(s.mirrorid))
382
383 if ms != 0 {
384 log.Noticef("[%s] Timezone offset detected: applied correction of %dms", name, ms)
385 }
386
387 return
388 }
389
390 type sourcescanner struct {
391 }
392
393 // Walk inside the source/reference repository
394 func (s *sourcescanner) walkSource(conn redis.Conn, path string, f os.FileInfo, rehash bool, err error) (*filedata, error) {
395 if f == nil || f.IsDir() || f.Mode()&os.ModeSymlink != 0 {
396 return nil, nil
397 }
398
399 d := new(filedata)
400 d.path = path[len(GetConfig().Repository):]
401 d.size = f.Size()
402 d.modTime = f.ModTime()
403
404 // Get the previous file properties
405 properties, err := redis.Strings(conn.Do("HMGET", fmt.Sprintf("FILE_%s", d.path), "size", "modTime", "sha1", "sha256", "md5"))
406 if err != nil && err != redis.ErrNil {
407 return nil, err
408 } else if len(properties) < 5 {
409 // This will force a rehash
410 properties = make([]string, 5)
411 }
412
413 size, _ := strconv.ParseInt(properties[0], 10, 64)
414 modTime, _ := time.Parse("2006-01-02 15:04:05.999999999 -0700 MST", properties[1])
415 sha1 := properties[2]
416 sha256 := properties[3]
417 md5 := properties[4]
418
419 rehash = rehash ||
420 (GetConfig().Hashes.SHA1 && len(sha1) == 0) ||
421 (GetConfig().Hashes.SHA256 && len(sha256) == 0) ||
422 (GetConfig().Hashes.MD5 && len(md5) == 0)
423
424 if rehash || size != d.size || !modTime.Equal(d.modTime) {
425 h, err := filesystem.HashFile(GetConfig().Repository + d.path)
426 if err != nil {
427 log.Warningf("%s: hashing failed: %s", d.path, err.Error())
428 } else {
429 d.sha1 = h.Sha1
430 d.sha256 = h.Sha256
431 d.md5 = h.Md5
432 if len(d.sha1) > 0 {
433 log.Infof("%s: SHA1 %s", d.path, d.sha1)
434 }
435 if len(d.sha256) > 0 {
436 log.Infof("%s: SHA256 %s", d.path, d.sha256)
437 }
438 if len(d.md5) > 0 {
439 log.Infof("%s: MD5 %s", d.path, d.md5)
440 }
441 }
442 } else {
443 d.sha1 = sha1
444 d.sha256 = sha256
445 d.md5 = md5
446 }
447
448 return d, nil
449 }
450
451 // ScanSource starts a scan of the local repository
452 func ScanSource(r *database.Redis, forceRehash bool, stop <-chan struct{}) (err error) {
453 s := &sourcescanner{}
454
455 conn := r.Get()
456 defer conn.Close()
457
458 if conn.Err() != nil {
459 return conn.Err()
460 }
461
462 sourceFiles := make([]*filedata, 0, 1000)
463
464 //TODO lock atomically inside redis to avoid two simultaneous scan
465
466 if _, err := os.Stat(GetConfig().Repository); os.IsNotExist(err) {
467 return fmt.Errorf("%s: No such file or directory", GetConfig().Repository)
468 }
469
470 log.Info("[source] Scanning the filesystem...")
471 err = filepath.Walk(GetConfig().Repository, func(path string, f os.FileInfo, err error) error {
472 fd, err := s.walkSource(conn, path, f, forceRehash, err)
473 if err != nil {
474 return err
475 }
476 if fd != nil {
477 sourceFiles = append(sourceFiles, fd)
478 }
479 return nil
480 })
481
482 if utils.IsStopped(stop) {
483 return ErrScanAborted
484 }
485 if err != nil {
486 return err
487 }
488 log.Info("[source] Indexing the files...")
489
490 lock := network.NewClusterLock(r, "SOURCE_REPO_SYNC", "source repository")
491
492 retry := 10
493 for {
494 if retry == 0 {
495 return ErrScanInProgress
496 }
497 done, err := lock.Get()
498 if err != nil {
499 return err
500 } else if done != nil {
501 break
502 }
503 time.Sleep(1 * time.Second)
504 retry--
505 }
506
507 defer lock.Release()
508
509 conn.Send("MULTI")
510
511 // Remove any left over
512 conn.Send("DEL", "FILES_TMP")
513
514 // Add all the files to a temporary key
515 count := 0
516 for _, e := range sourceFiles {
517 conn.Send("SADD", "FILES_TMP", e.path)
518 count++
519 }
520
521 _, err = conn.Do("EXEC")
522 if err != nil {
523 return err
524 }
525
526 // Do a diff between the sets to get the removed files
527 toremove, err := redis.Values(conn.Do("SDIFF", "FILES", "FILES_TMP"))
528 if err != nil {
529 return err
530 }
531
532 // Create/Update the files' hash keys with the fresh infos
533 conn.Send("MULTI")
534 for _, e := range sourceFiles {
535 conn.Send("HSET", fmt.Sprintf("FILE_%s", e.path),
536 "size", e.size,
537 "modTime", e.modTime,
538 "sha1", e.sha1,
539 "sha256", e.sha256,
540 "md5", e.md5)
541
542 // Publish update
543 database.SendPublish(conn, database.FILE_UPDATE, e.path)
544 }
545
546 // Remove old keys
547 if len(toremove) > 0 {
548 for _, e := range toremove {
549 conn.Send("DEL", fmt.Sprintf("FILE_%s", e))
550
551 // Publish update
552 database.SendPublish(conn, database.FILE_UPDATE, fmt.Sprintf("%s", e))
553 }
554 }
555
556 // Finally rename the temporary sets containing the list
557 // of files to the production key
558 conn.Send("RENAME", "FILES_TMP", "FILES")
559
560 _, err = conn.Do("EXEC")
561 if err != nil {
562 return err
563 }
564
565 log.Infof("[source] Indexed %d files, %d removed", count, len(toremove))
566
567 return nil
568 }