-
Notifications
You must be signed in to change notification settings - Fork 278
/
manager_server_v2.go
847 lines (748 loc) · 27.3 KB
/
manager_server_v2.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
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
/*
* Copyright 2023 The Dragonfly Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package rpcserver
import (
"context"
"encoding/json"
"errors"
"io"
cachev9 "github.com/go-redis/cache/v9"
"github.com/redis/go-redis/v9"
"google.golang.org/grpc/codes"
"google.golang.org/grpc/status"
"google.golang.org/protobuf/types/known/emptypb"
"gorm.io/gorm"
commonv2 "d7y.io/api/v2/pkg/apis/common/v2"
managerv2 "d7y.io/api/v2/pkg/apis/manager/v2"
logger "d7y.io/dragonfly/v2/internal/dflog"
"d7y.io/dragonfly/v2/manager/cache"
"d7y.io/dragonfly/v2/manager/config"
"d7y.io/dragonfly/v2/manager/database"
"d7y.io/dragonfly/v2/manager/metrics"
"d7y.io/dragonfly/v2/manager/models"
"d7y.io/dragonfly/v2/manager/searcher"
"d7y.io/dragonfly/v2/manager/types"
pkgredis "d7y.io/dragonfly/v2/pkg/redis"
"d7y.io/dragonfly/v2/pkg/slices"
)
// managerServerV2 is v2 version of the manager grpc server.
type managerServerV2 struct {
// Manager configuration.
config *config.Config
// GORM instance.
db *gorm.DB
// Redis universal client interface.
rdb redis.UniversalClient
// Cache instance.
cache *cache.Cache
// Searcher interface.
searcher searcher.Searcher
}
// newManagerServerV2 returns v2 version of the manager server.
func newManagerServerV2(cfg *config.Config, database *database.Database, cache *cache.Cache, searcher searcher.Searcher) managerv2.ManagerServer {
return &managerServerV2{
config: cfg,
db: database.DB,
rdb: database.RDB,
cache: cache,
searcher: searcher,
}
}
// Get SeedPeer and SeedPeer cluster configuration.
func (s *managerServerV2) GetSeedPeer(ctx context.Context, req *managerv2.GetSeedPeerRequest) (*managerv2.SeedPeer, error) {
log := logger.WithHostnameAndIP(req.Hostname, req.Ip)
cacheKey := pkgredis.MakeSeedPeerKeyInManager(uint(req.SeedPeerClusterId), req.Hostname, req.Ip)
// Cache hit.
var pbSeedPeer managerv2.SeedPeer
if err := s.cache.Get(ctx, cacheKey, &pbSeedPeer); err != nil {
log.Warnf("%s cache miss because of %s", cacheKey, err.Error())
} else {
log.Debugf("%s cache hit", cacheKey)
return &pbSeedPeer, nil
}
// Cache miss and search seed peer.
seedPeer := models.SeedPeer{}
if err := s.db.WithContext(ctx).Preload("SeedPeerCluster").Preload("SeedPeerCluster.SchedulerClusters.Schedulers", &models.Scheduler{
State: models.SchedulerStateActive,
}).First(&seedPeer, &models.SeedPeer{
Hostname: req.Hostname,
SeedPeerClusterID: uint(req.SeedPeerClusterId),
}).Error; err != nil {
return nil, status.Error(codes.Internal, err.Error())
}
// Marshal config of seed peer cluster.
config, err := seedPeer.SeedPeerCluster.Config.MarshalJSON()
if err != nil {
return nil, status.Error(codes.DataLoss, err.Error())
}
// Construct schedulers.
var pbSchedulers []*managerv2.Scheduler
for _, schedulerCluster := range seedPeer.SeedPeerCluster.SchedulerClusters {
for _, scheduler := range schedulerCluster.Schedulers {
// Marshal features of scheduler.
features, err := scheduler.Features.MarshalJSON()
if err != nil {
return nil, status.Error(codes.DataLoss, err.Error())
}
pbSchedulers = append(pbSchedulers, &managerv2.Scheduler{
Id: uint64(scheduler.ID),
Hostname: scheduler.Hostname,
Idc: &scheduler.IDC,
Location: &scheduler.Location,
Ip: scheduler.IP,
Port: scheduler.Port,
State: scheduler.State,
Features: features,
})
}
}
// Construct seed peer.
pbSeedPeer = managerv2.SeedPeer{
Id: uint64(seedPeer.ID),
Type: seedPeer.Type,
Hostname: seedPeer.Hostname,
Idc: &seedPeer.IDC,
Location: &seedPeer.Location,
Ip: seedPeer.IP,
Port: seedPeer.Port,
DownloadPort: seedPeer.DownloadPort,
State: seedPeer.State,
SeedPeerClusterId: uint64(seedPeer.SeedPeerClusterID),
SeedPeerCluster: &managerv2.SeedPeerCluster{
Id: uint64(seedPeer.SeedPeerCluster.ID),
Name: seedPeer.SeedPeerCluster.Name,
Bio: seedPeer.SeedPeerCluster.BIO,
Config: config,
},
Schedulers: pbSchedulers,
}
// Cache data.
if err := s.cache.Once(&cachev9.Item{
Ctx: ctx,
Key: cacheKey,
Value: &pbSeedPeer,
TTL: s.cache.TTL,
}); err != nil {
log.Error(err)
}
return &pbSeedPeer, nil
}
// List acitve seed peers configuration.
func (s *managerServerV2) ListSeedPeers(ctx context.Context, req *managerv2.ListSeedPeersRequest) (*managerv2.ListSeedPeersResponse, error) {
log := logger.WithHostnameAndIP(req.Hostname, req.Ip)
log.Debugf("list seed peers, version %s, commit %s", req.Version, req.Commit)
// Cache hit.
var pbListSeedPeersResponse managerv2.ListSeedPeersResponse
cacheKey := pkgredis.MakeSeedPeersKeyForPeerInManager(req.Hostname, req.Ip)
if err := s.cache.Get(ctx, cacheKey, &pbListSeedPeersResponse); err != nil {
log.Warnf("%s cache miss because of %s", cacheKey, err.Error())
} else {
log.Debugf("%s cache hit", cacheKey)
return &pbListSeedPeersResponse, nil
}
// Cache miss and search seed peer.
seedPeer := models.SeedPeer{}
if err := s.db.WithContext(ctx).Preload("SeedPeerCluster").First(&seedPeer, models.SeedPeer{
Hostname: req.Hostname,
IP: req.Ip,
}).Error; err != nil {
return nil, status.Error(codes.Internal, err.Error())
}
var seedPeers []models.SeedPeer
if err := s.db.WithContext(ctx).Find(&seedPeers, models.SeedPeer{
State: models.SeedPeerStateActive,
SeedPeerClusterID: uint(seedPeer.SeedPeerClusterID),
}).Error; err != nil {
return nil, status.Error(codes.Internal, err.Error())
}
if len(seedPeers) == 0 {
return nil, status.Error(codes.NotFound, "seed peer not found")
}
// Construct seed peers.
for _, seedPeer := range seedPeers {
pbListSeedPeersResponse.SeedPeers = append(pbListSeedPeersResponse.SeedPeers, &managerv2.SeedPeer{
Id: uint64(seedPeer.ID),
Hostname: seedPeer.Hostname,
Type: seedPeer.Type,
Idc: &seedPeer.IDC,
Location: &seedPeer.Location,
Ip: seedPeer.IP,
Port: seedPeer.Port,
DownloadPort: seedPeer.DownloadPort,
State: seedPeer.State,
SeedPeerClusterId: uint64(seedPeer.SeedPeerClusterID),
SeedPeerCluster: &managerv2.SeedPeerCluster{
Id: uint64(seedPeer.SeedPeerCluster.ID),
Name: seedPeer.SeedPeerCluster.Name,
Bio: seedPeer.SeedPeerCluster.BIO,
},
})
}
// Cache data.
if err := s.cache.Once(&cachev9.Item{
Ctx: ctx,
Key: cacheKey,
Value: &pbListSeedPeersResponse,
TTL: s.cache.TTL,
}); err != nil {
log.Error(err)
}
return &pbListSeedPeersResponse, nil
}
// Update SeedPeer configuration.
func (s *managerServerV2) UpdateSeedPeer(ctx context.Context, req *managerv2.UpdateSeedPeerRequest) (*managerv2.SeedPeer, error) {
log := logger.WithHostnameAndIP(req.Hostname, req.Ip)
seedPeer := models.SeedPeer{}
if err := s.db.WithContext(ctx).First(&seedPeer, models.SeedPeer{
Hostname: req.Hostname,
IP: req.Ip,
Port: req.Port,
SeedPeerClusterID: uint(req.SeedPeerClusterId),
}).Error; err != nil {
if errors.Is(err, gorm.ErrRecordNotFound) {
return s.createSeedPeer(ctx, req)
}
return nil, status.Error(codes.Internal, err.Error())
}
if err := s.db.WithContext(ctx).Model(&seedPeer).Updates(models.SeedPeer{
Type: req.GetType(),
IDC: req.GetIdc(),
Location: req.GetLocation(),
IP: req.GetIp(),
Port: req.GetPort(),
DownloadPort: req.GetDownloadPort(),
State: models.SeedPeerStateActive,
SeedPeerClusterID: uint(req.GetSeedPeerClusterId()),
}).Error; err != nil {
return nil, status.Error(codes.Internal, err.Error())
}
if err := s.cache.Delete(
ctx,
pkgredis.MakeSeedPeerKeyInManager(seedPeer.SeedPeerClusterID, seedPeer.Hostname, seedPeer.IP),
); err != nil {
log.Warn(err)
}
return &managerv2.SeedPeer{
Id: uint64(seedPeer.ID),
Hostname: seedPeer.Hostname,
Type: seedPeer.Type,
Idc: &seedPeer.IDC,
Location: &seedPeer.Location,
Ip: seedPeer.IP,
Port: seedPeer.Port,
DownloadPort: seedPeer.DownloadPort,
State: seedPeer.State,
SeedPeerClusterId: uint64(seedPeer.SeedPeerClusterID),
}, nil
}
// Create SeedPeer and associate cluster.
func (s *managerServerV2) createSeedPeer(ctx context.Context, req *managerv2.UpdateSeedPeerRequest) (*managerv2.SeedPeer, error) {
seedPeer := models.SeedPeer{
Hostname: req.GetHostname(),
Type: req.GetType(),
IDC: req.GetIdc(),
Location: req.GetLocation(),
IP: req.GetIp(),
Port: req.GetPort(),
DownloadPort: req.GetDownloadPort(),
State: models.SeedPeerStateActive,
SeedPeerClusterID: uint(req.GetSeedPeerClusterId()),
}
if err := s.db.WithContext(ctx).Create(&seedPeer).Error; err != nil {
return nil, status.Error(codes.Internal, err.Error())
}
return &managerv2.SeedPeer{
Id: uint64(seedPeer.ID),
Hostname: seedPeer.Hostname,
Type: seedPeer.Type,
Idc: &seedPeer.IDC,
Location: &seedPeer.Location,
Ip: seedPeer.IP,
Port: seedPeer.Port,
DownloadPort: seedPeer.DownloadPort,
SeedPeerClusterId: uint64(seedPeer.SeedPeerClusterID),
State: seedPeer.State,
}, nil
}
// Delete SeedPeer configuration.
func (s *managerServerV2) DeleteSeedPeer(ctx context.Context, req *managerv2.DeleteSeedPeerRequest) (*emptypb.Empty, error) {
if err := s.db.WithContext(ctx).Unscoped().Delete(&models.SeedPeer{}, models.SeedPeer{
Hostname: req.Hostname,
IP: req.Ip,
SeedPeerClusterID: uint(req.SeedPeerClusterId),
}).Error; err != nil {
if errors.Is(err, gorm.ErrRecordNotFound) {
return nil, status.Error(codes.NotFound, err.Error())
}
return nil, status.Error(codes.Internal, err.Error())
}
return new(emptypb.Empty), nil
}
// Get Scheduler and Scheduler cluster configuration.
func (s *managerServerV2) GetScheduler(ctx context.Context, req *managerv2.GetSchedulerRequest) (*managerv2.Scheduler, error) {
log := logger.WithHostnameAndIP(req.Hostname, req.Ip)
cacheKey := pkgredis.MakeSchedulerKeyInManager(uint(req.SchedulerClusterId), req.Hostname, req.Ip)
// Cache hit.
var pbScheduler managerv2.Scheduler
if err := s.cache.Get(ctx, cacheKey, &pbScheduler); err != nil {
log.Warnf("%s cache miss because of %s", cacheKey, err.Error())
} else {
log.Debugf("%s cache hit", cacheKey)
return &pbScheduler, nil
}
// Cache miss and search scheduler.
scheduler := models.Scheduler{}
if err := s.db.WithContext(ctx).Preload("SchedulerCluster").Preload("SchedulerCluster.SeedPeerClusters.SeedPeers", &models.SeedPeer{
State: models.SeedPeerStateActive,
}).First(&scheduler, &models.Scheduler{
Hostname: req.Hostname,
SchedulerClusterID: uint(req.SchedulerClusterId),
}).Error; err != nil {
return nil, status.Error(codes.Internal, err.Error())
}
// Marshal config of scheduler.
schedulerClusterConfig, err := scheduler.SchedulerCluster.Config.MarshalJSON()
if err != nil {
return nil, status.Error(codes.DataLoss, err.Error())
}
// Marshal config of client.
schedulerClusterClientConfig, err := scheduler.SchedulerCluster.ClientConfig.MarshalJSON()
if err != nil {
return nil, status.Error(codes.DataLoss, err.Error())
}
// Marshal scopes of client.
schedulerClusterScopes, err := scheduler.SchedulerCluster.Scopes.MarshalJSON()
if err != nil {
return nil, status.Error(codes.DataLoss, err.Error())
}
// Construct seed peers.
var pbSeedPeers []*managerv2.SeedPeer
for _, seedPeerCluster := range scheduler.SchedulerCluster.SeedPeerClusters {
seedPeerClusterConfig, err := seedPeerCluster.Config.MarshalJSON()
if err != nil {
return nil, status.Error(codes.DataLoss, err.Error())
}
for _, seedPeer := range seedPeerCluster.SeedPeers {
pbSeedPeers = append(pbSeedPeers, &managerv2.SeedPeer{
Id: uint64(seedPeer.ID),
Hostname: seedPeer.Hostname,
Type: seedPeer.Type,
Idc: &seedPeer.IDC,
Location: &seedPeer.Location,
Ip: seedPeer.IP,
Port: seedPeer.Port,
DownloadPort: seedPeer.DownloadPort,
State: seedPeer.State,
SeedPeerClusterId: uint64(seedPeer.SeedPeerClusterID),
SeedPeerCluster: &managerv2.SeedPeerCluster{
Id: uint64(seedPeerCluster.ID),
Name: seedPeerCluster.Name,
Bio: seedPeerCluster.BIO,
Config: seedPeerClusterConfig,
},
})
}
}
// Marshal features of scheduler.
features, err := scheduler.Features.MarshalJSON()
if err != nil {
return nil, status.Error(codes.DataLoss, err.Error())
}
// Construct scheduler.
pbScheduler = managerv2.Scheduler{
Id: uint64(scheduler.ID),
Hostname: scheduler.Hostname,
Idc: &scheduler.IDC,
Location: &scheduler.Location,
Ip: scheduler.IP,
Port: scheduler.Port,
State: scheduler.State,
Features: features,
SchedulerClusterId: uint64(scheduler.SchedulerClusterID),
SchedulerCluster: &managerv2.SchedulerCluster{
Id: uint64(scheduler.SchedulerCluster.ID),
Name: scheduler.SchedulerCluster.Name,
Bio: scheduler.SchedulerCluster.BIO,
Config: schedulerClusterConfig,
ClientConfig: schedulerClusterClientConfig,
Scopes: schedulerClusterScopes,
},
SeedPeers: pbSeedPeers,
}
// Cache data.
if err := s.cache.Once(&cachev9.Item{
Ctx: ctx,
Key: cacheKey,
Value: &pbScheduler,
TTL: s.cache.TTL,
}); err != nil {
log.Error(err)
}
return &pbScheduler, nil
}
// Update scheduler configuration.
func (s *managerServerV2) UpdateScheduler(ctx context.Context, req *managerv2.UpdateSchedulerRequest) (*managerv2.Scheduler, error) {
log := logger.WithHostnameAndIP(req.Hostname, req.Ip)
scheduler := models.Scheduler{}
if err := s.db.WithContext(ctx).First(&scheduler, models.Scheduler{
Hostname: req.Hostname,
IP: req.Ip,
Port: req.Port,
SchedulerClusterID: uint(req.SchedulerClusterId),
}).Error; err != nil {
if errors.Is(err, gorm.ErrRecordNotFound) {
return s.createScheduler(ctx, req)
}
return nil, status.Error(codes.Internal, err.Error())
}
if err := s.db.WithContext(ctx).Model(&scheduler).Updates(models.Scheduler{
IDC: req.GetIdc(),
Location: req.GetLocation(),
IP: req.GetIp(),
Port: req.GetPort(),
SchedulerClusterID: uint(req.GetSchedulerClusterId()),
}).Error; err != nil {
return nil, status.Error(codes.Internal, err.Error())
}
if err := s.cache.Delete(
ctx,
pkgredis.MakeSchedulerKeyInManager(scheduler.SchedulerClusterID, scheduler.Hostname, scheduler.IP),
); err != nil {
log.Warn(err)
}
// Marshal features of scheduler.
features, err := scheduler.Features.MarshalJSON()
if err != nil {
return nil, status.Error(codes.DataLoss, err.Error())
}
return &managerv2.Scheduler{
Id: uint64(scheduler.ID),
Hostname: scheduler.Hostname,
Idc: &scheduler.IDC,
Location: &scheduler.Location,
Ip: scheduler.IP,
Port: scheduler.Port,
Features: features,
State: scheduler.State,
SchedulerClusterId: uint64(scheduler.SchedulerClusterID),
}, nil
}
// Create scheduler and associate cluster.
func (s *managerServerV2) createScheduler(ctx context.Context, req *managerv2.UpdateSchedulerRequest) (*managerv2.Scheduler, error) {
scheduler := models.Scheduler{
Hostname: req.GetHostname(),
IDC: req.GetIdc(),
Location: req.GetLocation(),
IP: req.GetIp(),
Port: req.GetPort(),
Features: types.DefaultSchedulerFeatures,
SchedulerClusterID: uint(req.GetSchedulerClusterId()),
}
if err := s.db.WithContext(ctx).Create(&scheduler).Error; err != nil {
return nil, status.Error(codes.Internal, err.Error())
}
// Marshal features of scheduler.
features, err := scheduler.Features.MarshalJSON()
if err != nil {
return nil, status.Error(codes.DataLoss, err.Error())
}
return &managerv2.Scheduler{
Id: uint64(scheduler.ID),
Hostname: scheduler.Hostname,
Idc: &scheduler.IDC,
Location: &scheduler.Location,
Ip: scheduler.IP,
Port: scheduler.Port,
State: scheduler.State,
Features: features,
SchedulerClusterId: uint64(scheduler.SchedulerClusterID),
}, nil
}
// List acitve schedulers configuration.
func (s *managerServerV2) ListSchedulers(ctx context.Context, req *managerv2.ListSchedulersRequest) (*managerv2.ListSchedulersResponse, error) {
log := logger.WithHostnameAndIP(req.Hostname, req.Ip)
log.Debugf("list schedulers, version %s, commit %s", req.Version, req.Commit)
metrics.SearchSchedulerClusterCount.WithLabelValues(req.Version, req.Commit).Inc()
// Cache hit.
var pbListSchedulersResponse managerv2.ListSchedulersResponse
cacheKey := pkgredis.MakeSchedulersKeyForPeerInManager(req.Hostname, req.Ip)
if err := s.cache.Get(ctx, cacheKey, &pbListSchedulersResponse); err != nil {
log.Warnf("%s cache miss because of %s", cacheKey, err.Error())
} else {
log.Debugf("%s cache hit", cacheKey)
return &pbListSchedulersResponse, nil
}
// Cache miss and search scheduler cluster.
var schedulerClusters []models.SchedulerCluster
if err := s.db.WithContext(ctx).Preload("SeedPeerClusters.SeedPeers", "state = ?", "active").Preload("Schedulers", "state = ?", "active").Find(&schedulerClusters).Error; err != nil {
return nil, status.Error(codes.Internal, err.Error())
}
// Remove schedulers which not have scehdule featrue. As OceanBase does not support JSON type,
// it is not possible to use datatypes.JSONQuery for filtering.
var tmpSchedulerClusters []models.SchedulerCluster
for _, schedulerCluster := range schedulerClusters {
var tmpSchedulers []models.Scheduler
for _, scheduler := range schedulerCluster.Schedulers {
if slices.Contains(scheduler.Features, types.SchedulerFeatureSchedule) {
tmpSchedulers = append(tmpSchedulers, scheduler)
}
}
if len(tmpSchedulers) != 0 {
schedulerCluster.Schedulers = tmpSchedulers
tmpSchedulerClusters = append(tmpSchedulerClusters, schedulerCluster)
}
}
log.Debugf("list scheduler clusters %v, idc is %s, location is %s", getSchedulerClusterNames(tmpSchedulerClusters), req.GetIdc(), req.GetLocation())
// Search optimal scheduler clusters.
// If searcher can not found candidate scheduler cluster,
// return all scheduler clusters.
var (
candidateSchedulerClusters []models.SchedulerCluster
err error
)
candidateSchedulerClusters, err = s.searcher.FindSchedulerClusters(ctx, tmpSchedulerClusters, req.Ip, req.Hostname,
map[string]string{searcher.ConditionIDC: req.GetIdc(), searcher.ConditionLocation: req.GetLocation()}, logger.CoreLogger)
if err != nil {
log.Error(err)
metrics.SearchSchedulerClusterFailureCount.WithLabelValues(req.Version, req.Commit).Inc()
candidateSchedulerClusters = schedulerClusters
}
log.Debugf("find matching scheduler cluster %v", getSchedulerClusterNames(candidateSchedulerClusters))
schedulers := []models.Scheduler{}
for _, candidateSchedulerCluster := range candidateSchedulerClusters {
for _, scheduler := range candidateSchedulerCluster.Schedulers {
scheduler.SchedulerCluster = candidateSchedulerCluster
schedulers = append(schedulers, scheduler)
}
}
// Construct schedulers.
for _, scheduler := range schedulers {
seedPeers := []*managerv2.SeedPeer{}
for _, seedPeerCluster := range scheduler.SchedulerCluster.SeedPeerClusters {
for _, seedPeer := range seedPeerCluster.SeedPeers {
seedPeers = append(seedPeers, &managerv2.SeedPeer{
Id: uint64(seedPeer.ID),
Hostname: seedPeer.Hostname,
Type: seedPeer.Type,
Idc: &seedPeer.IDC,
Location: &seedPeer.Location,
Ip: seedPeer.IP,
Port: seedPeer.Port,
DownloadPort: seedPeer.DownloadPort,
State: seedPeer.State,
SeedPeerClusterId: uint64(seedPeer.SeedPeerClusterID),
})
}
}
// Marshal features of scheduler.
features, err := scheduler.Features.MarshalJSON()
if err != nil {
return nil, status.Error(codes.DataLoss, err.Error())
}
pbListSchedulersResponse.Schedulers = append(pbListSchedulersResponse.Schedulers, &managerv2.Scheduler{
Id: uint64(scheduler.ID),
Hostname: scheduler.Hostname,
Idc: &scheduler.IDC,
Location: &scheduler.Location,
Ip: scheduler.IP,
Port: scheduler.Port,
State: scheduler.State,
Features: features,
SchedulerClusterId: uint64(scheduler.SchedulerClusterID),
SeedPeers: seedPeers,
})
}
// If scheduler is not found, even no default scheduler is returned.
// It means that the scheduler has not been started,
// and the results are not cached, waiting for the scheduler to be ready.
if len(pbListSchedulersResponse.Schedulers) == 0 {
return &pbListSchedulersResponse, nil
}
// Cache data.
if err := s.cache.Once(&cachev9.Item{
Ctx: ctx,
Key: cacheKey,
Value: &pbListSchedulersResponse,
TTL: s.cache.TTL,
}); err != nil {
log.Error(err)
}
return &pbListSchedulersResponse, nil
}
// List applications configuration.
func (s *managerServerV2) ListApplications(ctx context.Context, req *managerv2.ListApplicationsRequest) (*managerv2.ListApplicationsResponse, error) {
log := logger.WithHostnameAndIP(req.Hostname, req.Ip)
// Cache hit.
var pbListApplicationsResponse managerv2.ListApplicationsResponse
cacheKey := pkgredis.MakeApplicationsKeyInManager()
if err := s.cache.Get(ctx, cacheKey, &pbListApplicationsResponse); err != nil {
log.Warnf("%s cache miss because of %s", cacheKey, err.Error())
} else {
log.Debugf("%s cache hit", cacheKey)
return &pbListApplicationsResponse, nil
}
// Cache miss and search applications.
var applications []models.Application
if err := s.db.WithContext(ctx).Find(&applications, "priority != ?", "").Error; err != nil {
if errors.Is(err, gorm.ErrRecordNotFound) {
return nil, status.Error(codes.NotFound, err.Error())
}
return nil, status.Error(codes.Internal, err.Error())
}
if len(applications) == 0 {
return nil, status.Error(codes.NotFound, "application not found")
}
for _, application := range applications {
b, err := application.Priority.MarshalJSON()
if err != nil {
log.Warn(err)
continue
}
var priority types.PriorityConfig
if err := json.Unmarshal(b, &priority); err != nil {
log.Warn(err)
continue
}
var pbURLPriorities []*managerv2.URLPriority
for _, url := range priority.URLs {
pbURLPriorities = append(pbURLPriorities, &managerv2.URLPriority{
Regex: url.Regex,
Value: commonv2.Priority(url.Value),
})
}
pbListApplicationsResponse.Applications = append(pbListApplicationsResponse.Applications, &managerv2.Application{
Id: uint64(application.ID),
Name: application.Name,
Url: application.URL,
Bio: application.BIO,
Priority: &managerv2.ApplicationPriority{
Value: commonv2.Priority(*priority.Value),
Urls: pbURLPriorities,
},
})
}
// Cache data.
if err := s.cache.Once(&cachev9.Item{
Ctx: ctx,
Key: cacheKey,
Value: &pbListApplicationsResponse,
TTL: s.cache.TTL,
}); err != nil {
log.Error(err)
}
return &pbListApplicationsResponse, nil
}
// KeepAlive with manager.
func (s *managerServerV2) KeepAlive(stream managerv2.Manager_KeepAliveServer) error {
req, err := stream.Recv()
if err != nil {
logger.Errorf("keepalive failed for the first time: %s", err.Error())
return status.Error(codes.Internal, err.Error())
}
hostname := req.Hostname
ip := req.Ip
sourceType := req.SourceType
clusterID := uint(req.ClusterId)
log := logger.WithKeepAlive(hostname, ip, sourceType.Enum().String(), req.ClusterId)
log.Info("keepalive for the first time")
// Initialize active scheduler.
if sourceType == managerv2.SourceType_SCHEDULER_SOURCE {
scheduler := models.Scheduler{}
if err := s.db.First(&scheduler, models.Scheduler{
Hostname: hostname,
IP: ip,
SchedulerClusterID: clusterID,
}).Updates(models.Scheduler{
State: models.SchedulerStateActive,
}).Error; err != nil {
return status.Error(codes.Internal, err.Error())
}
if err := s.cache.Delete(
context.TODO(),
pkgredis.MakeSchedulerKeyInManager(clusterID, hostname, ip),
); err != nil {
log.Warnf("refresh keepalive status failed: %s", err.Error())
}
}
// Initialize active seed peer.
if sourceType == managerv2.SourceType_SEED_PEER_SOURCE {
seedPeer := models.SeedPeer{}
if err := s.db.First(&seedPeer, models.SeedPeer{
Hostname: hostname,
IP: ip,
SeedPeerClusterID: clusterID,
}).Updates(models.SeedPeer{
State: models.SeedPeerStateActive,
}).Error; err != nil {
return status.Error(codes.Internal, err.Error())
}
if err := s.cache.Delete(
context.TODO(),
pkgredis.MakeSeedPeerKeyInManager(clusterID, hostname, ip),
); err != nil {
log.Warnf("refresh keepalive status failed: %s", err.Error())
}
}
for {
_, err := stream.Recv()
if err != nil {
// Inactive scheduler.
if sourceType == managerv2.SourceType_SCHEDULER_SOURCE {
scheduler := models.Scheduler{}
if err := s.db.First(&scheduler, models.Scheduler{
Hostname: hostname,
IP: ip,
SchedulerClusterID: clusterID,
}).Updates(models.Scheduler{
State: models.SchedulerStateInactive,
}).Error; err != nil {
return status.Error(codes.Internal, err.Error())
}
if err := s.cache.Delete(
context.TODO(),
pkgredis.MakeSchedulerKeyInManager(clusterID, hostname, ip),
); err != nil {
log.Warnf("refresh keepalive status failed: %s", err.Error())
}
}
// Inactive seed peer.
if sourceType == managerv2.SourceType_SEED_PEER_SOURCE {
seedPeer := models.SeedPeer{}
if err := s.db.First(&seedPeer, models.SeedPeer{
Hostname: hostname,
IP: ip,
SeedPeerClusterID: clusterID,
}).Updates(models.SeedPeer{
State: models.SeedPeerStateInactive,
}).Error; err != nil {
return status.Error(codes.Internal, err.Error())
}
if err := s.cache.Delete(
context.TODO(),
pkgredis.MakeSeedPeerKeyInManager(clusterID, hostname, ip),
); err != nil {
log.Warnf("refresh keepalive status failed: %s", err.Error())
}
}
if err == io.EOF {
log.Info("keepalive closed")
return nil
}
log.Errorf("keepalive failed: %s", err.Error())
return status.Error(codes.Unknown, err.Error())
}
}
}