-
Notifications
You must be signed in to change notification settings - Fork 12
/
manager_janitor.go
1574 lines (1385 loc) · 47.9 KB
/
manager_janitor.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
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// Copyright 2014-Present Couchbase, Inc.
//
// Use of this software is governed by the Business Source License included
// in the file licenses/BSL-Couchbase.txt. As of the Change Date specified
// in that file, in accordance with the Business Source License, use of this
// software will be governed by the Apache License, Version 2.0, included in
// the file licenses/APL2.txt.
package cbgt
import (
"bytes"
"fmt"
"math"
"os"
"strings"
"sync"
"sync/atomic"
"time"
log "github.com/couchbase/clog"
)
// FeedAllotmentOption is the manager option key used the specify how
// feeds should be alloted or assigned.
const FeedAllotmentOption = "feedAllotment"
// FeedAllotmentOnePerPIndex specifies that there should be only a
// single feed per pindex.
const FeedAllotmentOnePerPIndex = "oneFeedPerPIndex"
const JANITOR_CLOSE_PINDEX = "janitor_close_pindex"
const JANITOR_REMOVE_PINDEX = "janitor_remove_pindex"
const JANITOR_ROLLBACK_PINDEX = "janitor_rollback_pindex"
// JanitorNOOP sends a synchronous NOOP to the manager's janitor, if any.
func (mgr *Manager) JanitorNOOP(msg string) {
atomic.AddUint64(&mgr.stats.TotJanitorNOOP, 1)
if mgr.tagsMap == nil || (mgr.tagsMap["pindex"] && mgr.tagsMap["janitor"]) {
syncWorkReq(mgr.janitorCh, WORK_NOOP, msg, nil)
}
}
// JanitorKick synchronously kicks the manager's janitor, if any.
func (mgr *Manager) JanitorKick(msg string) {
atomic.AddUint64(&mgr.stats.TotJanitorKick, 1)
if mgr.tagsMap == nil || (mgr.tagsMap["pindex"] && mgr.tagsMap["janitor"]) {
syncWorkReq(mgr.janitorCh, WORK_KICK, msg, nil)
}
}
// JanitorKick synchronously kicks the manager's janitor, if any, to initiate a
// rollback.
func (mgr *Manager) JanitorRollbackKick(msg string, pindex *PIndex) {
atomic.AddUint64(&mgr.stats.TotJanitorKick, 1)
if mgr.tagsMap == nil || (mgr.tagsMap["pindex"] && mgr.tagsMap["janitor"]) {
syncWorkReq(mgr.janitorCh, JANITOR_ROLLBACK_PINDEX, msg, pindex)
}
}
// A way for applications to hook into the janitor's rollback phases.
// Must be set at init time, before the manager is started.
var RollbackHook func(phase RollbackPhase, pindex *PIndex) (err error)
type RollbackPhase int
const (
RollbackInit RollbackPhase = iota
RollbackCompleted
)
func (mgr *Manager) rollbackPIndex(pindex *PIndex) error {
defer func() {
if RollbackHook != nil {
err := RollbackHook(RollbackCompleted, pindex)
if err != nil {
log.Warnf("janitor: rollbackPIndex for pindex %s, "+
"RollbackHook, err: %v", pindex.Name, err)
}
}
}()
if pindex == nil {
return nil
}
if RollbackHook != nil {
err := RollbackHook(RollbackInit, pindex)
if err != nil {
return fmt.Errorf("janitor: rollbackPIndex for pindex %s, "+
"RollbackHook, err: %v", pindex.Name, err)
}
}
err := mgr.stopPIndex(pindex, false)
if err != nil {
return fmt.Errorf("janitor: rollbackPIndex for pindex %s, stopPIndex, "+
"err: %v", pindex.Name, err)
}
_, err = os.Stat(pindex.Path)
if os.IsNotExist(err) {
// Full rollback if the files are not there
return mgr.fullRollbackPIndex(pindex)
} else {
// Partial rollback if the files are present.
err = mgr.partiallyRollbackPIndex(pindex)
if err != nil {
log.Warnf("janitor: partiallyRollbackPIndex for pindex %s, cleaning "+
"and trying full rollback, err: %v", pindex.Name, err)
pindex.closed = false
err = mgr.stopPIndexFeeds(pindex)
if err != nil {
return err
}
if pindex.Dest != nil {
buf := bytes.NewBuffer(nil)
buf.Write([]byte(fmt.Sprintf(
`{"event":"stopPIndex","name":"%s","remove":%t,"time":"%s","stats":`,
pindex.Name, true, time.Now().Format(time.RFC3339Nano))))
err := pindex.Dest.Stats(buf)
if err == nil {
buf.Write(JsonCloseBrace)
mgr.AddEvent(buf.Bytes())
}
}
mgr.unregisterPIndex(pindex.Name, nil)
pindex.Close(true)
// Full rollback if the partial rollback failed.
return mgr.fullRollbackPIndex(pindex)
}
}
return nil
}
func (mgr *Manager) fullRollbackPIndex(pindex *PIndex) error {
log.Printf("janitor: fully rolling back pindex %s", pindex.Name)
pindexName := pindex.Name
var err error
pindex, err = createNewPIndex(mgr, pindex.Name, pindex.UUID,
pindex.IndexType, pindex.IndexName, pindex.IndexUUID, pindex.IndexParams,
pindex.SourceType, pindex.SourceName, pindex.SourceUUID, pindex.SourceParams,
pindex.SourcePartitions, pindex.Path, RollbackPIndexImpl)
if err != nil {
return fmt.Errorf("janitor: error rolling back pindex: %s, err: %v", pindexName, err)
}
err = mgr.registerPIndex(pindex)
if err != nil {
return fmt.Errorf("janitor: error registering pindex: %s, err: %v", pindex.Name, err)
}
return nil
}
func (mgr *Manager) partiallyRollbackPIndex(pindex *PIndex) error {
// if there is an error opening pindex, the returned pindex is nil
// hence, storing the path before opening pindex
pindexPath := pindex.Path
log.Printf("janitor: partial rollback, path: %s", pindexPath)
pindex, err := OpenPIndex(mgr, pindexPath)
if err != nil {
return err
}
err = mgr.registerPIndex(pindex)
if err != nil {
return fmt.Errorf("janitor: error registering pindex %s: %v", pindex.Name, err)
}
// Required to add feeds for partial rollback.
return mgr.JanitorOnce("Adding feeds after partial rollback of pindex: " + pindex.Name)
}
// JanitorLoop is the main loop for the janitor.
func (mgr *Manager) JanitorLoop() {
mgr.cfgObserver(componentJanitor, func(cfgEvent *CfgEvent) {
atomic.AddUint64(&mgr.stats.TotJanitorSubscriptionEvent, 1)
mgr.JanitorKick("cfg changed, key: " + cfgEvent.Key)
})
for {
select {
case <-mgr.stopCh:
atomic.AddUint64(&mgr.stats.TotJanitorStop, 1)
return
case m := <-mgr.janitorCh:
atomic.AddUint64(&mgr.stats.TotJanitorOpStart, 1)
log.Printf("janitor: awakes, op: %v, msg: %s", m.op, m.msg)
var err error
if m.op == WORK_KICK {
atomic.AddUint64(&mgr.stats.TotJanitorKickStart, 1)
err = mgr.JanitorOnce(m.msg)
if err != nil {
// Keep looping as perhaps it's a transient issue.
// TODO: Perhaps need a rescheduled janitor kick.
log.Warnf("janitor: JanitorOnce, err: %v", err)
atomic.AddUint64(&mgr.stats.TotJanitorKickErr, 1)
} else {
atomic.AddUint64(&mgr.stats.TotJanitorKickOk, 1)
}
} else if m.op == WORK_NOOP {
atomic.AddUint64(&mgr.stats.TotJanitorNOOPOk, 1)
} else if m.op == JANITOR_CLOSE_PINDEX {
err = mgr.stopPIndex(m.obj.(*PIndex), false)
} else if m.op == JANITOR_REMOVE_PINDEX {
err = mgr.stopPIndex(m.obj.(*PIndex), true)
} else if m.op == JANITOR_ROLLBACK_PINDEX {
err = mgr.rollbackPIndex(m.obj.(*PIndex))
if err != nil {
log.Warnf("janitor: rollbackPIndex for pindex %s, err: %v", m.obj.(*PIndex).Name, err)
}
} else {
err = fmt.Errorf("janitor: unknown op: %s, m: %#v", m.op, m)
atomic.AddUint64(&mgr.stats.TotJanitorUnknownErr, 1)
}
atomic.AddUint64(&mgr.stats.TotJanitorOpRes, 1)
if m.resCh != nil {
if err != nil {
atomic.AddUint64(&mgr.stats.TotJanitorOpErr, 1)
m.resCh <- err
}
close(m.resCh)
}
atomic.AddUint64(&mgr.stats.TotJanitorOpDone, 1)
}
}
}
func (mgr *Manager) pindexesStop(removePIndexes []*PIndex) []error {
var wg sync.WaitGroup
size := len(removePIndexes)
requestCh := make(chan *PIndex, size)
responseCh := make(chan error, size)
nWorkers := getWorkerCount(size)
// spawn the stop PIndex workers
for i := 0; i < nWorkers; i++ {
wg.Add(1)
go func() {
for pi := range requestCh {
// check if the loadDataDir is still loading this pindex, if so
// leave that to heal in subsequent Janitor loop?
if mgr.bootingPIndex(pi.Name) {
log.Printf("janitor: pindexesStop skipping stopPIndex,"+
" pindex: %s", pi.Name)
continue
}
err := mgr.stopPIndex(pi, true)
if err != nil {
responseCh <- fmt.Errorf("janitor: removing pindex: %s, err: %v",
pi.Name, err)
}
}
wg.Done()
}()
}
// feed the workers with PIndex to remove
for _, removePIndex := range removePIndexes {
requestCh <- removePIndex
}
close(requestCh)
wg.Wait()
close(responseCh)
var errs []error
for err := range responseCh {
errs = append(errs, err)
}
return errs
}
func (mgr *Manager) pindexesStart(addPlanPIndexes []*PlanPIndex) []error {
var wg sync.WaitGroup
size := len(addPlanPIndexes)
requestCh := make(chan *PlanPIndex, size)
responseCh := make(chan error, size)
nWorkers := getWorkerCount(size)
// spawn the start PIndex workers
for i := 0; i < nWorkers; i++ {
wg.Add(1)
go func() {
for pi := range requestCh {
// check if this pindex is already in booting
// by loadDataDir. If so just skip the processing here.
// else update the booting status so that the manager's
// loadDataDir won't reattempt the same pindex.
if !mgr.updateBootingStatus(pi.Name, true) {
// 'pi' already loaded
continue
}
err := mgr.startPIndex(pi)
if err != nil {
responseCh <- fmt.Errorf("janitor: adding pindex: %s, err: %v",
pi.Name, err)
}
// mark the pindex booting complete status
mgr.updateBootingStatus(pi.Name, false)
}
wg.Done()
}()
}
// feed the workers with planPIndexes
for _, addPlanPIndex := range addPlanPIndexes {
requestCh <- addPlanPIndex
}
close(requestCh)
wg.Wait()
close(responseCh)
var errs []error
for err := range responseCh {
errs = append(errs, err)
}
return errs
}
func cleanDir(path string) {
if path != "" {
_ = os.RemoveAll(path)
}
}
func (mgr *Manager) restartPIndex(req *pindexRestartReq) error {
if req == nil {
return nil
}
// check if the loadDataDir is still loading this pindex, if so
// leave that to heal in subsequent Janitor loops.
if mgr.bootingPIndex(req.pindex.Name) {
log.Printf("janitor: restartPIndex skipping restart for "+
" pindex: %s", req.pindex.Name)
return nil
}
// stop the pindex first
err := mgr.stopPIndex(req.pindex, false)
if err != nil {
cleanDir(req.pindex.Path)
return fmt.Errorf("janitor: restartPIndex stopping "+
" pindex: %s, err: %v", req.pindex.Name, err)
}
// rename the pindex folder and name as per the new plan
newPath := mgr.PIndexPath(req.planPIndexName)
if newPath != req.pindex.Path {
err = os.Rename(req.pindex.Path, newPath)
if err != nil {
cleanDir(req.pindex.Path)
cleanDir(newPath)
return fmt.Errorf("janitor: restartPIndex"+
" updating pindex: %s path: %s failed, err: %v",
req.pindex.Name, newPath, err)
}
}
pi := req.pindex.Clone()
pi.Name = req.planPIndexName
pi.Path = newPath
// persist PINDEX_META only if manager's dataDir is set
if len(mgr.dataDir) > 0 {
// update the new indexdef param changes
buf, err := MarshalJSON(pi)
if err != nil {
cleanDir(newPath)
return fmt.Errorf("janitor: restartPIndex"+
" Marshal pindex: %s, err: %v", pi.Name, err)
}
err = os.WriteFile(pi.Path+string(os.PathSeparator)+
PINDEX_META_FILENAME, buf, 0600)
if err != nil {
cleanDir(pi.Path)
return fmt.Errorf("janitor: restartPIndex could not save "+
"PINDEX_META_FILENAME,"+" path: %s, err: %v", pi.Path, err)
}
}
// open the pindex and register
pindex, err := OpenPIndex(mgr, pi.Path)
if err != nil {
cleanDir(req.pindex.Path)
return fmt.Errorf("janitor: restartPIndex could not open "+
" pindex path: %s, err: %v", pi.Path, err)
}
err = mgr.registerPIndex(pindex)
if err != nil {
cleanDir(pindex.Path)
return fmt.Errorf("janitor: restartPIndex failed to "+
"register pindex: %s, err: %v", pindex.Name, err)
}
atomic.AddUint64(&mgr.stats.TotJanitorRestartPIndex, 1)
return nil
}
type pindexHibernateReq struct {
pindex *PIndex
planPIndex *PlanPIndex
}
type pindexRestartReq struct {
pindex *PIndex
planPIndexName string
}
type pindexRestartErr struct {
err error
pindex *PIndex
}
func (re *pindexRestartErr) Error() string {
return re.err.Error()
}
func (mgr *Manager) pindexesRestart(
restartRequests []*pindexRestartReq) []pindexRestartErr {
var wg sync.WaitGroup
size := len(restartRequests)
requestCh := make(chan *pindexRestartReq, size)
responseCh := make(chan *pindexRestartErr, size)
nWorkers := getWorkerCount(size)
// spawn the restart PIndex workers
for i := 0; i < nWorkers; i++ {
wg.Add(1)
go func() {
for req := range requestCh {
err := mgr.restartPIndex(req)
if err != nil {
responseCh <- &pindexRestartErr{err: err,
pindex: req.pindex}
}
}
wg.Done()
}()
}
// feed the workers with restartRequests
for _, restartReq := range restartRequests {
requestCh <- restartReq
}
close(requestCh)
wg.Wait()
close(responseCh)
var errs []pindexRestartErr
for resp := range responseCh {
log.Warnf("janitor: restartPIndex err: %v", resp.err)
errs = append(errs, *resp)
}
return errs
}
var HibernatePartitionsHook func(mgr *Manager, activePIndexes,
replicaPIndexes []*PIndex) []error
var HibernationBucketStateTrackerHook func(*Manager, string, string)
var UnhibernationBucketStateTrackerHook func(*Manager, string, string)
// Specific restart and registration used in hibernation - followed by specific
// hibernation/unhibernation functions.
func (mgr *Manager) hibernateRestart(r *pindexRestartReq) (*PIndex, error) {
// stop the pindex first
err := mgr.stopPIndex(r.pindex, false)
if err != nil {
return nil, fmt.Errorf("janitor: hibernateRestart stopping "+
" pindex: %s, err: %v", r.pindex.Name, err)
}
// rename the pindex folder and name as per the new plan
newPath := mgr.PIndexPath(r.planPIndexName)
if newPath != r.pindex.Path {
err = os.Rename(r.pindex.Path, newPath)
if err != nil {
return nil, fmt.Errorf("janitor: hibernateRestart"+
" updating pindex: %s path: %s failed, err: %v",
r.pindex.Name, newPath, err)
}
}
pi := r.pindex.Clone()
pi.Name = r.planPIndexName
pi.Path = newPath
pi.HibernationPath = r.pindex.HibernationPath
// persist PINDEX_META only if manager's dataDir is set
if len(mgr.dataDir) > 0 {
buf, err := MarshalJSON(pi)
if err != nil {
return nil, fmt.Errorf("janitor: hibernateRestart"+
" Marshal pindex: %s, err: %v", pi.Name, err)
}
err = os.WriteFile(pi.Path+string(os.PathSeparator)+
PINDEX_META_FILENAME, buf, 0600)
if err != nil {
return nil, fmt.Errorf("janitor: hibernateRestart could not save "+
"PINDEX_META_FILENAME,"+" path: %s, err: %v", pi.Path, err)
}
}
err = mgr.registerPIndex(pi)
if err != nil {
return nil, fmt.Errorf("janitor: hibernateRestart failed to "+
"register pindex: %s, err: %v", pi.Name, err)
}
return pi, nil
}
func (mgr *Manager) hibernatePIndex(req []*pindexHibernateReq) []error {
// map of source name -> list of pindexes with the same source
pindexesToHibernate := make(map[string][][]*PIndex)
var errs []error
for _, r := range req {
tempReq := &pindexRestartReq{pindex: r.pindex,
planPIndexName: r.planPIndex.Name}
pi, err := mgr.hibernateRestart(tempReq)
if err != nil {
errs = append(errs, err)
continue
}
// Change 'closed' to false so that its files gets deleted on a
// successful hibernation.
pi.closed = false
if _, exists := pindexesToHibernate[pi.SourceName]; !exists {
pindexesToHibernate[pi.SourceName] = make([][]*PIndex, 2)
}
// Only hibernating if it's an active partition node.
if r.planPIndex.Nodes[mgr.uuid].Priority <= 0 {
pindexesToHibernate[pi.SourceName][0] = append(pindexesToHibernate[pi.SourceName][0],
pi)
} else {
pindexesToHibernate[pi.SourceName][1] = append(pindexesToHibernate[pi.SourceName][1],
pi)
}
}
if HibernatePartitionsHook != nil {
for source, pindexes := range pindexesToHibernate {
// Assuming bucket state is already being tracked for pause
mgr.RegisterHibernationBucketTracker(source)
hibErrs := HibernatePartitionsHook(mgr, pindexes[0], pindexes[1])
if len(hibErrs) > 0 {
errs = append(errs, hibErrs...)
}
}
}
return errs
}
// JanitorOnce is the main body of a JanitorLoop.
func (mgr *Manager) JanitorOnce(reason string) error {
if mgr.cfg == nil { // Can occur during testing.
return fmt.Errorf("janitor: skipped due to nil cfg")
}
feedAllotment := mgr.GetOption(FeedAllotmentOption)
// NOTE: The janitor doesn't reconfirm that we're a wanted node
// because instead some planner will see that & update the plan;
// then relevant janitors will react by closing pindexes & feeds.
planPIndexes, _, err := CfgGetPlanPIndexes(mgr.cfg)
if err != nil {
return fmt.Errorf("janitor: skipped on CfgGetPlanPIndexes err: %v", err)
}
if planPIndexes == nil {
// Might happen if janitor wins an initialization race.
return fmt.Errorf("janitor: skipped on nil planPIndexes")
}
_, currPIndexes := mgr.CurrentMaps()
mapWantedPlanPIndex := mgr.reusablePIndexesPlanMap(currPIndexes, planPIndexes)
addPlanPIndexes, removePIndexes :=
CalcPIndexesDelta(mgr.uuid, currPIndexes, planPIndexes, mapWantedPlanPIndex)
// check for any pindexes for restart and get classified lists of
// pindexes to add, remove and restart
planPIndexesToAdd, pindexesToRemove, pindexesToRestart, pindexesToHibernate :=
classifyAddRemoveRestartPIndexes(mgr, addPlanPIndexes, removePIndexes)
log.Printf("janitor: pindexes to remove: %d", len(pindexesToRemove))
for _, pi := range pindexesToRemove {
log.Printf(" pindex: %v; UUID: %v", pi.Name, pi.IndexUUID)
}
log.Printf("janitor: pindexes to add: %d", len(planPIndexesToAdd))
for _, ppi := range planPIndexesToAdd {
log.Printf(" pindex: %v; UUID: %v", ppi.Name, ppi.IndexUUID)
}
log.Printf("janitor: pindexes to restart: %d", len(pindexesToRestart))
for _, pi := range pindexesToRestart {
if pi.pindex != nil {
log.Printf(" pindex: %v; UUID: %v", pi.pindex.Name, pi.pindex.IndexUUID)
}
}
// restart any of the pindexes so that they can
// adopt the updated indexDef parameters, ex: storeOptions
restartErrs := mgr.pindexesRestart(pindexesToRestart)
// upon any restart errors, bring back the addPlanPIndex for
// starting the pindex afresh
if len(restartErrs) > 0 {
planPIndexesToAdd = append(planPIndexesToAdd, elicitAddPlanPIndexes(addPlanPIndexes, restartErrs)...)
}
var errs []error
log.Printf("janitor: pindexes to hibernate: %d", len(pindexesToHibernate))
for _, pi := range pindexesToHibernate {
if pi != nil {
log.Printf(" pindex %v; UUID: %v", pi.pindex.Name, pi.pindex.UUID)
}
}
errs = append(errs, mgr.hibernatePIndex(pindexesToHibernate)...)
// First, teardown pindexes that need to be removed.
// batching the stop, aiming to expedite the
// whole JanitorOnce call
errs = append(errs, mgr.pindexesStop(pindexesToRemove)...)
// Then, (re-)create pindexes that we're missing.
// batching the start, aiming to expedite the
// whole JanitorOnce call
errs = append(errs, mgr.pindexesStart(planPIndexesToAdd)...)
var currFeeds map[string]Feed
currFeeds, currPIndexes = mgr.CurrentMaps()
hibernationTask, hibernationBucket, hibernationSourceType :=
mgr.findHibernationBucketsToMonitor()
if hibernationTask == UNHIBERNATE_TASK {
log.Printf("janitor: bucket to track for unhibernation: %s", hibernationBucket)
mgr.trackResumeBucketState(hibernationBucket, hibernationSourceType)
}
if hibernationTask == HIBERNATE_TASK {
log.Printf("janitor: bucket to track for hibernation: %s", hibernationBucket)
mgr.trackPauseBucketState(hibernationBucket, hibernationSourceType)
}
addFeeds, removeFeeds :=
CalcFeedsDelta(mgr.uuid, planPIndexes, currFeeds, currPIndexes,
feedAllotment)
// filter out non-ready feeds.
addFeeds = filterFeedable(mgr, addFeeds)
log.Printf("janitor: feeds to remove: %d", len(removeFeeds))
for _, removeFeed := range removeFeeds {
log.Printf(" %s", removeFeed.Name())
}
log.Printf("janitor: feeds to add: %d", len(addFeeds))
for _, targetPIndexes := range addFeeds {
if len(targetPIndexes) > 0 {
log.Printf(" %s", FeedNameForPIndex(targetPIndexes[0], feedAllotment))
}
}
// First, teardown feeds that need to be removed.
for _, removeFeed := range removeFeeds {
err = mgr.stopFeed(removeFeed)
if err != nil {
errs = append(errs,
fmt.Errorf("janitor: stopping feed, name: %s, err: %v",
removeFeed.Name(), err))
}
}
// Then, (re-)create feeds that we're missing.
for _, addFeedTargetPIndexes := range addFeeds {
err = mgr.startFeed(addFeedTargetPIndexes)
if err != nil {
errs = append(errs,
fmt.Errorf("janitor: adding feed, err: %v", err))
}
}
if len(errs) > 0 {
var s []string
for i, err := range errs {
s = append(s, fmt.Sprintf("#%d: %v", i, err))
}
return fmt.Errorf("janitor: JanitorOnce errors: %d, %#v",
len(errs), s)
}
return nil
}
func filterFeedable(mgr *Manager, addFeeds [][]*PIndex) (af [][]*PIndex) {
for _, pindexes := range addFeeds {
addList := make([]*PIndex, 0, len(pindexes))
for _, pindex := range pindexes {
ready, err := pindex.IsFeedable()
if ready && err == nil {
// Need to filter pindexes which are being pause/
// were being paused before start to avoid adding feeds to them.
hibernationInProgress := mgr.IsBucketBeingHibernated(pindex.SourceName)
// if the pindex source name has a bucket being tracked, don't add it
if !hibernationInProgress {
addList = append(addList, pindex)
}
continue
}
log.Printf("janitor: skip feed: %s, err: %v", pindex.Name, err)
}
if len(addList) > 0 {
af = append(af, addList)
}
}
return af
}
func classifyAddRemoveRestartPIndexes(mgr *Manager, addPlanPIndexes []*PlanPIndex,
removePIndexes []*PIndex) (planPIndexesToAdd []*PlanPIndex,
pindexesToRemove []*PIndex, pindexesToRestart []*pindexRestartReq,
pindexesToHibernate []*pindexHibernateReq) {
// if there are no pindexes to be removed as per planner,
// then there won't be anything to restart as well.
if len(removePIndexes) == 0 {
return addPlanPIndexes, nil, nil, nil
}
pindexesToRestart = make([]*pindexRestartReq, 0)
pindexesToRemove = make([]*PIndex, 0)
pindexesToHibernate = make([]*pindexHibernateReq, 0)
planPIndexesToAdd = make([]*PlanPIndex, 0)
// grouping addPlanPIndexes and removePIndexes as per index for
// checking restartable indexDef changes per index
indexPlanPIndexMap := make(map[string][]*PlanPIndex)
indexPIndexMap := make(map[string][]*PIndex)
for _, rp := range removePIndexes {
indexPIndexMap[rp.IndexName] = append(indexPIndexMap[rp.IndexName], rp)
}
for _, addPlan := range addPlanPIndexes {
indexPlanPIndexMap[addPlan.IndexName] =
append(indexPlanPIndexMap[addPlan.IndexName], addPlan)
}
// avoid pindex rebuild on replica updates on index defn
// unless overridden
if v := mgr.GetOption("rebuildOnReplicaUpdate"); v != "true" {
return advPIndexClassifier(mgr, indexPIndexMap, indexPlanPIndexMap)
}
// take every pindex to remove and check the config change
// and sort out the pindexes to add, remove or restart
for indexName, pindexes := range indexPIndexMap {
if len(pindexes) > 0 && pindexes[0] != nil {
pindex := pindexes[0]
if planPIndexes, ok := indexPlanPIndexMap[indexName]; ok {
indexDefnCurr := getIndexDefFromPlanPIndexes(planPIndexes)
configAnalyzeReq := &ConfigAnalyzeRequest{
IndexDefnCur: indexDefnCurr,
IndexDefnPrev: getIndexDefFromPIndex(pindex),
SourcePartitionsCur: getSourcePartitionsMapFromPlanPIndexes(
planPIndexes),
SourcePartitionsPrev: getSourcePartitionsMapFromPIndexes(
pindexes)}
pindexImplType, exists := PIndexImplTypes[pindex.IndexType]
if !exists || pindexImplType == nil {
pindexesToRemove = append(pindexesToRemove, pindexes...)
planPIndexesToAdd = append(planPIndexesToAdd, planPIndexes...)
continue
}
pathChange := metadataPathChange(configAnalyzeReq)
if pathChange == HIBERNATE_TASK {
pidxList := getPIndexesToHibernate(pindexes, planPIndexes)
for _, pidx := range pidxList {
pindexesToHibernate = append(pindexesToHibernate, pidx)
}
continue
}
if pindexImplType.AnalyzeIndexDefUpdates != nil &&
pindexImplType.AnalyzeIndexDefUpdates(configAnalyzeReq) ==
PINDEXES_RESTART {
pindexesToRestart = append(pindexesToRestart,
getPIndexesToRestart(pindexes, planPIndexes)...)
continue
} else {
pindexesToRemove = append(pindexesToRemove, pindexes...)
planPIndexesToAdd = append(planPIndexesToAdd, planPIndexes...)
}
} else {
pindexesToRemove = append(pindexesToRemove, pindexes...)
}
}
}
return planPIndexesToAdd, pindexesToRemove, pindexesToRestart, pindexesToHibernate
}
const (
HIBERNATE_TASK = "pause"
UNHIBERNATE_TASK = "resume"
)
func isHibernateChange(curr, prev string) bool {
return strings.HasPrefix(curr, HIBERNATE_TASK) && curr != prev
// Add condition to check if pindex files are present locally.
}
func metadataPathChange(configAnalyzeReq *ConfigAnalyzeRequest) string {
if isHibernateChange(configAnalyzeReq.IndexDefnCur.HibernationPath,
configAnalyzeReq.IndexDefnPrev.HibernationPath) {
return HIBERNATE_TASK
}
// This condition occurs during resume, when the download of the pindex files has
// complete, the hibernation path is changed to a blank path, followed by waiting for
// the right bucket state to add feeds(which is part of the current janitor kick).
if strings.HasPrefix(configAnalyzeReq.IndexDefnPrev.HibernationPath, UNHIBERNATE_TASK) &&
configAnalyzeReq.IndexDefnCur.HibernationPath == "" {
return UNHIBERNATE_TASK
}
return ""
}
func advPIndexClassifier(mgr *Manager, indexPIndexMap map[string][]*PIndex,
indexPlanPIndexMap map[string][]*PlanPIndex) (planPIndexesToAdd []*PlanPIndex,
pindexesToRemove []*PIndex, pindexesToRestart []*pindexRestartReq,
pindexesToHibernate []*pindexHibernateReq) {
pindexesToRestart = make([]*pindexRestartReq, 0)
pindexesToRemove = make([]*PIndex, 0)
planPIndexesToAdd = make([]*PlanPIndex, 0)
pindexesToHibernate = make([]*pindexHibernateReq, 0)
// take every pindex to remove and check the config change
// and sort out the pindexes to add, remove or restart
for indexName, pindexes := range indexPIndexMap {
restartable := make(map[string]struct{}, len(indexPIndexMap))
if len(pindexes) > 0 && pindexes[0] != nil {
// look for new addPlans the index level
if planPIndexes, ok := indexPlanPIndexMap[indexName]; ok {
indexDefnCur := getIndexDefFromPlanPIndexes(planPIndexes)
indexDefnPrev := getIndexDefFromPIndex(pindexes[0])
for _, pindex := range pindexes {
// get the unique part of the pindex name
pName := pindex.Name[strings.LastIndex(pindex.Name, "_")+1:]
// look for a new plan for the older pindex
var targetPlan *PlanPIndex
for _, ppi := range planPIndexes {
if pName == ppi.Name[strings.LastIndex(ppi.Name, "_")+1:] {
targetPlan = ppi
break
}
}
if targetPlan == nil {
pindexesToRemove = append(pindexesToRemove, pindex)
continue
}
configAnalyzeReq := &ConfigAnalyzeRequest{
IndexDefnCur: indexDefnCur,
IndexDefnPrev: indexDefnPrev,
SourcePartitionsCur: map[string]bool{
targetPlan.SourcePartitions: true},
SourcePartitionsPrev: getSourcePartitionsMapFromPIndexes(
[]*PIndex{pindex})}
pindexImplType, exists := PIndexImplTypes[pindex.IndexType]
if !exists || pindexImplType == nil {
pindexesToRemove = append(pindexesToRemove, pindex)
continue
}
pathChange := metadataPathChange(configAnalyzeReq)
if pathChange == HIBERNATE_TASK {
pindexesToHibernate = append(pindexesToHibernate,
newPIndexHibernateReq(targetPlan, pindex))
restartable[targetPlan.Name] = struct{}{}
continue
}
// restartable pindex found from plan
if pindexImplType.AnalyzeIndexDefUpdates != nil &&
pindexImplType.AnalyzeIndexDefUpdates(configAnalyzeReq) ==
PINDEXES_RESTART {
pindexesToRestart = append(pindexesToRestart,
newPIndexRestartReq(targetPlan, pindex))
restartable[targetPlan.Name] = struct{}{}
continue
}
// upon no restartability, consider the pindex for removal
pindexesToRemove = append(pindexesToRemove, pindex)
}
// consider the remaining addPlans
for _, ppi := range planPIndexes {
if _, done := restartable[ppi.Name]; !done {
planPIndexesToAdd = append(planPIndexesToAdd, ppi)
}
}
// cleanup as all addPlans already processed for the index
delete(indexPlanPIndexMap, indexName)
} else {
// as there are no new addPlans for the index,
// consider complete pindexes/index removal
pindexesToRemove = append(pindexesToRemove, pindexes...)
}
}
}
// include the remaining addPlans for any of the newer indexes
for _, addPlans := range indexPlanPIndexMap {
planPIndexesToAdd = append(planPIndexesToAdd, addPlans...)
}
return planPIndexesToAdd, pindexesToRemove, pindexesToRestart, pindexesToHibernate
}
func newPIndexRestartReq(addPlanPI *PlanPIndex,
pindex *PIndex) *pindexRestartReq {
pindex.IndexUUID = addPlanPI.IndexUUID
pindex.IndexParams = addPlanPI.IndexParams
pindex.SourceParams = addPlanPI.SourceParams
return &pindexRestartReq{
pindex: pindex,
planPIndexName: addPlanPI.Name,
}
}
func getPIndexesToRestart(pindexesToRemove []*PIndex,
addPlanPIndexes []*PlanPIndex) []*pindexRestartReq {
pindexesToRestart := make([]*pindexRestartReq, len(pindexesToRemove))
i := 0
for _, pindex := range pindexesToRemove {
for _, addPlanPI := range addPlanPIndexes {
if addPlanPI.SourcePartitions == pindex.SourcePartitions {
pindex.IndexUUID = addPlanPI.IndexUUID
pindex.IndexParams = addPlanPI.IndexParams
pindex.SourceParams = addPlanPI.SourceParams
pindexesToRestart[i] = &pindexRestartReq{
pindex: pindex,
planPIndexName: addPlanPI.Name,
}
i++
}
}
}
return pindexesToRestart
}
func newPIndexHibernateReq(addPlanPI *PlanPIndex,
pindex *PIndex) *pindexHibernateReq {
pindex.IndexUUID = addPlanPI.IndexUUID
pindex.IndexParams = addPlanPI.IndexParams
pindex.SourceParams = addPlanPI.SourceParams
pindex.HibernationPath = addPlanPI.HibernationPath
return &pindexHibernateReq{
pindex: pindex,
planPIndex: addPlanPI,
}
}
func getPIndexesToHibernate(currPindexes []*PIndex,
addPlanPIndexes []*PlanPIndex) []*pindexHibernateReq {
pindexesToHibernate := make([]*pindexHibernateReq, len(currPindexes))
i := 0
for _, pindex := range currPindexes {
for _, addPlanPI := range addPlanPIndexes {
if addPlanPI.SourcePartitions == pindex.SourcePartitions {
pindex.IndexUUID = addPlanPI.IndexUUID
pindex.IndexParams = addPlanPI.IndexParams
pindex.SourceParams = addPlanPI.SourceParams
pindex.HibernationPath = addPlanPI.HibernationPath
pindexesToHibernate[i] = &pindexHibernateReq{
pindex: pindex,
planPIndex: addPlanPI,
}
i++
}
}
}
return pindexesToHibernate
}
func getIndexDefFromPIndex(pindex *PIndex) *IndexDef {
if pindex != nil {
return &IndexDef{Name: pindex.IndexName,
UUID: pindex.IndexUUID,
SourceName: pindex.SourceName,
SourceParams: pindex.SourceParams,
SourceType: pindex.SourceType,
SourceUUID: pindex.SourceUUID,
Type: pindex.IndexType,
Params: pindex.IndexParams,