forked from NVIDIA/aistore
/
htrun.go
2079 lines (1937 loc) · 57.3 KB
/
htrun.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-2023, NVIDIA CORPORATION. All rights reserved.
*/
package ais
import (
"bytes"
"context"
"errors"
"fmt"
"io"
"log"
"net/http"
"net/url"
"os"
"path/filepath"
"runtime"
"strconv"
"strings"
"sync"
"time"
"github.com/artashesbalabekyan/aistore/3rdparty/glog"
"github.com/artashesbalabekyan/aistore/api/apc"
"github.com/artashesbalabekyan/aistore/cluster"
"github.com/artashesbalabekyan/aistore/cluster/meta"
"github.com/artashesbalabekyan/aistore/cmn"
"github.com/artashesbalabekyan/aistore/cmn/atomic"
"github.com/artashesbalabekyan/aistore/cmn/cos"
"github.com/artashesbalabekyan/aistore/cmn/debug"
"github.com/artashesbalabekyan/aistore/cmn/jsp"
"github.com/artashesbalabekyan/aistore/cmn/k8s"
"github.com/artashesbalabekyan/aistore/cmn/mono"
"github.com/artashesbalabekyan/aistore/memsys"
"github.com/artashesbalabekyan/aistore/stats"
"github.com/artashesbalabekyan/aistore/xact"
"github.com/artashesbalabekyan/aistore/xact/xreg"
jsoniter "github.com/json-iterator/go"
"github.com/prometheus/client_golang/prometheus/promhttp"
"github.com/tinylib/msgp/msgp"
)
const ciePrefix = "cluster integrity error cie#"
// extra or extended state - currently, target only
type htext interface {
rebMarked() xact.Marked
}
type htrun struct {
si *meta.Snode
keepalive keepaliver
statsT stats.Tracker
netServ struct {
pub *netServer
control *netServer
data *netServer
}
client struct {
control *http.Client // http client for intra-cluster comm
data *http.Client // http client to execute target <=> target GET & PUT (object)
}
owner struct {
smap *smapOwner
bmd bmdOwner // an interface with proxy and target impl-s
rmd *rmdOwner
config *configOwner
etl etlOwner // ditto
}
startup struct {
cluster atomic.Int64 // mono.NanoTime() since cluster startup, zero prior to that
node atomic.Int64 // ditto - for the node
}
gmm *memsys.MMSA // system pagesize-based memory manager and slab allocator
smm *memsys.MMSA // system MMSA for small-size allocations
}
///////////
// htrun //
///////////
// interface guard
var _ cluster.Node = (*htrun)(nil)
func (h *htrun) DataClient() *http.Client { return h.client.data }
func (h *htrun) Snode() *meta.Snode { return h.si }
func (h *htrun) callerName() string { return h.si.String() }
func (h *htrun) SID() string { return h.si.ID() }
func (h *htrun) String() string { return h.si.String() }
func (h *htrun) Bowner() meta.Bowner { return h.owner.bmd }
func (h *htrun) Sowner() meta.Sowner { return h.owner.smap }
// NOTE: currently, only 'resume' (see also: kaSuspendMsg)
func (h *htrun) smapUpdatedCB(_, _ *smapX, nfl, ofl cos.BitFlags) {
if ofl.IsAnySet(meta.SnodeMaintDecomm) && !nfl.IsAnySet(meta.SnodeMaintDecomm) {
h.keepalive.ctrl(kaResumeMsg)
}
}
func (h *htrun) parseReq(w http.ResponseWriter, r *http.Request, apireq *apiRequest) (err error) {
debug.Assert(len(apireq.prefix) != 0)
apireq.items, err = h.apiItems(w, r, apireq.after, false, apireq.prefix)
if err != nil {
return
}
debug.Assert(len(apireq.items) > apireq.bckIdx)
bckName := apireq.items[apireq.bckIdx]
if apireq.dpq == nil {
apireq.query = r.URL.Query()
} else if err = apireq.dpq.fromRawQ(r.URL.RawQuery); err != nil {
return
}
apireq.bck, err = newBckFromQ(bckName, apireq.query, apireq.dpq)
if err != nil {
h.writeErr(w, r, err)
}
return
}
func (h *htrun) cluMeta(opts cmetaFillOpt) (*cluMeta, error) {
xele := voteInProgress()
cm := &cluMeta{
SI: h.si,
VoteInProgress: xele != nil,
}
if !opts.skipConfig {
var err error
cm.Config, err = h.owner.config.get()
if err != nil {
return nil, err
}
}
// don't send Smap when it is undergoing changes (and is about to get metasync-ed)
if !opts.skipSmap {
cm.Smap = h.owner.smap.get()
}
if !opts.skipBMD {
cm.BMD = h.owner.bmd.get()
}
if !opts.skipRMD {
cm.RMD = h.owner.rmd.get()
}
if !opts.skipEtlMD {
cm.EtlMD = h.owner.etl.get()
}
if h.si.IsTarget() && opts.fillRebMarker {
rebMarked := opts.htext.rebMarked()
cm.RebInterrupted, cm.Restarted = rebMarked.Interrupted, rebMarked.Restarted
}
return cm, nil
}
// usage: [API call => handler => ClusterStartedWithRetry ]
func (h *htrun) cluStartedWithRetry() bool {
if clutime := h.startup.cluster.Load(); clutime > 0 {
return true
}
if !h.NodeStarted() {
return false
}
time.Sleep(time.Second)
clutime := h.startup.cluster.Load()
if clutime == 0 {
glog.ErrorDepth(1, fmt.Sprintf("%s: cluster is starting up", h.si))
}
return clutime > 0
}
func (h *htrun) ClusterStarted() bool { return h.startup.cluster.Load() > 0 } // see also: p.ready()
func (h *htrun) markClusterStarted() { h.startup.cluster.Store(mono.NanoTime()) }
func (h *htrun) NodeStarted() bool { return h.startup.node.Load() > 0 }
func (h *htrun) markNodeStarted() { h.startup.node.Store(mono.NanoTime()) }
func (h *htrun) regNetHandlers(networkHandlers []networkHandler) {
var (
path string
config = cmn.GCO.Get()
)
// common, debug
for r, nh := range debug.Handlers() {
h.registerPublicNetHandler(r, nh)
}
// node type specific
for _, nh := range networkHandlers {
var reg bool
if nh.r[0] == '/' { // absolute path
path = nh.r
} else {
path = cos.JoinWords(apc.Version, nh.r)
}
debug.Assert(nh.net != 0)
if nh.net.isSet(accessNetPublic) {
h.registerPublicNetHandler(path, nh.h)
reg = true
}
if config.HostNet.UseIntraControl && nh.net.isSet(accessNetIntraControl) {
h.registerIntraControlNetHandler(path, nh.h)
reg = true
}
if config.HostNet.UseIntraData && nh.net.isSet(accessNetIntraData) {
h.registerIntraDataNetHandler(path, nh.h)
reg = true
}
if reg {
continue
}
// none of the above
if !config.HostNet.UseIntraControl && !config.HostNet.UseIntraData {
// no intra-cluster networks: default to pub net
h.registerPublicNetHandler(path, nh.h)
} else if config.HostNet.UseIntraControl && nh.net.isSet(accessNetIntraData) {
// (not configured) data defaults to (configured) control
h.registerIntraControlNetHandler(path, nh.h)
} else {
debug.Assert(config.HostNet.UseIntraData && nh.net.isSet(accessNetIntraControl))
// (not configured) control defaults to (configured) data
h.registerIntraDataNetHandler(path, nh.h)
}
}
// common Prometheus
if h.statsT.IsPrometheus() {
nh := networkHandler{r: "/" + apc.Metrics, h: promhttp.Handler().ServeHTTP}
path := nh.r // absolute
h.registerPublicNetHandler(path, nh.h)
}
}
func (h *htrun) registerPublicNetHandler(path string, handler func(http.ResponseWriter, *http.Request)) {
for _, v := range allHTTPverbs {
h.netServ.pub.muxers[v].HandleFunc(path, handler)
if !strings.HasSuffix(path, "/") {
h.netServ.pub.muxers[v].HandleFunc(path+"/", handler)
}
}
}
func (h *htrun) registerIntraControlNetHandler(path string, handler func(http.ResponseWriter, *http.Request)) {
for _, v := range allHTTPverbs {
h.netServ.control.muxers[v].HandleFunc(path, handler)
if !strings.HasSuffix(path, "/") {
h.netServ.control.muxers[v].HandleFunc(path+"/", handler)
}
}
}
func (h *htrun) registerIntraDataNetHandler(path string, handler func(http.ResponseWriter, *http.Request)) {
for _, v := range allHTTPverbs {
h.netServ.data.muxers[v].HandleFunc(path, handler)
if !strings.HasSuffix(path, "/") {
h.netServ.data.muxers[v].HandleFunc(path+"/", handler)
}
}
}
func (h *htrun) init(config *cmn.Config) {
const (
defaultControlWriteBufferSize = 16 * cos.KiB // for more defaults see cmn/network.go
defaultControlReadBufferSize = 16 * cos.KiB
)
h.client.control = cmn.NewClient(cmn.TransportArgs{
Timeout: config.Client.Timeout.D(),
WriteBufferSize: defaultControlWriteBufferSize,
ReadBufferSize: defaultControlReadBufferSize,
UseHTTPS: config.Net.HTTP.UseHTTPS,
SkipVerify: config.Net.HTTP.SkipVerify,
})
wbuf, rbuf := config.Net.HTTP.WriteBufferSize, config.Net.HTTP.ReadBufferSize
// NOTE: when not configured use AIS defaults (to override the usual 4KB)
if wbuf == 0 {
wbuf = cmn.DefaultWriteBufferSize
}
if rbuf == 0 {
rbuf = cmn.DefaultReadBufferSize
}
h.client.data = cmn.NewClient(cmn.TransportArgs{
Timeout: config.Client.TimeoutLong.D(),
WriteBufferSize: wbuf,
ReadBufferSize: rbuf,
UseHTTPS: config.Net.HTTP.UseHTTPS,
SkipVerify: config.Net.HTTP.SkipVerify,
})
tcpbuf := config.Net.L4.SndRcvBufSize
if h.si.IsProxy() {
tcpbuf = 0
} else if tcpbuf == 0 {
tcpbuf = cmn.DefaultSendRecvBufferSize // ditto: targets use AIS default when not configured
}
muxers := newMuxers()
h.netServ.pub = &netServer{muxers: muxers, sndRcvBufSize: tcpbuf}
h.netServ.control = h.netServ.pub // if not separately configured, intra-control net is public
if config.HostNet.UseIntraControl {
muxers = newMuxers()
h.netServ.control = &netServer{muxers: muxers, sndRcvBufSize: 0}
}
h.netServ.data = h.netServ.control // if not configured, intra-data net is intra-control
if config.HostNet.UseIntraData {
muxers = newMuxers()
h.netServ.data = &netServer{muxers: muxers, sndRcvBufSize: tcpbuf}
}
h.owner.smap = newSmapOwner(config)
h.owner.rmd = newRMDOwner()
h.owner.rmd.load()
h.gmm = memsys.PageMM()
h.gmm.RegWithHK()
h.smm = memsys.ByteMM()
h.smm.RegWithHK()
}
func (h *htrun) initNetworks() {
var (
s string
pubAddr meta.NetInfo
intraControlAddr meta.NetInfo
intraDataAddr meta.NetInfo
config = cmn.GCO.Get()
port = strconv.Itoa(config.HostNet.Port)
proto = config.Net.HTTP.Proto
addrList, err = getLocalIPv4List()
)
if err != nil {
cos.ExitLogf("failed to get local IP addr list: %v", err)
}
// NOTE in re K8S deployment:
// public hostname could be LoadBalancer external IP or a service DNS
k8sDetected := k8s.Detect() == nil
if k8sDetected && config.HostNet.Hostname != "" {
glog.Infof("detected K8S deployment, skipping hostname validation for %q", config.HostNet.Hostname)
pubAddr = *meta.NewNetInfo(proto, config.HostNet.Hostname, port)
} else {
pubAddr, err = getNetInfo(addrList, proto, config.HostNet.Hostname, port)
}
if err != nil {
cos.ExitLogf("failed to get %s IPv4/hostname: %v", cmn.NetPublic, err)
}
if config.HostNet.Hostname != "" {
s = " (config: " + config.HostNet.Hostname + ")"
}
glog.Infof("%s (user) access: [%s]%s", cmn.NetPublic, pubAddr, s)
intraControlAddr = pubAddr
if config.HostNet.UseIntraControl {
icport := strconv.Itoa(config.HostNet.PortIntraControl)
intraControlAddr, err = getNetInfo(addrList, proto, config.HostNet.HostnameIntraControl, icport)
if err != nil {
cos.ExitLogf("failed to get %s IPv4/hostname: %v", cmn.NetIntraControl, err)
}
s = ""
if config.HostNet.HostnameIntraControl != "" {
s = " (config: " + config.HostNet.HostnameIntraControl + ")"
}
glog.Infof("%s access: [%s]%s", cmn.NetIntraControl, intraControlAddr, s)
}
intraDataAddr = pubAddr
if config.HostNet.UseIntraData {
idport := strconv.Itoa(config.HostNet.PortIntraData)
intraDataAddr, err = getNetInfo(addrList, proto, config.HostNet.HostnameIntraData, idport)
if err != nil {
cos.ExitLogf("failed to get %s IPv4/hostname: %v", cmn.NetIntraData, err)
}
s = ""
if config.HostNet.HostnameIntraData != "" {
s = " (config: " + config.HostNet.HostnameIntraData + ")"
}
glog.Infof("%s access: [%s]%s", cmn.NetIntraData, intraDataAddr, s)
}
mustDiffer(pubAddr,
config.HostNet.Port,
true,
intraControlAddr,
config.HostNet.PortIntraControl,
config.HostNet.UseIntraControl,
"pub/ctl",
)
mustDiffer(pubAddr,
config.HostNet.Port,
true,
intraDataAddr,
config.HostNet.PortIntraData,
config.HostNet.UseIntraData,
"pub/data",
)
mustDiffer(intraDataAddr,
config.HostNet.PortIntraData,
config.HostNet.UseIntraData,
intraControlAddr,
config.HostNet.PortIntraControl,
config.HostNet.UseIntraControl,
"ctl/data",
)
h.si = &meta.Snode{
PubNet: pubAddr,
ControlNet: intraControlAddr,
DataNet: intraDataAddr,
}
}
func mustDiffer(ip1 meta.NetInfo, port1 int, use1 bool, ip2 meta.NetInfo, port2 int, use2 bool, tag string) {
if !use1 || !use2 {
return
}
if ip1.Hostname == ip2.Hostname && port1 == port2 {
cos.ExitLogf("%s: cannot use the same IP:port (%s) for two networks", tag, ip1)
}
}
// at startup, check this Snode vs locally stored Smap replica (NOTE: some errors are FATAL)
func (h *htrun) loadSmap() (smap *smapX, reliable bool) {
smap = newSmap()
loaded, err := h.owner.smap.load(smap)
if err != nil {
glog.Errorf("Failed to load cluster map (\"Smap\"): %v - reinitializing", err)
return
}
if !loaded {
return // no local replica - joining from scratch
}
node := smap.GetNode(h.SID())
if node == nil {
cos.ExitLogf("%s: %s is not present in the loaded %s", cmn.BadSmapPrefix, h.si, smap.StringEx())
return
}
if node.Type() != h.si.Type() {
cos.ExitLogf("%s: %s is %q while the node in the loaded %s is %q", cmn.BadSmapPrefix,
h.si, h.si.Type(), smap.StringEx(), node.Type())
return
}
// NOTE: not enforcing Snode's immutability - in particular, IPs that may change upon restart
// in certain environments
if _, err := smap.IsDupNet(h.si); err != nil {
glog.Error(err)
return
}
reliable = true
return
}
func (h *htrun) setDaemonConfigMsg(w http.ResponseWriter, r *http.Request, msg *apc.ActMsg, query url.Values) {
var (
transient = cos.IsParseBool(query.Get(apc.ActTransient))
toUpdate = &cmn.ConfigToUpdate{}
)
if err := cos.MorphMarshal(msg.Value, toUpdate); err != nil {
h.writeErrf(w, r, cmn.FmtErrMorphUnmarshal, h.si, msg.Action, msg.Value, err)
return
}
if err := h.owner.config.setDaemonConfig(toUpdate, transient); err != nil {
h.writeErr(w, r, err)
}
}
func (h *htrun) setDaemonConfigQuery(w http.ResponseWriter, r *http.Request) {
var (
query = r.URL.Query()
transient = cos.IsParseBool(query.Get(apc.ActTransient))
toUpdate = &cmn.ConfigToUpdate{}
)
if err := toUpdate.FillFromQuery(query); err != nil {
h.writeErr(w, r, err)
return
}
err := h.owner.config.setDaemonConfig(toUpdate, transient)
if err != nil {
h.writeErr(w, r, err)
}
}
func (h *htrun) run() error {
config := cmn.GCO.Get()
// A wrapper to glog http.Server errors - otherwise
// os.Stderr would be used, as per golang.org/pkg/net/http/#Server
logger := log.New(&glogWriter{}, "net/http err: ", 0)
if config.HostNet.UseIntraControl || config.HostNet.UseIntraData {
var errCh chan error
if config.HostNet.UseIntraControl && config.HostNet.UseIntraData {
errCh = make(chan error, 3)
} else {
errCh = make(chan error, 2)
}
if config.HostNet.UseIntraControl {
go func() {
addr := h.si.ControlNet.TCPEndpoint()
errCh <- h.netServ.control.listen(addr, logger)
}()
}
if config.HostNet.UseIntraData {
go func() {
addr := h.si.DataNet.TCPEndpoint()
errCh <- h.netServ.data.listen(addr, logger)
}()
}
go func() {
addr := h.pubListeningAddr(config)
errCh <- h.netServ.pub.listen(addr, logger)
}()
return <-errCh
}
addr := h.pubListeningAddr(config)
return h.netServ.pub.listen(addr, logger)
}
// testing environment excluding Kubernetes: listen on `host:port`
// otherwise (including production): listen on `*:port`
func (h *htrun) pubListeningAddr(config *cmn.Config) string {
var (
testingEnv = config.TestingEnv()
k8sDetected = k8s.Detect() == nil
)
if testingEnv && !k8sDetected {
return h.si.PubNet.TCPEndpoint()
}
return ":" + h.si.PubNet.Port
}
func (h *htrun) stopHTTPServer() {
h.netServ.pub.shutdown()
config := cmn.GCO.Get()
if config.HostNet.UseIntraControl {
h.netServ.control.shutdown()
}
if config.HostNet.UseIntraData {
h.netServ.data.shutdown()
}
}
// remove self from Smap (if required), terminate http, and wait (w/ timeout)
// for running xactions to abort
func (h *htrun) stop(rmFromSmap bool) {
if rmFromSmap {
h.unregisterSelf(true)
}
glog.Warningln("Shutting down HTTP")
wg := &sync.WaitGroup{}
wg.Add(1)
go func() {
time.Sleep(time.Second / 2)
h.stopHTTPServer()
wg.Done()
}()
entry := xreg.GetRunning(xreg.Flt{})
if entry != nil {
time.Sleep(time.Second)
entry = xreg.GetRunning(xreg.Flt{})
if entry != nil {
glog.Warningf("Timed out waiting for %q to finish aborting", entry.Kind())
}
}
if h.si.IsTarget() {
wg.Wait()
}
}
//
// intra-cluster IPC, control plane
// call another target or a proxy; optionally, include a json-encoded body
//
func (h *htrun) _call(si *meta.Snode, bargs *bcastArgs, results *bcastResults) {
cargs := allocCargs()
{
cargs.si = si
cargs.req = bargs.req
cargs.timeout = bargs.timeout
}
cargs.req.Base = si.URL(bargs.network)
if bargs.req.BodyR != nil {
cargs.req.BodyR, _ = bargs.req.BodyR.(cos.ReadOpenCloser).Open()
}
cargs.cresv = bargs.cresv
res := h.call(cargs)
if bargs.async {
freeCR(res) // discard right away
} else {
results.mu.Lock()
results.s = append(results.s, res)
results.mu.Unlock()
}
freeCargs(cargs)
}
func (h *htrun) call(args *callArgs) (res *callResult) {
var (
req *http.Request
resp *http.Response
client *http.Client
sid = unknownDaemonID
)
res = allocCR()
if args.si != nil {
sid = args.si.ID()
res.si = args.si
}
debug.Assert(args.si != nil || args.req.Base != "") // either si or base
if args.req.Base == "" && args.si != nil {
args.req.Base = args.si.ControlNet.URL // by default, use intra-cluster control network
}
if args.req.Header == nil {
args.req.Header = make(http.Header)
}
switch args.timeout {
case apc.DefaultTimeout:
req, res.err = args.req.Req()
if res.err != nil {
break
}
client = h.client.control
case apc.LongTimeout:
req, res.err = args.req.Req()
if res.err != nil {
break
}
client = h.client.data
default:
var cancel context.CancelFunc
if args.timeout == 0 {
args.timeout = cmn.Timeout.CplaneOperation()
}
req, _, cancel, res.err = args.req.ReqWithTimeout(args.timeout)
if res.err != nil {
break
}
defer cancel()
// NOTE: timeout handling
// - timeout causes context.deadlineExceededError, i.e. "context deadline exceeded"
// - the two knobs are configurable via "client_timeout" and "client_long_timeout",
// respectively (client section in the global config)
if args.timeout > h.client.control.Timeout {
client = h.client.data
} else {
client = h.client.control
}
}
if res.err != nil {
res.details = fmt.Sprintf("FATAL: failed to create HTTP request %s %s: %v",
args.req.Method, args.req.URL(), res.err)
return
}
req.Header.Set(apc.HdrCallerID, h.si.ID())
req.Header.Set(apc.HdrCallerName, h.si.Name())
if smap := h.owner.smap.get(); smap != nil && smap.vstr != "" {
req.Header.Set(apc.HdrCallerSmapVersion, smap.vstr)
}
req.Header.Set(cos.HdrUserAgent, ua)
resp, res.err = client.Do(req)
if res.err != nil {
res.details = fmt.Sprintf("Failed to call %s (%s %s): %v", sid, args.req.Method, args.req.URL(), res.err)
return
}
defer resp.Body.Close()
res.status = resp.StatusCode
res.header = resp.Header
// err == nil && bad status: resp.Body contains the error message
if res.status >= http.StatusBadRequest {
if args.req.Method == http.MethodHead {
msg := resp.Header.Get(apc.HdrError)
res.err = cmn.S2HTTPErr(req, msg, res.status)
} else {
b := cmn.NewBuffer()
b.ReadFrom(resp.Body)
res.err = cmn.S2HTTPErr(req, b.String(), res.status)
cmn.FreeBuffer(b)
}
res.details = res.err.Error()
return
}
// read and decode via call result value (`cresv`), if provided
// othwerwise, read and return bytes for the caller to unmarshal
if args.cresv != nil {
res.v = args.cresv.newV()
args.cresv.read(res, resp.Body)
if res.err != nil {
return
}
} else {
res.read(resp.Body)
if res.err != nil {
return
}
}
if sid != unknownDaemonID {
h.keepalive.heardFrom(sid, false /* reset */)
}
return
}
//
// intra-cluster IPC, control plane: notify another node
//
func (h *htrun) notifyTerm(n cluster.Notif, err error) { h._nfy(n, err, apc.Finished) }
func (h *htrun) notifyProgress(n cluster.Notif) { h._nfy(n, nil, apc.Progress) }
func (h *htrun) _nfy(n cluster.Notif, err error, upon string) {
var (
smap = h.owner.smap.get()
dsts = n.Subscribers()
msg = n.ToNotifMsg()
args = allocBcArgs()
nodes = args.selected
)
debug.Assert(upon == apc.Progress || upon == apc.Finished)
if len(dsts) == 1 && dsts[0] == equalIC {
for pid, psi := range smap.Pmap {
if smap.IsIC(psi) && pid != h.si.ID() && !psi.InMaintOrDecomm() {
nodes = append(nodes, psi)
}
}
} else {
for _, dst := range dsts {
debug.Assert(dst != equalIC)
if si := smap.GetActiveNode(dst); si != nil {
nodes = append(nodes, si)
} else {
glog.Error(&errNodeNotFound{"failed to notify", dst, h.si, smap})
}
}
}
if err != nil {
msg.ErrMsg = err.Error()
}
msg.NodeID = h.si.ID()
if len(nodes) == 0 {
glog.Errorf("%s: have no nodes to send notification %s", h.si, &msg)
return
}
path := apc.URLPathNotifs.Join(upon)
args.req = cmn.HreqArgs{Method: http.MethodPost, Path: path, Body: cos.MustMarshal(&msg)}
args.network = cmn.NetIntraControl
args.timeout = cmn.Timeout.MaxKeepalive()
args.selected = nodes
args.nodeCount = len(nodes)
args.async = true
_ = h.bcastSelected(args)
freeBcArgs(args)
}
///////////////
// broadcast //
///////////////
// bcastGroup broadcasts a message to a specific group of nodes: targets, proxies, all.
func (h *htrun) bcastGroup(args *bcastArgs) sliceResults {
if args.smap == nil {
args.smap = h.owner.smap.get()
}
present := args.smap.isPresent(h.si)
if args.network == "" {
args.network = cmn.NetIntraControl
}
debug.Assert(cmn.NetworkIsKnown(args.network))
if args.timeout == 0 {
args.timeout = cmn.Timeout.CplaneOperation()
debug.Assert(args.timeout != 0)
}
switch args.to {
case cluster.Targets:
args.nodes = []meta.NodeMap{args.smap.Tmap}
args.nodeCount = len(args.smap.Tmap)
if present && h.si.IsTarget() {
args.nodeCount--
}
case cluster.Proxies:
args.nodes = []meta.NodeMap{args.smap.Pmap}
args.nodeCount = len(args.smap.Pmap)
if present && h.si.IsProxy() {
args.nodeCount--
}
case cluster.AllNodes:
args.nodes = []meta.NodeMap{args.smap.Pmap, args.smap.Tmap}
args.nodeCount = len(args.smap.Pmap) + len(args.smap.Tmap)
if present {
args.nodeCount--
}
default:
debug.Assert(false)
}
return h.bcastNodes(args)
}
// broadcast to the specified destinations (`bargs.nodes`)
// (if specified, `bargs.req.BodyR` must implement `cos.ReadOpenCloser`)
func (h *htrun) bcastNodes(bargs *bcastArgs) sliceResults {
var (
results bcastResults
wg = cos.NewLimitedWaitGroup(meta.MaxBcastParallel(), bargs.nodeCount)
f = func(si *meta.Snode) { h._call(si, bargs, &results); wg.Done() }
)
debug.Assert(len(bargs.selected) == 0)
if !bargs.async {
results.s = allocBcastRes(len(bargs.nodes))
}
for _, nodeMap := range bargs.nodes {
for _, si := range nodeMap {
if si.ID() == h.si.ID() {
continue
}
if !bargs.ignoreMaintenance && si.InMaintOrDecomm() {
continue
}
wg.Add(1)
go f(si)
}
}
wg.Wait()
return results.s
}
func (h *htrun) bcastSelected(bargs *bcastArgs) sliceResults {
var (
results bcastResults
wg = cos.NewLimitedWaitGroup(meta.MaxBcastParallel(), bargs.nodeCount)
f = func(si *meta.Snode) { h._call(si, bargs, &results); wg.Done() }
)
debug.Assert(len(bargs.selected) > 0)
if !bargs.async {
results.s = allocBcastRes(len(bargs.selected))
}
for _, si := range bargs.selected {
debug.Assert(si.ID() != h.si.ID())
wg.Add(1)
go f(si)
}
wg.Wait()
return results.s
}
func (h *htrun) bcastAsyncIC(msg *aisMsg) {
var (
wg = &sync.WaitGroup{}
smap = h.owner.smap.get()
args = allocBcArgs()
)
args.req = cmn.HreqArgs{Method: http.MethodPost, Path: apc.URLPathIC.S, Body: cos.MustMarshal(msg)}
args.network = cmn.NetIntraControl
args.timeout = cmn.Timeout.MaxKeepalive()
for pid, psi := range smap.Pmap {
if pid == h.si.ID() || !smap.IsIC(psi) || smap.GetActiveNode(pid) == nil {
continue
}
wg.Add(1)
go func(si *meta.Snode) {
cargs := allocCargs()
{
cargs.si = si
cargs.req = args.req
cargs.timeout = args.timeout
}
res := h.call(cargs)
freeCargs(cargs)
freeCR(res) // discard right away
wg.Done()
}(psi)
}
wg.Wait()
freeBcArgs(args)
}
func (h *htrun) bcastReqGroup(w http.ResponseWriter, r *http.Request, args *bcastArgs, to int) {
args.to = to
results := h.bcastGroup(args)
for _, res := range results {
if res.err != nil {
h.writeErr(w, r, res.toErr())
break
}
}
freeBcastRes(results)
}
//////////////////////////////////
// HTTP request parsing helpers //
//////////////////////////////////
// remove validated fields and return the resulting slice
func (h *htrun) apiItems(w http.ResponseWriter, r *http.Request, itemsAfter int,
splitAfter bool, items []string) ([]string, error) {
items, err := cmn.MatchItems(r.URL.Path, itemsAfter, splitAfter, items)
if err != nil {
h.writeErr(w, r, err)
return nil, err
}
return items, nil
}
func (h *htrun) writeMsgPack(w http.ResponseWriter, v msgp.Encodable, tag string) (ok bool) {
var (
err error
buf, slab = h.gmm.AllocSize(cmn.MsgpLsoBufSize) // max size
mw = msgp.NewWriterBuf(w, buf)
)
w.Header().Set(cos.HdrContentType, cos.ContentMsgPack)
if err = v.EncodeMsg(mw); err == nil {
err = mw.Flush()
}
slab.Free(buf)
if err == nil {
return true
}
h.logerr(tag, v, err)
return false
}
func (h *htrun) writeJSON(w http.ResponseWriter, r *http.Request, v any, tag string) {
if err := _writejs(w, r, v); err != nil {
h.logerr(tag, v, err)
}
}
// same as above with boolean return to facilitate early termination
func (h *htrun) writeJS(w http.ResponseWriter, r *http.Request, v any, tag string) bool {
if err := _writejs(w, r, v); err != nil {
h.logerr(tag, v, err)
return false
}
return true
}
func _writejs(w http.ResponseWriter, r *http.Request, v any) (err error) {
w.Header().Set(cos.HdrContentType, cos.ContentJSONCharsetUTF)
if isBrowser(r.Header.Get(cos.HdrUserAgent)) {
var out []byte
if out, err = jsoniter.MarshalIndent(v, "", " "); err == nil {
w.Header().Set(cos.HdrContentLength, strconv.Itoa(len(out)))
_, err = w.Write(out)
}
} else { // previously: new-encoder(w).encode(v) (non-browser client)
j := cos.JSON.BorrowStream(nil)
j.WriteVal(v)
j.WriteRaw("\n")
if err = j.Error; err == nil {
b := j.Buffer()
w.Header().Set(cos.HdrContentLength, strconv.Itoa(len(b)))
_, err = w.Write(b)
// NOTE: consider http.NewResponseController(w).Flush()
}
cos.JSON.ReturnStream(j)
}
return
}
// See https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/User-Agent
// and https://developer.mozilla.org/en-US/docs/Web/HTTP/Browser_detection_using_the_user_agent
func isBrowser(userAgent string) bool {
return strings.HasPrefix(userAgent, "Mozilla/5.0")
}
func (h *htrun) logerr(tag string, v any, err error) {
const maxl = 32
if daemon.stopping.Load() {
return
}
var s string
if v != nil {
s = fmt.Sprintf("[%+v", v)
if len(s) > maxl {
s = s[:maxl] + "...]"
} else {
s += "]"
}
}
msg := fmt.Sprintf("%s: failed to write bytes%s: %v (", s, tag, err)
for i := 1; i < 4; i++ {
_, file, line, ok := runtime.Caller(i)
if !ok {
break
}
if i > 1 {
msg += " <- "
}
f := filepath.Base(file)
msg += fmt.Sprintf("%s:%d", f, line)
}
glog.Errorln(msg + ")")
h.statsT.IncErr(stats.ErrHTTPWriteCount)
}