Debian Codegraph @

rpc/rpc.go

raw
1 // Copyright (c) 2014-2019 Ludovic Fauvet
2 // Licensed under the MIT license
3
4 package rpc
5
6 import (
7 "errors"
8 "fmt"
9 "log"
10 "net"
11 "net/url"
12 "os"
13 "regexp"
14 "runtime"
15 "strconv"
16 "strings"
17 "sync"
18 "syscall"
19
20 . "github.com/etix/mirrorbits/config"
21 "github.com/etix/mirrorbits/core"
22 "github.com/etix/mirrorbits/database"
23 "github.com/etix/mirrorbits/mirrors"
24 "github.com/etix/mirrorbits/network"
25 "github.com/etix/mirrorbits/scan"
26 "github.com/etix/mirrorbits/utils"
27 "github.com/golang/protobuf/ptypes"
28 "github.com/golang/protobuf/ptypes/empty"
29 "github.com/gomodule/redigo/redis"
30 context "golang.org/x/net/context"
31 grpc "google.golang.org/grpc"
32 "google.golang.org/grpc/codes"
33 "google.golang.org/grpc/reflection"
34 "google.golang.org/grpc/status"
35 "gopkg.in/yaml.v3"
36 )
37
38 var (
39 // ErrNameAlreadyTaken is returned when the request name is already taken by another mirror
40 ErrNameAlreadyTaken = errors.New("name already taken")
41 )
42
43 // CLI object handles the server side RPC of the CLI
44 type CLI struct {
45 listener net.Listener
46 server *grpc.Server
47 sig chan<- os.Signal
48 redis *database.Redis
49 cache *mirrors.Cache
50 }
51
52 func (c *CLI) Start() error {
53 var err error
54 c.listener, err = net.Listen("tcp", GetConfig().RPCListenAddress)
55 if err != nil {
56 return err
57 }
58 c.server = grpc.NewServer(
59 grpc.UnaryInterceptor(UnaryInterceptor),
60 grpc.StreamInterceptor(StreamInterceptor),
61 )
62 RegisterCLIServer(c.server, c)
63 reflection.Register(c.server)
64 go func() {
65 if err := c.server.Serve(c.listener); err != nil {
66 log.Fatalf("failed to serve rpc: %v", err)
67 }
68 }()
69 return nil
70 }
71
72 func (c *CLI) Close() error {
73 c.server.Stop()
74 return c.listener.Close()
75 }
76
77 func (c *CLI) SetSignals(sig chan<- os.Signal) {
78 c.sig = sig
79 }
80
81 func (c *CLI) SetDatabase(r *database.Redis) {
82 c.redis = r
83 }
84
85 func (c *CLI) SetCache(cache *mirrors.Cache) {
86 c.cache = cache
87 }
88
89 func (c *CLI) Ping(context.Context, *empty.Empty) (*empty.Empty, error) {
90 return &empty.Empty{}, nil
91 }
92
93 func (c *CLI) GetVersion(context.Context, *empty.Empty) (*VersionReply, error) {
94 return &VersionReply{
95 Version: core.VERSION,
96 Build: core.BUILD + core.DEV,
97 GoVersion: runtime.Version(),
98 OS: runtime.GOOS,
99 Arch: runtime.GOARCH,
100 GoMaxProcs: int32(runtime.GOMAXPROCS(0)),
101 }, nil
102 }
103
104 func (c *CLI) Upgrade(ctx context.Context, in *empty.Empty) (*empty.Empty, error) {
105 select {
106 case c.sig <- syscall.SIGUSR2:
107 default:
108 return nil, status.Error(codes.Internal, "signal handler not ready")
109 }
110 return &empty.Empty{}, nil
111 }
112
113 func (c *CLI) Reload(ctx context.Context, in *empty.Empty) (*empty.Empty, error) {
114 select {
115 case c.sig <- syscall.SIGHUP:
116 default:
117 return nil, status.Error(codes.Internal, "signal handler not ready")
118 }
119 return &empty.Empty{}, nil
120 }
121
122 func (c *CLI) MatchMirror(ctx context.Context, in *MatchRequest) (*MatchReply, error) {
123 if c.redis == nil {
124 return nil, status.Error(codes.Internal, "database not ready")
125 }
126
127 mirrors, err := c.redis.GetListOfMirrors()
128 if err != nil {
129 return nil, fmt.Errorf("can't fetch the list of mirrors: %w", err)
130 }
131
132 reply := &MatchReply{
133 Mirrors: matchMirrorsByPattern(mirrors, in.Pattern),
134 }
135
136 return reply, nil
137 }
138
139 // matchMirrorsByPattern returns a list of mirrors:
140 // - if the pattern matches a mirror's name exactly, only that mirror is returned
141 // - otherwise, all mirrors containing the pattern as a substring are returned
142 // - all matches are case-insensitive
143 // This allows a mirror whose name is a substring of other mirror names
144 // (e.g. "fcix.net" vs. "mirror.fcix.net") to still be matched unambiguously.
145 func matchMirrorsByPattern(mirrors map[int]string, pattern string) []*MirrorID {
146 lowerPattern := strings.ToLower(pattern)
147
148 var matches []*MirrorID
149 for id, name := range mirrors {
150 lowerName := strings.ToLower(name)
151 if lowerName == lowerPattern {
152 return []*MirrorID{{
153 ID: int32(id),
154 Name: name,
155 }}
156 }
157 if strings.Contains(lowerName, lowerPattern) {
158 matches = append(matches, &MirrorID{
159 ID: int32(id),
160 Name: name,
161 })
162 }
163 }
164
165 return matches
166 }
167
168 func (c *CLI) ChangeStatus(ctx context.Context, in *ChangeStatusRequest) (*empty.Empty, error) {
169 if in.ID <= 0 {
170 return nil, status.Error(codes.FailedPrecondition, "invalid mirror id")
171 }
172
173 var err error
174
175 switch in.Enabled {
176 case true:
177 err = mirrors.EnableMirror(c.redis, int(in.ID))
178 case false:
179 err = mirrors.DisableMirror(c.redis, int(in.ID))
180 }
181
182 return &empty.Empty{}, err
183 }
184
185 func (c *CLI) List(ctx context.Context, in *empty.Empty) (*MirrorListReply, error) {
186 conn, err := c.redis.Connect()
187 if err != nil {
188 return nil, err
189 }
190 defer conn.Close()
191
192 mirrorsIDs, err := c.redis.GetListOfMirrors()
193 if err != nil {
194 return nil, fmt.Errorf("can't fetch the list of mirrors: %w", err)
195 }
196
197 conn.Send("MULTI")
198 for id := range mirrorsIDs {
199 conn.Send("HGETALL", fmt.Sprintf("MIRROR_%d", id))
200 }
201
202 res, err := redis.Values(conn.Do("EXEC"))
203 if err != nil {
204 return nil, fmt.Errorf("database error: %w", err)
205 }
206
207 reply := &MirrorListReply{}
208
209 for _, e := range res {
210 var mirror mirrors.Mirror
211 res, ok := e.([]any)
212 if !ok {
213 return nil, errors.New("typecast failed")
214 }
215 err = redis.ScanStruct([]any(res), &mirror)
216 if err != nil {
217 return nil, fmt.Errorf("scan struct failed: %w", err)
218 }
219 m, err := MirrorToRPC(&mirror)
220 if err != nil {
221 return nil, err
222 }
223 reply.Mirrors = append(reply.Mirrors, m)
224 }
225
226 return reply, nil
227 }
228
229 func (c *CLI) MirrorInfo(ctx context.Context, in *MirrorIDRequest) (*Mirror, error) {
230 if in.ID <= 0 {
231 return nil, status.Error(codes.FailedPrecondition, "invalid mirror id")
232 }
233
234 conn, err := c.redis.Connect()
235 if err != nil {
236 return nil, err
237 }
238 defer conn.Close()
239
240 m, err := redis.Values(conn.Do("HGETALL", fmt.Sprintf("MIRROR_%d", in.ID)))
241 if err != nil {
242 return nil, err
243 }
244
245 var mi mirrors.Mirror
246 err = redis.ScanStruct(m, &mi)
247 if err != nil {
248 return nil, err
249 }
250
251 rpcm, err := MirrorToRPC(&mi)
252 if err != nil {
253 return nil, err
254 }
255
256 return rpcm, nil
257 }
258
259 func (c *CLI) GeoUpdateMirror(ctx context.Context, in *MirrorIDRequest) (*GeoUpdateMirrorReply, error) {
260 if in.ID <= 0 {
261 return nil, status.Error(codes.FailedPrecondition, "invalid mirror id")
262 }
263
264 conn, err := c.redis.Connect()
265 if err != nil {
266 return nil, err
267 }
268 defer conn.Close()
269
270 m, err := redis.Values(conn.Do("HGETALL", fmt.Sprintf("MIRROR_%d", in.ID)))
271 if err != nil {
272 return nil, err
273 }
274
275 var mirror mirrors.Mirror
276 err = redis.ScanStruct(m, &mirror)
277 if err != nil {
278 return nil, err
279 }
280
281 var u *url.URL
282 if utils.HasAnyPrefix(mirror.HttpURL, "http://", "https://") {
283 u, err = url.Parse(mirror.HttpURL)
284 } else {
285 u, err = url.Parse("http://" + mirror.HttpURL)
286 }
287 if err != nil {
288 return nil, fmt.Errorf("can't parse http url: %w", err)
289 }
290
291 reply := &GeoUpdateMirrorReply{}
292
293 ip, err := network.LookupMirrorIP(u.Host)
294 if err == network.ErrMultipleAddresses {
295 reply.Warnings = append(reply.Warnings,
296 "Warning: the hostname returned more than one address. Assuming they're sharing the same location.")
297 } else if err != nil {
298 return nil, fmt.Errorf("IP lookup failed: %w", err)
299 }
300
301 geo := network.NewGeoIP()
302 if err := geo.LoadGeoIP(); err != nil {
303 return nil, err
304 }
305
306 geoRec := geo.GetRecord(ip)
307 if geoRec.IsValid() {
308 original := mirror
309 mirror.Latitude = geoRec.Latitude
310 mirror.Longitude = geoRec.Longitude
311 mirror.Asnum = geoRec.ASNum
312 // We need to sanitize, as we're going to do a diff below,
313 // and the mirror fields are sanitized.
314 continent := utils.SanitizeLocationCodes(geoRec.ContinentCode)
315 country := utils.SanitizeLocationCodes(geoRec.CountryCode)
316 // ContinentCode is the easy one.
317 mirror.ContinentCode = continent
318 // CountryCodes needs special care: it might have been modified
319 // by user in order to list the countries that this mirror is
320 // expected to serve. Therefore we check if the country from
321 // the GeoIP record is included in the mirror country(ies), and
322 // if that's the case we don't touch it.
323 if !utils.IsInSlice(country, strings.Fields(mirror.CountryCodes)) {
324 mirror.CountryCodes = country
325 }
326 reply.Mirror, err = MirrorToRPC(&mirror)
327 if err != nil {
328 return nil, err
329 }
330 reply.Diff = createDiff(&original, &mirror)
331 } else {
332 reply.Warnings = append(reply.Warnings,
333 "Warning: unable to guess the geographic location of this mirror")
334 }
335
336 return reply, nil
337 }
338
339 func (c *CLI) AddMirror(ctx context.Context, in *Mirror) (*AddMirrorReply, error) {
340 mirror, err := MirrorFromRPC(in)
341 if err != nil {
342 return nil, err
343 }
344
345 if mirror.ID != 0 {
346 return nil, status.Error(codes.FailedPrecondition, "unexpected ID")
347 }
348
349 var u *url.URL
350 if utils.HasAnyPrefix(mirror.HttpURL, "http://", "https://") {
351 u, err = url.Parse(mirror.HttpURL)
352 } else {
353 u, err = url.Parse("http://" + mirror.HttpURL)
354 }
355 if err != nil {
356 return nil, fmt.Errorf("can't parse http url: %w", err)
357 }
358
359 reply := &AddMirrorReply{}
360
361 ip, err := network.LookupMirrorIP(u.Host)
362 if err == network.ErrMultipleAddresses {
363 reply.Warnings = append(reply.Warnings,
364 "Warning: the hostname returned more than one address. Assuming they're sharing the same location.")
365 } else if err != nil {
366 return nil, fmt.Errorf("IP lookup failed: %w", err)
367 }
368
369 geo := network.NewGeoIP()
370 if err := geo.LoadGeoIP(); err != nil {
371 return nil, err
372 }
373
374 geoRec := geo.GetRecord(ip)
375 if geoRec.IsValid() {
376 mirror.Latitude = geoRec.Latitude
377 mirror.Longitude = geoRec.Longitude
378 mirror.ContinentCode = geoRec.ContinentCode
379 mirror.CountryCodes = geoRec.CountryCode
380 mirror.Asnum = geoRec.ASNum
381
382 reply.Latitude = geoRec.Latitude
383 reply.Longitude = geoRec.Longitude
384 reply.Continent = geoRec.ContinentCode
385 reply.Country = geoRec.Country
386 reply.ASN = fmt.Sprintf("%s (%d)", geoRec.ASName, geoRec.ASNum)
387 } else {
388 reply.Warnings = append(reply.Warnings,
389 "Warning: unable to guess the geographic location of this mirror")
390 }
391
392 return reply, c.setMirror(mirror)
393 }
394
395 func (c *CLI) UpdateMirror(ctx context.Context, in *Mirror) (*UpdateMirrorReply, error) {
396 mirror, err := MirrorFromRPC(in)
397 if err != nil {
398 return nil, err
399 }
400
401 if mirror.ID <= 0 {
402 return nil, status.Error(codes.FailedPrecondition, "invalid mirror id")
403 }
404
405 conn, err := c.redis.Connect()
406 if err != nil {
407 return &UpdateMirrorReply{}, err
408 }
409 defer conn.Close()
410
411 m, err := redis.Values(conn.Do("HGETALL", fmt.Sprintf("MIRROR_%d", mirror.ID)))
412 if err != nil {
413 return nil, err
414 }
415
416 var original mirrors.Mirror
417 err = redis.ScanStruct(m, &original)
418 if err != nil {
419 return nil, err
420 }
421
422 diff := createDiff(&original, mirror)
423
424 return &UpdateMirrorReply{
425 Diff: diff,
426 }, c.setMirror(mirror)
427 }
428
429 func createDiff(mirror1, mirror2 *mirrors.Mirror) (out string) {
430 yamlo, _ := yaml.Marshal(mirror1)
431 yamln, _ := yaml.Marshal(mirror2)
432
433 splito := strings.Split(string(yamlo), "\n")
434 splitn := strings.Split(string(yamln), "\n")
435
436 for i, l := range splito {
437 if l != splitn[i] {
438 out += fmt.Sprintf("- %s\n+ %s\n", l, splitn[i])
439 }
440 }
441
442 return
443 }
444
445 func (c *CLI) setMirror(mirror *mirrors.Mirror) error {
446 conn, err := c.redis.Connect()
447 if err != nil {
448 return err
449 }
450 defer conn.Close()
451
452 mirrorsIDs, err := c.redis.GetListOfMirrors()
453 if err != nil {
454 return fmt.Errorf("can't fetch the list of mirrors: %w", err)
455 }
456
457 isUpdate := false
458
459 for id, name := range mirrorsIDs {
460 if id == mirror.ID {
461 isUpdate = true
462 }
463 if mirror.ID != id && name == mirror.Name {
464 return ErrNameAlreadyTaken
465 }
466 }
467
468 if mirror.ID <= 0 {
469 // Generate a new ID
470 mirror.ID, err = redis.Int(conn.Do("INCR", "LAST_MID"))
471 if err != nil {
472 return fmt.Errorf("failed creating a new id: %w", err)
473 }
474 }
475
476 // Reformat contry codes
477 mirror.CountryCodes = utils.SanitizeLocationCodes(mirror.CountryCodes)
478 mirror.ExcludedCountryCodes = utils.SanitizeLocationCodes(mirror.ExcludedCountryCodes)
479
480 // Reformat continent code
481 mirror.ContinentCode = utils.SanitizeLocationCodes(mirror.ContinentCode)
482
483 // Normalize URLs
484 mirror.HttpURL = utils.NormalizeURL(mirror.HttpURL)
485 mirror.RsyncURL = utils.NormalizeURL(mirror.RsyncURL)
486 mirror.FtpURL = utils.NormalizeURL(mirror.FtpURL)
487
488 // Save the values back into redis
489 conn.Send("MULTI")
490 conn.Send("HSET", fmt.Sprintf("MIRROR_%d", mirror.ID),
491 "ID", mirror.ID,
492 "name", mirror.Name,
493 "http", mirror.HttpURL,
494 "rsync", mirror.RsyncURL,
495 "ftp", mirror.FtpURL,
496 "sponsorName", mirror.SponsorName,
497 "sponsorURL", mirror.SponsorURL,
498 "sponsorLogo", mirror.SponsorLogoURL,
499 "adminName", mirror.AdminName,
500 "adminEmail", mirror.AdminEmail,
501 "customData", mirror.CustomData,
502 "continentOnly", mirror.ContinentOnly,
503 "countryOnly", mirror.CountryOnly,
504 "asOnly", mirror.ASOnly,
505 "score", mirror.Score,
506 "latitude", mirror.Latitude,
507 "longitude", mirror.Longitude,
508 "continentCode", mirror.ContinentCode,
509 "countryCodes", mirror.CountryCodes,
510 "excludedCountryCodes", mirror.ExcludedCountryCodes,
511 "asnum", mirror.Asnum,
512 "comment", mirror.Comment,
513 "allowredirects", mirror.AllowRedirects,
514 "enabled", mirror.Enabled)
515
516 // Reset state to down for unsupported protocol
517 if strings.HasPrefix(mirror.HttpURL, "http://") {
518 conn.Send("HSET", fmt.Sprintf("MIRROR_%d", mirror.ID),
519 "httpsUp", false)
520 } else if strings.HasPrefix(mirror.HttpURL, "https://") {
521 conn.Send("HSET", fmt.Sprintf("MIRROR_%d", mirror.ID),
522 "httpUp", false)
523 }
524
525 // The name of the mirror has been changed.
526 conn.Send("HSET", "MIRRORS", mirror.ID, mirror.Name)
527
528 _, err = conn.Do("EXEC")
529 if err != nil {
530 return fmt.Errorf("couldn't save the mirror configuration: %w", err)
531 }
532
533 // Publish update
534 database.Publish(conn, database.MIRROR_UPDATE, strconv.Itoa(mirror.ID))
535
536 if isUpdate {
537 // This was an update of an existing mirror
538 mirrors.PushLog(c.redis, mirrors.NewLogEdited(mirror.ID))
539 } else {
540 // We just added a new mirror
541 mirrors.PushLog(c.redis, mirrors.NewLogAdded(mirror.ID))
542 }
543
544 return nil
545 }
546
547 func (c *CLI) RemoveMirror(ctx context.Context, in *MirrorIDRequest) (*empty.Empty, error) {
548 if in.ID <= 0 {
549 return nil, status.Error(codes.FailedPrecondition, "invalid mirror id")
550 }
551
552 conn, err := c.redis.Connect()
553 if err != nil {
554 return nil, err
555 }
556 defer conn.Close()
557
558 // First disable the mirror
559 err = mirrors.DisableMirror(c.redis, int(in.ID))
560 if err != nil {
561 return nil, fmt.Errorf("unable to disable the mirror: %w", err)
562 }
563
564 // Get all files supported by the given mirror
565 files, err := redis.Strings(conn.Do("SMEMBERS", fmt.Sprintf("MIRRORFILES_%d", in.ID)))
566 if err != nil {
567 return nil, fmt.Errorf("unable to fetch the file list: %w", err)
568 }
569
570 conn.Send("MULTI")
571
572 // Remove each FILEINFO / FILEMIRRORS
573 for _, file := range files {
574 conn.Send("DEL", fmt.Sprintf("FILEINFO_%d_%s", in.ID, file))
575 conn.Send("SREM", fmt.Sprintf("FILEMIRRORS_%s", file), in.ID)
576 conn.Send("PUBLISH", database.MIRROR_FILE_UPDATE, fmt.Sprintf("%d %s", in.ID, file))
577 }
578
579 // Remove all other keys
580 conn.Send("DEL",
581 fmt.Sprintf("MIRROR_%d", in.ID),
582 fmt.Sprintf("MIRRORFILES_%d", in.ID),
583 fmt.Sprintf("MIRRORFILESTMP_%d", in.ID),
584 fmt.Sprintf("HANDLEDFILES_%d", in.ID),
585 fmt.Sprintf("SCANNING_%d", in.ID),
586 fmt.Sprintf("MIRRORLOGS_%d", in.ID))
587
588 // Remove the last reference
589 conn.Send("HDEL", "MIRRORS", in.ID)
590
591 _, err = conn.Do("EXEC")
592 if err != nil {
593 return nil, fmt.Errorf("operation failed: %w", err)
594 }
595
596 // Publish update
597 database.Publish(conn, database.MIRROR_UPDATE, strconv.Itoa(int(in.ID)))
598
599 return &empty.Empty{}, nil
600 }
601
602 func (c *CLI) RefreshRepository(ctx context.Context, in *RefreshRepositoryRequest) (*empty.Empty, error) {
603 return &empty.Empty{}, scan.ScanSource(c.redis, in.Rehash, nil)
604 }
605
606 func (c *CLI) ScanMirror(ctx context.Context, in *ScanMirrorRequest) (*ScanMirrorReply, error) {
607 if in.ID <= 0 {
608 return nil, status.Error(codes.FailedPrecondition, "invalid mirror id")
609 }
610
611 conn, err := c.redis.Connect()
612 if err != nil {
613 return nil, err
614 }
615 defer conn.Close()
616
617 // Check if the local repository has been scanned already
618 exists, err := redis.Bool(conn.Do("EXISTS", "FILES"))
619 if err != nil {
620 return nil, err
621 }
622 if !exists {
623 return nil, status.Error(codes.FailedPrecondition, "local repository not yet indexed. You should run 'refresh' first!")
624 }
625
626 key := fmt.Sprintf("MIRROR_%d", in.ID)
627 m, err := redis.Values(conn.Do("HGETALL", key))
628 if err != nil {
629 return nil, err
630 }
631
632 var mirror mirrors.Mirror
633 err = redis.ScanStruct(m, &mirror)
634 if err != nil {
635 return nil, err
636 }
637
638 var wg sync.WaitGroup
639 trace := scan.NewTraceHandler(c.redis, make(<-chan struct{}))
640
641 wg.Add(1)
642 go func() {
643 defer wg.Done()
644 err := trace.GetLastUpdate(mirror)
645 if err != nil && err != scan.ErrNoTrace {
646 var numError *strconv.NumError
647 if errors.As(err, &numError) {
648 if numError.Err == strconv.ErrSyntax {
649 //log.Warningf("[%s] parsing trace file failed: %s is not a valid timestamp", mirror.Name, strconv.Quote(numError.Num))
650 return
651 }
652 } else {
653 //log.Warningf("[%s] fetching trace file failed: %s", mirror.Name, err)
654 }
655 }
656 }()
657
658 err = scan.ErrNoSyncMethod
659 var res *scan.ScanResult
660
661 if in.Protocol == ScanMirrorRequest_ALL {
662 // Use rsync (if applicable) and fallback to FTP
663 if mirror.RsyncURL != "" {
664 res, err = scan.Scan(core.RSYNC, c.redis, c.cache, mirror.RsyncURL, mirror.ID, ctx.Done())
665 }
666 if err != nil && mirror.FtpURL != "" {
667 res, err = scan.Scan(core.FTP, c.redis, c.cache, mirror.FtpURL, mirror.ID, ctx.Done())
668 }
669 } else {
670 // Use the requested protocol
671 if in.Protocol == ScanMirrorRequest_RSYNC && mirror.RsyncURL != "" {
672 res, err = scan.Scan(core.RSYNC, c.redis, c.cache, mirror.RsyncURL, mirror.ID, ctx.Done())
673 } else if in.Protocol == ScanMirrorRequest_FTP && mirror.FtpURL != "" {
674 res, err = scan.Scan(core.FTP, c.redis, c.cache, mirror.FtpURL, mirror.ID, ctx.Done())
675 }
676 }
677
678 if err != nil {
679 return nil, errors.New(fmt.Sprintf("scanning %s failed: %s", mirror.Name, err))
680 }
681
682 reply := &ScanMirrorReply{
683 FilesIndexed: res.FilesIndexed,
684 KnownIndexed: res.KnownIndexed,
685 Removed: res.Removed,
686 TZOffsetMs: res.TZOffsetMs,
687 }
688
689 // Finally enable the mirror if requested
690 if err == nil && in.AutoEnable == true {
691 if err := mirrors.EnableMirror(c.redis, mirror.ID); err != nil {
692 return nil, fmt.Errorf("couldn't enable the mirror: %w", err)
693 }
694 reply.Enabled = true
695 }
696
697 wg.Wait()
698
699 return reply, nil
700 }
701
702 func (c *CLI) StatsFile(ctx context.Context, in *StatsFileRequest) (*StatsFileReply, error) {
703 conn, err := c.redis.Connect()
704 if err != nil {
705 return nil, err
706 }
707 defer conn.Close()
708
709 // Convert the timestamps
710 start, err := ptypes.Timestamp(in.DateStart)
711 if err != nil {
712 return nil, err
713 }
714 end, err := ptypes.Timestamp(in.DateEnd)
715 if err != nil {
716 return nil, err
717 }
718
719 // Compile the regex pattern
720 re, err := regexp.Compile(in.Pattern)
721 if err != nil {
722 return nil, err
723 }
724
725 // Generate the list of redis key for the period
726 tkcoverage := utils.TimeKeyCoverage(start, end)
727
728 // Prepare the transaction
729 conn.Send("MULTI")
730
731 for _, k := range tkcoverage {
732 conn.Send("HGETALL", "STATS_FILE_"+k)
733 }
734
735 stats, err := redis.Values(conn.Do("EXEC"))
736 if err != nil {
737 return nil, fmt.Errorf("can't fetch stats: %w", err)
738 }
739
740 reply := &StatsFileReply{
741 Files: make(map[string]int64),
742 }
743
744 for _, res := range stats {
745 line, ok := res.([]any)
746 if !ok {
747 return nil, errors.New("typecast failed")
748 }
749 stats := []any(line)
750 for i := 0; i < len(stats); i += 2 {
751 path, _ := redis.String(stats[i], nil)
752 matched := re.MatchString(path)
753 if matched {
754 reqs, _ := redis.Int64(stats[i+1], nil)
755 reply.Files[path] += reqs
756 }
757 }
758 }
759
760 return reply, nil
761 }
762
763 func (c *CLI) StatsMirror(ctx context.Context, in *StatsMirrorRequest) (*StatsMirrorReply, error) {
764 if in.ID <= 0 {
765 return nil, status.Error(codes.FailedPrecondition, "invalid mirror id")
766 }
767
768 conn, err := c.redis.Connect()
769 if err != nil {
770 return nil, err
771 }
772 defer conn.Close()
773
774 // Convert the timestamps
775 start, err := ptypes.Timestamp(in.DateStart)
776 if err != nil {
777 return nil, err
778 }
779 end, err := ptypes.Timestamp(in.DateEnd)
780 if err != nil {
781 return nil, err
782 }
783
784 // Generate the list of redis key for the period
785 tkcoverage := utils.TimeKeyCoverage(start, end)
786
787 conn.Send("MULTI")
788
789 // Fetch the stats
790 for _, k := range tkcoverage {
791 conn.Send("HGET", "STATS_MIRROR_"+k, in.ID)
792 conn.Send("HGET", "STATS_MIRROR_BYTES_"+k, in.ID)
793 }
794
795 stats, err := redis.Strings(conn.Do("EXEC"))
796 if err != nil {
797 return nil, fmt.Errorf("can't fetch stats: %w", err)
798 }
799
800 // Fetch the mirror struct
801 m, err := redis.Values(conn.Do("HGETALL", fmt.Sprintf("MIRROR_%d", in.ID)))
802 if err != nil {
803 return nil, fmt.Errorf("can't fetch mirror: %w", err)
804 }
805
806 reply := &StatsMirrorReply{}
807
808 var mirror mirrors.Mirror
809 err = redis.ScanStruct(m, &mirror)
810 if err != nil {
811 return nil, fmt.Errorf("stats error: %w", err)
812 }
813
814 reply.Mirror, err = MirrorToRPC(&mirror)
815 if err != nil {
816 return nil, fmt.Errorf("stats error: %w", err)
817 }
818
819 for i := 0; i < len(stats); i += 2 {
820 v1, _ := strconv.ParseInt(stats[i], 10, 64)
821 v2, _ := strconv.ParseInt(stats[i+1], 10, 64)
822 reply.Requests += v1
823 reply.Bytes += v2
824 }
825
826 return reply, nil
827 }
828
829 func (c *CLI) GetMirrorLogs(ctx context.Context, in *GetMirrorLogsRequest) (*GetMirrorLogsReply, error) {
830 if in.ID <= 0 {
831 return nil, status.Error(codes.FailedPrecondition, "invalid mirror id")
832 }
833
834 lines, err := mirrors.ReadLogs(c.redis, int(in.ID), int(in.MaxResults))
835 if err != nil {
836 return nil, fmt.Errorf("mirror logs error: %w", err)
837 }
838
839 return &GetMirrorLogsReply{Line: lines}, nil
840 }