-
Notifications
You must be signed in to change notification settings - Fork 172
/
tgtcp.go
1251 lines (1163 loc) · 33.4 KB
/
tgtcp.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
// Package ais provides core functionality for the AIStore object storage.
/*
* Copyright (c) 2018-2024, NVIDIA CORPORATION. All rights reserved.
*/
package ais
import (
"errors"
"fmt"
"net/http"
"net/url"
"os"
"path/filepath"
"strconv"
"sync"
"time"
"github.com/NVIDIA/aistore/ais/backend"
"github.com/NVIDIA/aistore/api/apc"
"github.com/NVIDIA/aistore/api/env"
"github.com/NVIDIA/aistore/cmn"
"github.com/NVIDIA/aistore/cmn/cos"
"github.com/NVIDIA/aistore/cmn/debug"
"github.com/NVIDIA/aistore/cmn/fname"
"github.com/NVIDIA/aistore/cmn/nlog"
"github.com/NVIDIA/aistore/core"
"github.com/NVIDIA/aistore/core/meta"
"github.com/NVIDIA/aistore/ec"
"github.com/NVIDIA/aistore/ext/etl"
"github.com/NVIDIA/aistore/fs"
"github.com/NVIDIA/aistore/ios"
"github.com/NVIDIA/aistore/nl"
"github.com/NVIDIA/aistore/reb"
"github.com/NVIDIA/aistore/res"
"github.com/NVIDIA/aistore/stats"
"github.com/NVIDIA/aistore/xact"
"github.com/NVIDIA/aistore/xact/xreg"
jsoniter "github.com/json-iterator/go"
)
const (
bmdFixup = "fixup"
bmdRecv = "receive"
bmdReg = "register"
)
type delb struct {
obck *meta.Bck
present bool
}
func (t *target) joinCluster(action string, primaryURLs ...string) (status int, err error) {
res := t.join(nil, t, primaryURLs...)
defer freeCR(res)
if res.err != nil {
status, err = res.status, res.err
return
}
// not being sent at cluster startup and keepalive
if len(res.bytes) == 0 {
return
}
err = t.recvCluMetaBytes(action, res.bytes, "")
return
}
// TODO: unify w/ p.recvCluMeta
// do not receive RMD: `receiveRMD` runs extra jobs and checks specific for metasync.
func (t *target) recvCluMetaBytes(action string, body []byte, caller string) error {
var (
cm cluMeta
errs []error
)
if err := jsoniter.Unmarshal(body, &cm); err != nil {
return fmt.Errorf(cmn.FmtErrUnmarshal, t, "clumeta", cos.BHead(body), err)
}
debug.Assert(cm.PrimeTime != 0, t.String()) // expecting
xreg.PrimeTime.Store(cm.PrimeTime)
xreg.MyTime.Store(time.Now().UnixNano())
msg := t.newAmsgStr(action, cm.BMD)
// Config
debug.Assert(cm.Config != nil)
if err := t.receiveConfig(cm.Config, msg, nil, caller); err != nil {
if !isErrDowngrade(err) {
errs = append(errs, err)
nlog.Errorln(err)
}
} else {
nlog.Infof("%s: recv-clumeta %s %s", t, action, cm.Config)
}
// There's a window of time between:
// a) target joining existing cluster and b) cluster starting to rebalance itself
// The latter is driven by regMetasync (see regMetasync.go) distributing updated cluster map.
// To handle incoming GETs within this window (which would typically take a few seconds or less)
// we need to have the current cluster-wide regMetadata and the temporary gfn state:
reb.OnTimedGFN()
// BMD
if err := t.receiveBMD(cm.BMD, msg, nil /*ms payload */, bmdReg, caller, true /*silent*/); err != nil {
if !isErrDowngrade(err) {
errs = append(errs, err)
nlog.Errorln(err)
}
} else {
nlog.Infof("%s: recv-clumeta %s %s", t, action, cm.BMD)
}
// Smap
if err := t.receiveSmap(cm.Smap, msg, nil /*ms payload*/, caller, t.htrun.smapUpdatedCB); err != nil {
if !isErrDowngrade(err) {
errs = append(errs, err)
nlog.Errorln(cmn.NewErrFailedTo(t, "sync", cm.Smap, err))
}
} else if cm.Smap != nil {
nlog.Infof("%s: recv-clumeta %s %s", t, action, cm.Smap)
}
switch {
case errs == nil:
return nil
case len(errs) == 1:
return errs[0]
default:
return cmn.NewErrFailedTo(t, action, "clumeta", errors.Join(errs...))
}
}
// [METHOD] /v1/daemon
func (t *target) daemonHandler(w http.ResponseWriter, r *http.Request) {
switch r.Method {
case http.MethodGet:
t.httpdaeget(w, r)
case http.MethodPut:
t.httpdaeput(w, r)
case http.MethodPost:
t.httpdaepost(w, r)
case http.MethodDelete:
t.httpdaedelete(w, r)
default:
cmn.WriteErr405(w, r, http.MethodDelete, http.MethodGet, http.MethodPost, http.MethodPut)
}
}
func (t *target) httpdaeput(w http.ResponseWriter, r *http.Request) {
apiItems, err := t.parseURL(w, r, apc.URLPathDae.L, 0, true)
if err != nil {
return
}
if len(apiItems) == 0 {
t.daeputJSON(w, r)
} else {
t.daeputQuery(w, r, apiItems)
}
}
func (t *target) daeputJSON(w http.ResponseWriter, r *http.Request) {
msg, err := t.readActionMsg(w, r)
if err != nil {
return
}
switch msg.Action {
case apc.ActSetConfig: // set-config #2 - via action message
t.setDaemonConfigMsg(w, r, msg, r.URL.Query())
case apc.ActResetConfig:
if err := t.owner.config.resetDaemonConfig(); err != nil {
t.writeErr(w, r, err)
}
case apc.ActRotateLogs:
nlog.Flush(nlog.ActRotate)
case apc.ActResetStats:
errorsOnly := msg.Value.(bool)
t.statsT.ResetStats(errorsOnly)
case apc.ActStartMaintenance:
if !t.ensureIntraControl(w, r, true /* from primary */) {
return
}
t.termKaliveX(msg.Action, true)
case apc.ActShutdownCluster, apc.ActShutdownNode:
if !t.ensureIntraControl(w, r, true /* from primary */) {
return
}
t.termKaliveX(msg.Action, false)
t.shutdown(msg.Action)
case apc.ActRmNodeUnsafe:
if !t.ensureIntraControl(w, r, true /* from primary */) {
return
}
t.termKaliveX(msg.Action, true)
case apc.ActDecommissionCluster, apc.ActDecommissionNode:
if !t.ensureIntraControl(w, r, true /* from primary */) {
return
}
var opts apc.ActValRmNode
if err := cos.MorphMarshal(msg.Value, &opts); err != nil {
t.writeErr(w, r, err)
return
}
t.termKaliveX(msg.Action, opts.NoShutdown)
t.decommission(msg.Action, &opts)
case apc.ActCleanupMarkers:
if !t.ensureIntraControl(w, r, true /* from primary */) {
return
}
var ctx cleanmark
if err := cos.MorphMarshal(msg.Value, &ctx); err != nil {
t.writeErr(w, r, err)
return
}
t.cleanupMark(&ctx)
default:
t.writeErrAct(w, r, msg.Action)
}
}
func (t *target) daeputQuery(w http.ResponseWriter, r *http.Request, apiItems []string) {
switch apiItems[0] {
case apc.Proxy:
// PUT /v1/daemon/proxy/newprimaryproxyid
t.daeSetPrimary(w, r, apiItems)
case apc.SyncSmap:
newsmap := &smapX{}
if cmn.ReadJSON(w, r, newsmap) != nil {
return
}
if err := t.owner.smap.synchronize(t.si, newsmap, nil /*ms payload*/, t.htrun.smapUpdatedCB); err != nil {
t.writeErr(w, r, cmn.NewErrFailedTo(t, "synchronize", newsmap, err))
}
nlog.Infof("%s: %s %s done", t, apc.SyncSmap, newsmap)
case apc.Mountpaths:
t.handleMountpathReq(w, r)
case apc.ActSetConfig: // set-config #1 - via query parameters and "?n1=v1&n2=v2..."
t.setDaemonConfigQuery(w, r)
}
}
func (t *target) daeSetPrimary(w http.ResponseWriter, r *http.Request, apiItems []string) {
var (
err error
prepare bool
)
if len(apiItems) != 2 {
t.writeErrf(w, r, "Incorrect number of API items: %d, should be: %d", len(apiItems), 2)
return
}
proxyID := apiItems[1]
query := r.URL.Query()
preparestr := query.Get(apc.QparamPrepare)
if prepare, err = cos.ParseBool(preparestr); err != nil {
t.writeErrf(w, r, "Failed to parse %s URL Parameter: %v", apc.QparamPrepare, err)
return
}
if prepare {
if cmn.Rom.FastV(4, cos.SmoduleAIS) {
nlog.Infoln("Preparation step: do nothing")
}
return
}
ctx := &smapModifier{pre: t._setPrim, sid: proxyID}
err = t.owner.smap.modify(ctx)
if err != nil {
t.writeErr(w, r, err)
}
}
func (t *target) _setPrim(ctx *smapModifier, clone *smapX) (err error) {
if clone.Primary.ID() == ctx.sid {
return
}
psi := clone.GetProxy(ctx.sid)
if psi == nil {
return &errNodeNotFound{"cannot set new primary", ctx.sid, t.si, clone}
}
clone.Primary = psi
return
}
func (t *target) httpdaeget(w http.ResponseWriter, r *http.Request) {
var (
query = r.URL.Query()
getWhat = query.Get(apc.QparamWhat)
httpdaeWhat = "httpdaeget-" + getWhat
)
switch getWhat {
case apc.WhatNodeConfig, apc.WhatSmap, apc.WhatBMD, apc.WhatSmapVote,
apc.WhatSnode, apc.WhatLog, apc.WhatNodeStats, apc.WhatMetricNames:
t.htrun.httpdaeget(w, r, query, t /*htext*/)
case apc.WhatSysInfo:
tsysinfo := apc.TSysInfo{MemCPUInfo: apc.GetMemCPU(), CapacityInfo: fs.CapStatusGetWhat()}
t.writeJSON(w, r, tsysinfo, httpdaeWhat)
case apc.WhatMountpaths:
t.writeJSON(w, r, fs.MountpathsToLists(), httpdaeWhat)
case apc.WhatNodeStatsAndStatus:
var rebSnap *core.Snap
if entry := xreg.GetLatest(xreg.Flt{Kind: apc.ActRebalance}); entry != nil {
if xctn := entry.Get(); xctn != nil {
rebSnap = xctn.Snap()
}
}
smap := t.owner.smap.get()
msg := &stats.NodeStatus{
Node: stats.Node{
Snode: t.htrun.si,
},
SmapVersion: smap.Version,
MemCPUInfo: apc.GetMemCPU(),
RebSnap: rebSnap,
DeploymentType: deploymentType(),
Version: daemon.version,
BuildTime: daemon.buildTime,
K8sPodName: os.Getenv(env.AIS.K8sPod),
Status: t._status(smap),
}
// stats and capacity
daeStats := t.statsT.GetStats()
msg.Tracker = daeStats.Tracker
msg.TargetCDF = daeStats.TargetCDF
t.writeJSON(w, r, msg, httpdaeWhat)
case apc.WhatDiskStats:
diskStats := make(ios.AllDiskStats)
fs.FillDiskStats(diskStats)
t.writeJSON(w, r, diskStats, httpdaeWhat)
case apc.WhatRemoteAIS:
var (
aisBackend = t.aisBackend()
refresh = cos.IsParseBool(query.Get(apc.QparamClusterInfo))
)
if !refresh {
t.writeJSON(w, r, aisBackend.GetInfoInternal(), httpdaeWhat)
return
}
anyConf := cmn.GCO.Get().Backend.Get(apc.AIS)
if anyConf == nil {
t.writeJSON(w, r, meta.RemAisVec{}, httpdaeWhat)
return
}
aisConf, ok := anyConf.(cmn.BackendConfAIS)
debug.Assert(ok)
t.writeJSON(w, r, aisBackend.GetInfo(aisConf), httpdaeWhat)
default:
t.htrun.httpdaeget(w, r, query, t /*htext*/)
}
}
// admin-join target | enable/disable mountpath
func (t *target) httpdaepost(w http.ResponseWriter, r *http.Request) {
apiItems, err := t.parseURL(w, r, apc.URLPathDae.L, 0, true)
if err != nil {
return
}
if len(apiItems) == 0 {
t.writeErrURL(w, r)
return
}
apiOp := apiItems[0]
if apiOp == apc.Mountpaths {
t.handleMountpathReq(w, r)
return
}
if apiOp != apc.AdminJoin {
t.writeErrURL(w, r)
return
}
// user request to join cluster (compare with `apc.SelfJoin`)
if !t.regstate.disabled.Load() {
if t.keepalive.paused() {
t.keepalive.ctrl(kaResumeMsg)
} else {
nlog.Warningf("%s already joined (\"enabled\")- nothing to do", t)
}
return
}
if daemon.cli.target.standby {
nlog.Infof("%s: transitioning standby => join", t)
}
t.keepalive.ctrl(kaResumeMsg)
body, err := cmn.ReadBytes(r)
if err != nil {
t.writeErr(w, r, err)
return
}
caller := r.Header.Get(apc.HdrCallerName)
if err := t.recvCluMetaBytes(apc.ActAdminJoinTarget, body, caller); err != nil {
t.writeErr(w, r, err)
return
}
if daemon.cli.target.standby {
if err := t.endStartupStandby(); err != nil {
nlog.Warningf("%s: err %v ending standby...", t, err)
}
}
}
func (t *target) httpdaedelete(w http.ResponseWriter, r *http.Request) {
apiItems, err := t.parseURL(w, r, apc.URLPathDae.L, 1, false)
if err != nil {
return
}
switch apiItems[0] {
case apc.Mountpaths:
t.handleMountpathReq(w, r)
default:
t.writeErrURL(w, r)
}
}
// called by p.cleanupMark
func (t *target) cleanupMark(ctx *cleanmark) {
smap := t.owner.smap.get()
if smap.version() > ctx.NewVer {
nlog.Warningf("%s: %s is newer - ignoring (and dropping) %v", t, smap, ctx)
return
}
if ctx.Interrupted {
if err := fs.RemoveMarker(fname.RebalanceMarker); err == nil {
nlog.Infof("%s: cleanmark 'rebalance', %s", t, smap)
} else {
nlog.Errorf("%s: failed to cleanmark 'rebalance': %v, %s", t, err, smap)
}
}
if ctx.Restarted {
if err := fs.RemoveMarker(fname.NodeRestartedPrev); err == nil {
nlog.Infof("%s: cleanmark 'restarted', %s", t, smap)
} else {
nlog.Errorf("%s: failed to cleanmark 'restarted': %v, %s", t, err, smap)
}
}
}
func (t *target) handleMountpathReq(w http.ResponseWriter, r *http.Request) {
msg, err := t.readActionMsg(w, r)
if err != nil {
return
}
mpath, ok := msg.Value.(string)
if !ok {
t.writeErrMsg(w, r, "invalid mountpath value in request")
return
}
if mpath == "" {
t.writeErrMsg(w, r, "mountpath is not defined")
return
}
switch msg.Action {
case apc.ActMountpathEnable:
t.enableMpath(w, r, mpath)
case apc.ActMountpathAttach:
t.attachMpath(w, r, mpath)
case apc.ActMountpathDisable:
t.disableMpath(w, r, mpath)
case apc.ActMountpathDetach:
t.detachMpath(w, r, mpath)
default:
t.writeErrAct(w, r, msg.Action)
}
fs.ComputeDiskSize()
}
func (t *target) enableMpath(w http.ResponseWriter, r *http.Request, mpath string) {
enabledMi, err := t.fsprg.enableMpath(mpath)
if err != nil {
if cmn.IsErrMountpathNotFound(err) {
t.writeErr(w, r, err, http.StatusNotFound)
} else {
// cmn.ErrInvalidMountpath
t.writeErr(w, r, err)
}
return
}
if enabledMi == nil {
w.WriteHeader(http.StatusNoContent)
return
}
// create missing buckets dirs
bmd := t.owner.bmd.get()
bmd.Range(nil, nil, func(bck *meta.Bck) bool {
err = enabledMi.CreateMissingBckDirs(bck.Bucket())
return err != nil // break on error
})
if err != nil {
t.writeErr(w, r, err)
return
}
}
func (t *target) attachMpath(w http.ResponseWriter, r *http.Request, mpath string) {
force := cos.IsParseBool(r.URL.Query().Get(apc.QparamForce))
addedMi, err := t.fsprg.attachMpath(mpath, force)
if err != nil {
t.writeErr(w, r, err)
return
}
if addedMi == nil {
return
}
// create missing buckets dirs, if any
bmd := t.owner.bmd.get()
bmd.Range(nil, nil, func(bck *meta.Bck) bool {
err = addedMi.CreateMissingBckDirs(bck.Bucket())
return err != nil // break on error
})
if err != nil {
t.writeErr(w, r, err)
return
}
}
func (t *target) disableMpath(w http.ResponseWriter, r *http.Request, mpath string) {
dontResilver := cos.IsParseBool(r.URL.Query().Get(apc.QparamDontResilver))
disabledMi, err := t.fsprg.disableMpath(mpath, dontResilver)
if err != nil {
if cmn.IsErrMountpathNotFound(err) {
t.writeErr(w, r, err, http.StatusNotFound)
} else {
// cmn.ErrInvalidMountpath
t.writeErr(w, r, err)
}
return
}
if disabledMi == nil {
w.WriteHeader(http.StatusNoContent)
}
}
func (t *target) detachMpath(w http.ResponseWriter, r *http.Request, mpath string) {
dontResilver := cos.IsParseBool(r.URL.Query().Get(apc.QparamDontResilver))
if _, err := t.fsprg.detachMpath(mpath, dontResilver); err != nil {
t.writeErr(w, r, err)
}
}
func (t *target) receiveBMD(newBMD *bucketMD, msg *aisMsg, payload msPayload, tag, caller string, silent bool) (err error) {
var oldVer int64
if msg.UUID == "" {
oldVer, err = t.applyBMD(newBMD, msg, payload, tag)
if newBMD.Version > oldVer {
if err == nil {
logmsync(oldVer, newBMD, msg, caller, newBMD.StringEx())
}
}
return
}
// txn [before -- do -- after]
if errDone := t.transactions.commitBefore(caller, msg); errDone != nil {
err = fmt.Errorf("%s commit-before %s, errDone: %v", t, newBMD, errDone)
if !silent {
nlog.Errorln(err)
}
return
}
oldVer, err = t.applyBMD(newBMD, msg, payload, tag)
// log
switch {
case err != nil:
nlog.Errorf("%s: %v (receive %s from %q, action %q, uuid %q)", t, err, newBMD.StringEx(), caller, msg.Action, msg.UUID)
case newBMD.Version > oldVer:
logmsync(oldVer, newBMD, msg, caller, newBMD.StringEx())
case newBMD.Version == oldVer:
nlog.Warningf("%s (same version w/ txn commit): receive %s from %q (action %q, uuid %q)",
t, newBMD.StringEx(), caller, msg.Action, msg.UUID)
}
// --after]
if errDone := t.transactions.commitAfter(caller, msg, err, newBMD); errDone != nil {
err = fmt.Errorf("%s commit-after %s, err: %v, errDone: %v", t, newBMD, err, errDone)
if !silent {
nlog.Errorln(err)
}
}
return
}
func (t *target) applyBMD(newBMD *bucketMD, msg *aisMsg, payload msPayload, tag string) (int64, error) {
_, psi := t.getPrimaryURLAndSI(nil)
t.owner.bmd.Lock()
rmbcks, oldVer, emsg, err := t._syncBMD(newBMD, msg, payload, psi)
t.owner.bmd.Unlock()
if err != nil {
nlog.Errorln(err)
} else if oldVer < newBMD.Version {
t.regstate.prevbmd.Store(false)
t._postBMD(newBMD, tag, rmbcks)
}
if emsg != "" {
nlog.Errorln(emsg)
}
return oldVer, err
}
// executes under lock
func (t *target) _syncBMD(newBMD *bucketMD, msg *aisMsg, payload msPayload, psi *meta.Snode) (rmbcks []*meta.Bck,
oldVer int64, emsg string, err error) {
var (
createErrs []error
destroyErrs []error
bmd = t.owner.bmd.get()
)
if err = bmd.validateUUID(newBMD, t.si, psi, ""); err != nil {
cos.ExitLog(err) // FATAL: cluster integrity error (cie)
return
}
// check downgrade
if oldVer = bmd.version(); newBMD.version() <= oldVer {
if newBMD.version() < oldVer {
err = newErrDowngrade(t.si, bmd.StringEx(), newBMD.StringEx())
}
return
}
nilbmd := bmd.version() == 0 || t.regstate.prevbmd.Load()
// 1. create
newBMD.Range(nil, nil, func(bck *meta.Bck) bool {
if _, present := bmd.Get(bck); present {
return false
}
errs := fs.CreateBucket(bck.Bucket(), nilbmd)
if len(errs) > 0 {
createErrs = append(createErrs, errs...)
}
return false
})
if len(createErrs) > 0 {
err = fmt.Errorf("%s: failed to add new buckets: %s, old/cur %s(%t): %v",
t, newBMD, bmd, nilbmd, errors.Join(createErrs...))
return
}
// 2. persist
if err = t.owner.bmd.putPersist(newBMD, payload); err != nil {
cos.ExitLog(err)
return
}
// 3. delete, ignore errors
bmd.Range(nil, nil, func(obck *meta.Bck) bool {
f := &delb{obck: obck}
newBMD.Range(nil, nil, f.do)
if !f.present {
rmbcks = append(rmbcks, obck)
if errD := fs.DestroyBucket("recv-bmd-"+msg.Action, obck.Bucket(), obck.Props.BID); errD != nil {
destroyErrs = append(destroyErrs, errD)
}
}
return false
})
if len(destroyErrs) > 0 {
emsg = fmt.Sprintf("%s: failed to cleanup destroyed buckets: %s, old/cur %s(%t): %v",
t, newBMD, bmd, nilbmd, errors.Join(destroyErrs...))
}
return
}
func (f *delb) do(nbck *meta.Bck) bool {
if !f.obck.Equal(nbck, false /*ignore BID*/, false /* ignore backend */) {
return false // keep going
}
f.present = true
// assorted props changed?
if f.obck.Props.Mirror.Enabled && !nbck.Props.Mirror.Enabled {
flt := xreg.Flt{Kind: apc.ActPutCopies, Bck: nbck}
xreg.DoAbort(flt, errors.New("apply-bmd"))
// NOTE: apc.ActMakeNCopies takes care of itself
}
if f.obck.Props.EC.Enabled && !nbck.Props.EC.Enabled {
flt := xreg.Flt{Kind: apc.ActECEncode, Bck: nbck}
xreg.DoAbort(flt, errors.New("apply-bmd"))
}
return true // break
}
func (t *target) _postBMD(newBMD *bucketMD, tag string, rmbcks []*meta.Bck) {
// evict LOM cache
if len(rmbcks) > 0 {
errV := fmt.Errorf("[post-bmd] %s %s: remove bucket%s", tag, newBMD, cos.Plural(len(rmbcks)))
xreg.AbortAllBuckets(errV, rmbcks...)
go func(bcks ...*meta.Bck) {
for _, b := range bcks {
core.UncacheBck(b)
}
}(rmbcks...)
}
if tag != bmdReg {
if err := ec.ECM.BMDChanged(); err != nil {
nlog.Errorf("Failed to initialize EC manager: %v", err)
}
}
// since some buckets may have been destroyed
cs := fs.Cap()
if cs.Err() != nil {
_ = t.OOS(nil)
}
}
// is called under lock
func (t *target) receiveRMD(newRMD *rebMD, msg *aisMsg) (err error) {
rmd := t.owner.rmd.get()
if newRMD.Version <= rmd.Version {
if newRMD.Version < rmd.Version {
err = newErrDowngrade(t.si, rmd.String(), newRMD.String())
}
return
}
smap := t.owner.smap.get()
if err = smap.validate(); err != nil {
return
}
if smap.GetNode(t.SID()) == nil {
err = fmt.Errorf("%s (self) not present in %s", t, smap.StringEx())
return
}
for _, tsi := range rmd.TargetIDs {
if smap.GetNode(tsi) == nil {
nlog.Warningf("%s: %s (target_id) not present in %s (old %s, new %s)",
t.si, tsi, smap.StringEx(), rmd, newRMD)
}
}
if !t.regstate.disabled.Load() {
//
// run rebalance
//
notif := &xact.NotifXact{
Base: nl.Base{When: core.UponTerm, Dsts: []string{equalIC}, F: t.notifyTerm},
}
if msg.Action == apc.ActRebalance {
nlog.Infof("%s: starting user-requested rebalance[%s]", t, msg.UUID)
go t.reb.RunRebalance(&smap.Smap, newRMD.Version, notif)
return
}
switch msg.Action {
case apc.ActStartMaintenance, apc.ActDecommissionNode, apc.ActShutdownNode, apc.ActRmNodeUnsafe:
var opts apc.ActValRmNode
if err := cos.MorphMarshal(msg.Value, &opts); err != nil {
debug.AssertNoErr(err) // unlikely
} else {
var s string
if opts.DaemonID == t.SID() {
s = " (to subsequently deactivate or remove _this_ target)"
}
nlog.Infof("%s: starting '%s' triggered rebalance[%s]%s: %+v",
t, msg.Action, xact.RebID2S(newRMD.Version), s, opts)
}
default:
nlog.Infof("%s: starting rebalance[%s]", t, xact.RebID2S(newRMD.Version))
}
go t.reb.RunRebalance(&smap.Smap, newRMD.Version, notif)
if newRMD.Resilver != "" {
nlog.Infof("%s: ... and resilver", t)
go t.runResilver(res.Args{UUID: newRMD.Resilver, SkipGlobMisplaced: true}, nil /*wg*/)
}
t.owner.rmd.put(newRMD)
// TODO: move and refactor
} else if msg.Action == apc.ActAdminJoinTarget && daemon.cli.target.standby && msg.Name == t.SID() {
nlog.Warningf("%s: standby => join %s", t, msg)
if _, err = t.joinCluster(msg.Action); err == nil {
err = t.endStartupStandby()
}
t.owner.rmd.put(newRMD)
}
return
}
func (t *target) ensureLatestBMD(msg *aisMsg, r *http.Request) {
bmd, bmdVersion := t.owner.bmd.Get(), msg.BMDVersion
if bmd.Version < bmdVersion {
nlog.Errorf("%s: local %s < v%d %s - running fixup...", t, bmd, bmdVersion, msg)
t.BMDVersionFixup(r)
} else if bmd.Version > bmdVersion {
// If metasync outraces the request, we end up here, just log it and continue.
nlog.Warningf("%s: local %s > v%d %s", t, bmd, bmdVersion, msg)
}
}
func (t *target) getPrimaryBMD(renamed string) (bmd *bucketMD, err error) {
smap := t.owner.smap.get()
if err = smap.validate(); err != nil {
return nil, cmn.NewErrFailedTo(t, "get-primary-bmd", smap, err)
}
var (
what = apc.WhatBMD
q = url.Values{apc.QparamWhat: []string{what}}
psi = smap.Primary
path = apc.URLPathDae.S
url = psi.URL(cmn.NetIntraControl)
timeout = cmn.Rom.CplaneOperation()
)
if renamed != "" {
q.Set(whatRenamedLB, renamed)
}
cargs := allocCargs()
{
cargs.si = psi
cargs.req = cmn.HreqArgs{Method: http.MethodGet, Base: url, Path: path, Query: q}
cargs.timeout = timeout
cargs.cresv = cresBM{}
}
res := t.call(cargs, smap)
if res.err != nil {
time.Sleep(timeout / 2)
smap = t.owner.smap.get()
res = t.call(cargs, smap)
if res.err != nil {
err = res.errorf("%s: failed to GET(%q)", t.si, what)
}
}
if err == nil {
bmd = res.v.(*bucketMD)
}
freeCargs(cargs)
freeCR(res)
return
}
func (t *target) BMDVersionFixup(r *http.Request, bcks ...cmn.Bck) {
var (
caller string
bck cmn.Bck
)
if len(bcks) > 0 {
bck = bcks[0]
}
time.Sleep(200 * time.Millisecond)
newBucketMD, err := t.getPrimaryBMD(bck.Name)
if err != nil {
nlog.Errorln(err)
return
}
msg := t.newAmsgStr("get-what="+apc.WhatBMD, newBucketMD)
if r != nil {
caller = r.Header.Get(apc.HdrCallerName)
}
t.regstate.mu.Lock()
if daemon.stopping.Load() {
t.regstate.mu.Unlock()
return
}
err = t.receiveBMD(newBucketMD, msg, nil, bmdFixup, caller, true /*silent*/)
t.regstate.mu.Unlock()
if err != nil && !isErrDowngrade(err) {
nlog.Errorln(err)
}
}
// [METHOD] /v1/metasync
func (t *target) metasyncHandler(w http.ResponseWriter, r *http.Request) {
if daemon.stopping.Load() {
w.WriteHeader(http.StatusServiceUnavailable)
return
}
switch r.Method {
case http.MethodPut:
t.regstate.mu.Lock()
if daemon.stopping.Load() {
w.WriteHeader(http.StatusServiceUnavailable)
} else {
t.metasyncPut(w, r)
}
t.regstate.mu.Unlock()
case http.MethodPost:
t.metasyncPost(w, r)
default:
cmn.WriteErr405(w, r, http.MethodPost, http.MethodPut)
}
}
// PUT /v1/metasync
// compare w/ p.metasyncHandler (NOTE: executes under regstate lock)
func (t *target) metasyncPut(w http.ResponseWriter, r *http.Request) {
var (
err = &errMsync{}
cii = &err.Cii
)
if r.Method != http.MethodPut {
cmn.WriteErr405(w, r, http.MethodPut)
return
}
payload := make(msPayload)
if errP := payload.unmarshal(r.Body, "metasync put"); errP != nil {
cmn.WriteErr(w, r, errP)
return
}
// 1. extract
var (
caller = r.Header.Get(apc.HdrCallerName)
newConf, msgConf, errConf = t.extractConfig(payload, caller)
newSmap, msgSmap, errSmap = t.extractSmap(payload, caller, false /*skip validation*/)
newBMD, msgBMD, errBMD = t.extractBMD(payload, caller)
newRMD, msgRMD, errRMD = t.extractRMD(payload, caller)
newEtlMD, msgEtlMD, errEtlMD = t.extractEtlMD(payload, caller)
)
// 2. apply
if errConf == nil && newConf != nil {
errConf = t.receiveConfig(newConf, msgConf, payload, caller)
}
if errSmap == nil && newSmap != nil {
errSmap = t.receiveSmap(newSmap, msgSmap, payload, caller, t.htrun.smapUpdatedCB)
}
if errBMD == nil && newBMD != nil {
errBMD = t.receiveBMD(newBMD, msgBMD, payload, bmdRecv, caller, false /*silent*/)
}
if errRMD == nil && newRMD != nil {
rmd := t.owner.rmd.get()
logmsync(rmd.Version, newRMD, msgRMD, caller)
t.owner.rmd.Lock()
errRMD = t.receiveRMD(newRMD, msgRMD)
t.owner.rmd.Unlock()
}
if errEtlMD == nil && newEtlMD != nil {
errEtlMD = t.receiveEtlMD(newEtlMD, msgEtlMD, payload, caller, _stopETLs)
}
// 3. respond
if errConf == nil && errSmap == nil && errBMD == nil && errRMD == nil && errEtlMD == nil {
return
}
cii.fill(&t.htrun)
retErr := err.message(errConf, errSmap, errBMD, errRMD, errEtlMD, nil)
t.writeErr(w, r, retErr, http.StatusConflict)
}
func _stopETLs(newEtlMD, oldEtlMD *etlMD) {
for id := range oldEtlMD.ETLs {
if _, ok := newEtlMD.ETLs[id]; ok {
continue
}
// TODO: stop only when running
nlog.Infof("stopping (removed from md) etl[%s] (old md v%d, new v%d)", id, oldEtlMD.Version, newEtlMD.Version)
etl.Stop(id, nil)
}
}
// compare w/ p.receiveConfig
func (t *target) receiveConfig(newConfig *globalConfig, msg *aisMsg, payload msPayload, caller string) (err error) {
oldConfig := cmn.GCO.Get()
logmsync(oldConfig.Version, newConfig, msg, caller)
t.owner.config.Lock()
err = t._recvCfg(newConfig, payload)
t.owner.config.Unlock()
if err != nil {
return
}
if !t.NodeStarted() {
if msg.Action == apc.ActAttachRemAis || msg.Action == apc.ActDetachRemAis {
nlog.Errorf("%s: cannot handle %s (%s => %s) - starting up...", t, msg, oldConfig, newConfig)
}
return
}
// special: remais update
if msg.Action == apc.ActAttachRemAis || msg.Action == apc.ActDetachRemAis {
return t.attachDetachRemAis(newConfig, msg)
}
if !newConfig.Backend.EqualRemAIS(&oldConfig.Backend, t.String()) {
if aisConf := newConfig.Backend.Get(apc.AIS); aisConf != nil {
err = t.attachDetachRemAis(newConfig, msg)
} else {
t.backend[apc.AIS] = backend.NewAIS(t)
}
}
return
}
// NOTE: apply the entire config: add new and update existing entries (remote clusters)
func (t *target) attachDetachRemAis(newConfig *globalConfig, msg *aisMsg) (err error) {
var (
aisBackend *backend.AISBackendProvider
aisConf = newConfig.Backend.Get(apc.AIS)
)
debug.Assert(aisConf != nil)
aisBackend = t.aisBackend()
return aisBackend.Apply(aisConf, msg.Action, &newConfig.ClusterConfig)
}
// POST /v1/metasync
func (t *target) metasyncPost(w http.ResponseWriter, r *http.Request) {
payload := make(msPayload)
if err := payload.unmarshal(r.Body, "metasync post"); err != nil {
cmn.WriteErr(w, r, err)
return
}
caller := r.Header.Get(apc.HdrCallerName)
newSmap, msg, err := t.extractSmap(payload, caller, true /*skip validation*/)