-
Notifications
You must be signed in to change notification settings - Fork 149
/
XrdClXRootDMsgHandler.cc
2514 lines (2194 loc) · 93.5 KB
/
XrdClXRootDMsgHandler.cc
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 (c) 2011-2014 by European Organization for Nuclear Research (CERN)
// Author: Lukasz Janyst <ljanyst@cern.ch>
//------------------------------------------------------------------------------
// This file is part of the XRootD software suite.
//
// XRootD is free software: you can redistribute it and/or modify
// it under the terms of the GNU Lesser General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// XRootD is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public License
// along with XRootD. If not, see <http://www.gnu.org/licenses/>.
//
// In applying this licence, CERN does not waive the privileges and immunities
// granted to it by virtue of its status as an Intergovernmental Organization
// or submit itself to any jurisdiction.
//------------------------------------------------------------------------------
#include "XrdCl/XrdClXRootDMsgHandler.hh"
#include "XrdCl/XrdClLog.hh"
#include "XrdCl/XrdClDefaultEnv.hh"
#include "XrdCl/XrdClConstants.hh"
#include "XrdCl/XrdClXRootDTransport.hh"
#include "XrdCl/XrdClMessage.hh"
#include "XrdCl/XrdClURL.hh"
#include "XrdCl/XrdClUtils.hh"
#include "XrdCl/XrdClTaskManager.hh"
#include "XrdCl/XrdClJobManager.hh"
#include "XrdCl/XrdClSIDManager.hh"
#include "XrdCl/XrdClMessageUtils.hh"
#include "XrdCl/XrdClLocalFileHandler.hh"
#include "XrdCl/XrdClRedirectorRegistry.hh"
#include "XrdCl/XrdClSocket.hh"
#include "XrdCl/XrdClTls.hh"
#include "XrdOuc/XrdOucCRC.hh"
#include "XrdSys/XrdSysPlatform.hh" // same as above
#include "XrdSys/XrdSysAtomics.hh"
#include "XrdSys/XrdSysPthread.hh"
#include <memory>
#include <sstream>
#include <numeric>
namespace
{
//----------------------------------------------------------------------------
// We need an extra task what will run the handler in the future, because
// tasks get deleted and we need the handler
//----------------------------------------------------------------------------
class WaitTask: public XrdCl::Task
{
public:
WaitTask( XrdCl::XRootDMsgHandler *handler ): pHandler( handler )
{
std::ostringstream o;
o << "WaitTask for: 0x" << handler->GetRequest();
SetName( o.str() );
}
virtual time_t Run( time_t now )
{
pHandler->WaitDone( now );
return 0;
}
private:
XrdCl::XRootDMsgHandler *pHandler;
};
}
namespace XrdCl
{
//----------------------------------------------------------------------------
// Delegate the response handling to the thread-pool
//----------------------------------------------------------------------------
class HandleRspJob: public XrdCl::Job
{
public:
HandleRspJob( XrdCl::XRootDMsgHandler *handler ): pHandler( handler )
{
}
virtual ~HandleRspJob()
{
}
virtual void Run( void *arg )
{
pHandler->HandleResponse();
delete this;
}
private:
XrdCl::XRootDMsgHandler *pHandler;
};
//----------------------------------------------------------------------------
// Examine an incoming message, and decide on the action to be taken
//----------------------------------------------------------------------------
uint16_t XRootDMsgHandler::Examine( std::shared_ptr<Message> &msg )
{
//--------------------------------------------------------------------------
// if the MsgHandler is already being used to process another request
// (kXR_oksofar) we need to wait
//--------------------------------------------------------------------------
if( pOksofarAsAnswer )
{
XrdSysCondVarHelper lck( pCV );
while( pResponse ) pCV.Wait();
}
else
{
if( pResponse )
{
Log *log = DefaultEnv::GetLog();
log->Warning( ExDbgMsg, "[%s] MsgHandler is examining a response although "
"it already owns a response: 0x%x (message: %s ).",
pUrl.GetHostId().c_str(), this,
pRequest->GetDescription().c_str() );
}
}
if( msg->GetSize() < 8 )
return Ignore;
ServerResponse *rsp = (ServerResponse *)msg->GetBuffer();
ClientRequest *req = (ClientRequest *)pRequest->GetBuffer();
uint16_t status = 0;
uint32_t dlen = 0;
//--------------------------------------------------------------------------
// We only care about async responses, but those are extracted now
// in the SocketHandler.
//--------------------------------------------------------------------------
if( rsp->hdr.status == kXR_attn )
{
return Ignore;
}
//--------------------------------------------------------------------------
// We got a sync message - check if it belongs to us
//--------------------------------------------------------------------------
else
{
if( rsp->hdr.streamid[0] != req->header.streamid[0] ||
rsp->hdr.streamid[1] != req->header.streamid[1] )
return Ignore;
status = rsp->hdr.status;
dlen = rsp->hdr.dlen;
}
//--------------------------------------------------------------------------
// We take the ownership of the message and decide what we will do
// with the handler itself, the options are:
// 1) we want to either read in raw mode (the Raw flag) or have the message
// body reconstructed for us by the TransportHandler by the time
// Process() is called (default, no extra flag)
// 2) we either got a full response in which case we don't want to be
// notified about anything anymore (RemoveHandler) or we got a partial
// answer and we need to wait for more (default, no extra flag)
//--------------------------------------------------------------------------
pResponse = msg;
pBodyReader->SetDataLength( dlen );
Log *log = DefaultEnv::GetLog();
switch( status )
{
//------------------------------------------------------------------------
// Handle the cached cases
//------------------------------------------------------------------------
case kXR_error:
case kXR_redirect:
case kXR_wait:
return RemoveHandler;
case kXR_waitresp:
{
log->Dump( XRootDMsg, "[%s] Got kXR_waitresp response to "
"message %s", pUrl.GetHostId().c_str(),
pRequest->GetDescription().c_str() );
pResponse.reset();
return Ignore; // This must be handled synchronously!
}
//------------------------------------------------------------------------
// Handle the potential raw cases
//------------------------------------------------------------------------
case kXR_ok:
{
//----------------------------------------------------------------------
// For kXR_read we read in raw mode
//----------------------------------------------------------------------
uint16_t reqId = ntohs( req->header.requestid );
if( reqId == kXR_read )
{
return Raw | RemoveHandler;
}
//----------------------------------------------------------------------
// kXR_readv is the same as kXR_read
//----------------------------------------------------------------------
if( reqId == kXR_readv )
{
return Raw | RemoveHandler;
}
//----------------------------------------------------------------------
// For everything else we just take what we got
//----------------------------------------------------------------------
return RemoveHandler;
}
//------------------------------------------------------------------------
// kXR_oksofars are special, they are not full responses, so we reset
// the response pointer to 0 and add the message to the partial list
//------------------------------------------------------------------------
case kXR_oksofar:
{
log->Dump( XRootDMsg, "[%s] Got a kXR_oksofar response to request "
"%s", pUrl.GetHostId().c_str(),
pRequest->GetDescription().c_str() );
if( !pOksofarAsAnswer )
{
pPartialResps.emplace_back( std::move( pResponse ) );
}
//----------------------------------------------------------------------
// For kXR_read we either read in raw mode if the message has not
// been fully reconstructed already, if it has, we adjust
// the buffer offset to prepare for the next one
//----------------------------------------------------------------------
uint16_t reqId = ntohs( req->header.requestid );
if( reqId == kXR_read )
{
pTimeoutFence.store( true, std::memory_order_relaxed );
return Raw | ( pOksofarAsAnswer ? None : NoProcess );
}
//----------------------------------------------------------------------
// kXR_readv is similar to read, except that the payload is different
//----------------------------------------------------------------------
if( reqId == kXR_readv )
{
pTimeoutFence.store( true, std::memory_order_relaxed );
return Raw | ( pOksofarAsAnswer ? None : NoProcess );
}
return ( pOksofarAsAnswer ? None : NoProcess );
}
case kXR_status:
{
log->Dump( XRootDMsg, "[%s] Got a kXR_status response to request "
"%s", pUrl.GetHostId().c_str(),
pRequest->GetDescription().c_str() );
uint16_t reqId = ntohs( req->header.requestid );
if( reqId == kXR_pgwrite )
{
//--------------------------------------------------------------------
// In case of pgwrite by definition this wont be a partial response
// so we can already remove the handler from the in-queue
//--------------------------------------------------------------------
return RemoveHandler;
}
//----------------------------------------------------------------------
// Otherwise (pgread), first of all we need to read the body of the
// kXR_status response, we can handle the raw data (if any) only after
// we have the whole kXR_status body
//----------------------------------------------------------------------
pTimeoutFence.store( true, std::memory_order_relaxed );
return None;
}
//------------------------------------------------------------------------
// Default
//------------------------------------------------------------------------
default:
return RemoveHandler;
}
return RemoveHandler;
}
//----------------------------------------------------------------------------
// Reexamine the incoming message, and decide on the action to be taken
//----------------------------------------------------------------------------
uint16_t XRootDMsgHandler::InspectStatusRsp()
{
if( !pResponse )
return 0;
Log *log = DefaultEnv::GetLog();
ServerResponse *rsp = (ServerResponse *)pResponse->GetBuffer();
//--------------------------------------------------------------------------
// Additional action is only required for kXR_status
//--------------------------------------------------------------------------
if( rsp->hdr.status != kXR_status ) return 0;
//--------------------------------------------------------------------------
// Ignore malformed status response
//--------------------------------------------------------------------------
if( pResponse->GetSize() < sizeof( ServerResponseStatus ) )
return Ignore;
ClientRequest *req = (ClientRequest *)pRequest->GetBuffer();
uint16_t reqId = ntohs( req->header.requestid );
//--------------------------------------------------------------------------
// Unmarshal the status body
//--------------------------------------------------------------------------
if( !pRspStatusBodyUnMarshaled )
{
XRootDStatus st = XRootDTransport::UnMarshalStatusBody( *pResponse, reqId );
if( !st.IsOK() && st.code == errDataError )
{
log->Error( XRootDMsg, "[%s] %s", pUrl.GetHostId().c_str(),
st.GetErrorMessage().c_str() );
return Corrupted;
}
if( !st.IsOK() )
{
log->Error( XRootDMsg, "[%s] Failed to unmarshall status body.",
pUrl.GetHostId().c_str() );
pStatus = st;
HandleRspOrQueue();
return Ignore;
}
pRspStatusBodyUnMarshaled = true;
}
//--------------------------------------------------------------------------
// Common handling for partial results
//--------------------------------------------------------------------------
ServerResponseV2 *rspst = (ServerResponseV2*)pResponse->GetBuffer();
if( rspst->status.bdy.resptype == XrdProto::kXR_PartialResult )
{
pPartialResps.push_back( std::move( pResponse ) );
}
//--------------------------------------------------------------------------
// Decide the actions that we need to take
//--------------------------------------------------------------------------
uint16_t action = 0;
if( reqId == kXR_pgread )
{
//----------------------------------------------------------------------
// The message contains only Status header and body but no raw data
//----------------------------------------------------------------------
if( !pPageReader )
pPageReader.reset( new AsyncPageReader( *pChunkList, pCrc32cDigests ) );
pPageReader->SetRsp( rspst );
action |= Raw;
if( rspst->status.bdy.resptype == XrdProto::kXR_PartialResult )
action |= NoProcess;
else
action |= RemoveHandler;
}
else if( reqId == kXR_pgwrite )
{
// if data corruption has been detected on the server side we will
// send some additional data pointing to the pages that need to be
// retransmitted
if( size_t( sizeof( ServerResponseHeader ) + rspst->status.hdr.dlen + rspst->status.bdy.dlen ) >
pResponse->GetCursor() )
action |= More;
// if we already have this data we need to unmarshal it
else if( !pRspPgWrtRetrnsmReqUnMarshalled )
{
XRootDStatus st = XRootDTransport::UnMarchalStatusCSE( *pResponse );
if( !st.IsOK() && st.code == errDataError )
{
log->Error( XRootDMsg, "[%s] %s", pUrl.GetHostId().c_str(),
st.GetErrorMessage().c_str() );
return Corrupted;
}
if( !st.IsOK() )
{
log->Error( XRootDMsg, "[%s] Failed to unmarshall status body.",
pUrl.GetHostId().c_str() );
pStatus = st;
HandleRspOrQueue();
return Ignore;
}
pRspPgWrtRetrnsmReqUnMarshalled = true;
}
}
return action;
}
//----------------------------------------------------------------------------
// Get handler sid
//----------------------------------------------------------------------------
uint16_t XRootDMsgHandler::GetSid() const
{
ClientRequest* req = (ClientRequest*) pRequest->GetBuffer();
return ((uint16_t)req->header.streamid[1] << 8) | (uint16_t)req->header.streamid[0];
}
//----------------------------------------------------------------------------
//! Process the message if it was "taken" by the examine action
//----------------------------------------------------------------------------
void XRootDMsgHandler::Process()
{
Log *log = DefaultEnv::GetLog();
ServerResponse *rsp = (ServerResponse *)pResponse->GetBuffer();
ClientRequest *req = (ClientRequest *)pRequest->GetBuffer();
//--------------------------------------------------------------------------
// If it is a local file, it can be only a metalink redirector
//--------------------------------------------------------------------------
if( pUrl.IsLocalFile() && pUrl.IsMetalink() )
pHosts->back().protocol = kXR_PROTOCOLVERSION;
//--------------------------------------------------------------------------
// We got an answer, check who we were talking to
//--------------------------------------------------------------------------
else
{
AnyObject qryResult;
int *qryResponse = 0;
pPostMaster->QueryTransport( pUrl, XRootDQuery::ServerFlags, qryResult );
qryResult.Get( qryResponse );
pHosts->back().flags = *qryResponse; delete qryResponse; qryResponse = 0;
pPostMaster->QueryTransport( pUrl, XRootDQuery::ProtocolVersion, qryResult );
qryResult.Get( qryResponse );
pHosts->back().protocol = *qryResponse; delete qryResponse;
}
//--------------------------------------------------------------------------
// Process the message
//--------------------------------------------------------------------------
Status st = XRootDTransport::UnMarshallBody( pResponse.get(), req->header.requestid );
if( !st.IsOK() )
{
pStatus = Status( stFatal, errInvalidMessage );
HandleResponse();
return;
}
//--------------------------------------------------------------------------
// we have an response for the message so it's not in fly anymore
//--------------------------------------------------------------------------
pMsgInFly = false;
//--------------------------------------------------------------------------
// Reset the aggregated wait (used to omit wait response in case of Metalink
// redirector)
//--------------------------------------------------------------------------
if( rsp->hdr.status != kXR_wait )
pAggregatedWaitTime = 0;
switch( rsp->hdr.status )
{
//------------------------------------------------------------------------
// kXR_ok - we're done here
//------------------------------------------------------------------------
case kXR_ok:
{
log->Dump( XRootDMsg, "[%s] Got a kXR_ok response to request %s",
pUrl.GetHostId().c_str(),
pRequest->GetDescription().c_str() );
pStatus = Status();
HandleResponse();
return;
}
case kXR_status:
{
log->Dump( XRootDMsg, "[%s] Got a kXR_status response to request %s",
pUrl.GetHostId().c_str(),
pRequest->GetDescription().c_str() );
pStatus = Status();
HandleResponse();
return;
}
//------------------------------------------------------------------------
// kXR_ok - we're serving partial result to the user
//------------------------------------------------------------------------
case kXR_oksofar:
{
log->Dump( XRootDMsg, "[%s] Got a kXR_oksofar response to request %s",
pUrl.GetHostId().c_str(),
pRequest->GetDescription().c_str() );
pStatus = Status( stOK, suContinue );
HandleResponse();
return;
}
//------------------------------------------------------------------------
// kXR_error - we've got a problem
//------------------------------------------------------------------------
case kXR_error:
{
char *errmsg = new char[rsp->hdr.dlen-3]; errmsg[rsp->hdr.dlen-4] = 0;
memcpy( errmsg, rsp->body.error.errmsg, rsp->hdr.dlen-4 );
log->Dump( XRootDMsg, "[%s] Got a kXR_error response to request %s "
"[%d] %s", pUrl.GetHostId().c_str(),
pRequest->GetDescription().c_str(), rsp->body.error.errnum,
errmsg );
delete [] errmsg;
HandleError( Status(stError, errErrorResponse, rsp->body.error.errnum) );
return;
}
//------------------------------------------------------------------------
// kXR_redirect - they tell us to go elsewhere
//------------------------------------------------------------------------
case kXR_redirect:
{
if( rsp->hdr.dlen <= 4 )
{
log->Error( XRootDMsg, "[%s] Got invalid redirect response.",
pUrl.GetHostId().c_str() );
pStatus = Status( stError, errInvalidResponse );
HandleResponse();
return;
}
char *urlInfoBuff = new char[rsp->hdr.dlen-3];
urlInfoBuff[rsp->hdr.dlen-4] = 0;
memcpy( urlInfoBuff, rsp->body.redirect.host, rsp->hdr.dlen-4 );
std::string urlInfo = urlInfoBuff;
delete [] urlInfoBuff;
log->Dump( XRootDMsg, "[%s] Got kXR_redirect response to "
"message %s: %s, port %d", pUrl.GetHostId().c_str(),
pRequest->GetDescription().c_str(), urlInfo.c_str(),
rsp->body.redirect.port );
//----------------------------------------------------------------------
// Check if we can proceed
//----------------------------------------------------------------------
if( !pRedirectCounter )
{
log->Warning( XRootDMsg, "[%s] Redirect limit has been reached for "
"message %s, the last known error is: %s",
pUrl.GetHostId().c_str(),
pRequest->GetDescription().c_str(),
pLastError.ToString().c_str() );
pStatus = Status( stFatal, errRedirectLimit );
HandleResponse();
return;
}
--pRedirectCounter;
//----------------------------------------------------------------------
// Keep the info about this server if we still need to find a load
// balancer
//----------------------------------------------------------------------
uint32_t flags = pHosts->back().flags;
if( !pHasLoadBalancer )
{
if( flags & kXR_isManager )
{
//------------------------------------------------------------------
// If the current server is a meta manager then it supersedes
// any existing load balancer, otherwise we assign a load-balancer
// only if it has not been already assigned
//------------------------------------------------------------------
if( ( flags & kXR_attrMeta ) || !pLoadBalancer.url.IsValid() )
{
pLoadBalancer = pHosts->back();
log->Dump( XRootDMsg, "[%s] Current server has been assigned "
"as a load-balancer for message %s",
pUrl.GetHostId().c_str(),
pRequest->GetDescription().c_str() );
HostList::iterator it;
for( it = pHosts->begin(); it != pHosts->end(); ++it )
it->loadBalancer = false;
pHosts->back().loadBalancer = true;
}
}
}
//----------------------------------------------------------------------
// If the redirect comes from a data server safe the URL because
// in case of a failure we will use it as the effective data server URL
// for the tried CGI opaque info
//----------------------------------------------------------------------
if( flags & kXR_isServer )
pEffectiveDataServerUrl = new URL( pHosts->back().url );
//----------------------------------------------------------------------
// Build the URL and check it's validity
//----------------------------------------------------------------------
std::vector<std::string> urlComponents;
std::string newCgi;
Utils::splitString( urlComponents, urlInfo, "?" );
std::ostringstream o;
o << urlComponents[0];
if( rsp->body.redirect.port > 0 )
o << ":" << rsp->body.redirect.port << "/";
else if( rsp->body.redirect.port < 0 )
{
//--------------------------------------------------------------------
// check if the manager wants to enforce write recovery at himself
// (beware we are dealing here with negative flags)
//--------------------------------------------------------------------
if( ~uint32_t( rsp->body.redirect.port ) & kXR_recoverWrts )
pHosts->back().flags |= kXR_recoverWrts;
//--------------------------------------------------------------------
// check if the manager wants to collapse the communication channel
// (the redirect host is to replace the current host)
//--------------------------------------------------------------------
if( ~uint32_t( rsp->body.redirect.port ) & kXR_collapseRedir )
{
std::string url( rsp->body.redirect.host, rsp->hdr.dlen-4 );
pPostMaster->CollapseRedirect( pUrl, url );
}
if( ~uint32_t( rsp->body.redirect.port ) & kXR_ecRedir )
{
std::string url( rsp->body.redirect.host, rsp->hdr.dlen-4 );
if( Utils::CheckEC( pRequest, url ) )
pRedirectAsAnswer = true;
}
}
URL newUrl = URL( o.str() );
if( !newUrl.IsValid() )
{
pStatus = Status( stError, errInvalidRedirectURL );
log->Error( XRootDMsg, "[%s] Got invalid redirection URL: %s",
pUrl.GetHostId().c_str(), urlInfo.c_str() );
HandleResponse();
return;
}
if( pUrl.GetUserName() != "" && newUrl.GetUserName() == "" )
newUrl.SetUserName( pUrl.GetUserName() );
if( pUrl.GetPassword() != "" && newUrl.GetPassword() == "" )
newUrl.SetPassword( pUrl.GetPassword() );
//----------------------------------------------------------------------
// Forward any "xrd.*" params from the original client request also to
// the new redirection url
// Also, we need to preserve any "xrdcl.*' as they are important for
// our internal workflows.
//----------------------------------------------------------------------
std::ostringstream ossXrd;
const URL::ParamsMap &urlParams = pUrl.GetParams();
for(URL::ParamsMap::const_iterator it = urlParams.begin();
it != urlParams.end(); ++it )
{
if( it->first.compare( 0, 4, "xrd." ) &&
it->first.compare( 0, 6, "xrdcl." ) )
continue;
ossXrd << it->first << '=' << it->second << '&';
}
std::string xrdCgi = ossXrd.str();
pRedirectUrl = newUrl.GetURL();
URL cgiURL;
if( urlComponents.size() > 1 )
{
pRedirectUrl += "?";
pRedirectUrl += urlComponents[1];
std::ostringstream o;
o << "fake://fake:111//fake?";
o << urlComponents[1];
if( urlComponents.size() == 3 )
o << '?' << urlComponents[2];
if (!xrdCgi.empty())
{
o << '&' << xrdCgi;
pRedirectUrl += '&';
pRedirectUrl += xrdCgi;
}
cgiURL = URL( o.str() );
}
else {
if (!xrdCgi.empty())
{
std::ostringstream o;
o << "fake://fake:111//fake?";
o << xrdCgi;
cgiURL = URL( o.str() );
pRedirectUrl += '?';
pRedirectUrl += xrdCgi;
}
}
//----------------------------------------------------------------------
// Check if we need to return the URL as a response
//----------------------------------------------------------------------
if( newUrl.GetProtocol() != "root" && newUrl.GetProtocol() != "xroot" &&
newUrl.GetProtocol() != "roots" && newUrl.GetProtocol() != "xroots" &&
!newUrl.IsLocalFile() )
pRedirectAsAnswer = true;
if( pRedirectAsAnswer )
{
pStatus = Status( stError, errRedirect );
HandleResponse();
return;
}
//----------------------------------------------------------------------
// Rewrite the message in a way required to send it to another server
//----------------------------------------------------------------------
newUrl.SetParams( cgiURL.GetParams() );
Status st = RewriteRequestRedirect( newUrl );
if( !st.IsOK() )
{
pStatus = st;
HandleResponse();
return;
}
//----------------------------------------------------------------------
// Make sure we don't change the protocol by accident (root vs roots)
//----------------------------------------------------------------------
if( ( pUrl.GetProtocol() == "roots" || pUrl.GetProtocol() == "xroots" ) &&
( newUrl.GetProtocol() == "root" || newUrl.GetProtocol() == "xroot" ) )
newUrl.SetProtocol( "roots" );
//----------------------------------------------------------------------
// Send the request to the new location
//----------------------------------------------------------------------
HandleError( RetryAtServer( newUrl, RedirectEntry::EntryRedirect ) );
return;
}
//------------------------------------------------------------------------
// kXR_wait - we wait, and re-issue the request later
//------------------------------------------------------------------------
case kXR_wait:
{
uint32_t waitSeconds = 0;
if( rsp->hdr.dlen >= 4 )
{
char *infoMsg = new char[rsp->hdr.dlen-3];
infoMsg[rsp->hdr.dlen-4] = 0;
memcpy( infoMsg, rsp->body.wait.infomsg, rsp->hdr.dlen-4 );
log->Dump( XRootDMsg, "[%s] Got kXR_wait response of %d seconds to "
"message %s: %s", pUrl.GetHostId().c_str(),
rsp->body.wait.seconds, pRequest->GetDescription().c_str(),
infoMsg );
delete [] infoMsg;
waitSeconds = rsp->body.wait.seconds;
}
else
{
log->Dump( XRootDMsg, "[%s] Got kXR_wait response of 0 seconds to "
"message %s", pUrl.GetHostId().c_str(),
pRequest->GetDescription().c_str() );
}
pAggregatedWaitTime += waitSeconds;
// We need a special case if the data node comes from metalink
// redirector. In this case it might make more sense to try the
// next entry in the Metalink than wait.
if( OmitWait( *pRequest, pLoadBalancer.url ) )
{
int maxWait = DefaultMaxMetalinkWait;
DefaultEnv::GetEnv()->GetInt( "MaxMetalinkWait", maxWait );
if( pAggregatedWaitTime > maxWait )
{
UpdateTriedCGI();
HandleError( RetryAtServer( pLoadBalancer.url, RedirectEntry::EntryRedirectOnWait ) );
return;
}
}
//----------------------------------------------------------------------
// Some messages require rewriting before they can be sent again
// after wait
//----------------------------------------------------------------------
Status st = RewriteRequestWait();
if( !st.IsOK() )
{
pStatus = st;
HandleResponse();
return;
}
//----------------------------------------------------------------------
// Register a task to resend the message in some seconds, if we still
// have time to do that, and report a timeout otherwise
//----------------------------------------------------------------------
time_t resendTime = ::time(0)+waitSeconds;
if( resendTime < pExpiration )
{
log->Debug( ExDbgMsg, "[%s] Scheduling WaitTask for MsgHandler: 0x%x (message: %s ).",
pUrl.GetHostId().c_str(), this,
pRequest->GetDescription().c_str() );
TaskManager *taskMgr = pPostMaster->GetTaskManager();
taskMgr->RegisterTask( new WaitTask( this ), resendTime );
}
else
{
log->Debug( XRootDMsg, "[%s] Wait time is too long, timing out %s",
pUrl.GetHostId().c_str(),
pRequest->GetDescription().c_str() );
HandleError( Status( stError, errOperationExpired) );
}
return;
}
//------------------------------------------------------------------------
// kXR_waitresp - the response will be returned in some seconds as an
// unsolicited message. Currently all messages of this type are handled
// one step before in the XrdClStream::OnIncoming as they need to be
// processed synchronously.
//------------------------------------------------------------------------
case kXR_waitresp:
{
if( rsp->hdr.dlen < 4 )
{
log->Error( XRootDMsg, "[%s] Got invalid waitresp response.",
pUrl.GetHostId().c_str() );
pStatus = Status( stError, errInvalidResponse );
HandleResponse();
return;
}
log->Dump( XRootDMsg, "[%s] Got kXR_waitresp response of %d seconds to "
"message %s", pUrl.GetHostId().c_str(),
rsp->body.waitresp.seconds,
pRequest->GetDescription().c_str() );
return;
}
//------------------------------------------------------------------------
// Default - unrecognized/unsupported response, declare an error
//------------------------------------------------------------------------
default:
{
log->Dump( XRootDMsg, "[%s] Got unrecognized response %d to "
"message %s", pUrl.GetHostId().c_str(),
rsp->hdr.status, pRequest->GetDescription().c_str() );
pStatus = Status( stError, errInvalidResponse );
HandleResponse();
return;
}
}
return;
}
//----------------------------------------------------------------------------
// Handle an event other that a message arrival - may be timeout
//----------------------------------------------------------------------------
uint8_t XRootDMsgHandler::OnStreamEvent( StreamEvent event,
XRootDStatus status )
{
Log *log = DefaultEnv::GetLog();
log->Dump( XRootDMsg, "[%s] Stream event reported for msg %s",
pUrl.GetHostId().c_str(), pRequest->GetDescription().c_str() );
if( event == Ready )
return 0;
if( pTimeoutFence.load( std::memory_order_relaxed ) )
return 0;
HandleError( status );
return RemoveHandler;
}
//----------------------------------------------------------------------------
// Read message body directly from a socket
//----------------------------------------------------------------------------
XRootDStatus XRootDMsgHandler::ReadMessageBody( Message*,
Socket *socket,
uint32_t &bytesRead )
{
ClientRequest *req = (ClientRequest *)pRequest->GetBuffer();
uint16_t reqId = ntohs( req->header.requestid );
if( reqId == kXR_pgread )
return pPageReader->Read( *socket, bytesRead );
return pBodyReader->Read( *socket, bytesRead );
}
//----------------------------------------------------------------------------
// We're here when we requested sending something over the wire
// and there has been a status update on this action
//----------------------------------------------------------------------------
void XRootDMsgHandler::OnStatusReady( const Message *message,
XRootDStatus status )
{
Log *log = DefaultEnv::GetLog();
//--------------------------------------------------------------------------
// We were successful, so we now need to listen for a response
//--------------------------------------------------------------------------
if( status.IsOK() )
{
log->Dump( XRootDMsg, "[%s] Message %s has been successfully sent.",
pUrl.GetHostId().c_str(), message->GetDescription().c_str() );
log->Debug( ExDbgMsg, "[%s] Moving MsgHandler: 0x%x (message: %s ) from out-queu to in-queue.",
pUrl.GetHostId().c_str(), this,
pRequest->GetDescription().c_str() );
pMsgInFly = true;
return;
}
//--------------------------------------------------------------------------
// We have failed, recover if possible
//--------------------------------------------------------------------------
log->Error( XRootDMsg, "[%s] Impossible to send message %s. Trying to "
"recover.", pUrl.GetHostId().c_str(),
message->GetDescription().c_str() );
HandleError( status );
}
//----------------------------------------------------------------------------
// Are we a raw writer or not?
//----------------------------------------------------------------------------
bool XRootDMsgHandler::IsRaw() const
{
ClientRequest *req = (ClientRequest *)pRequest->GetBuffer();
uint16_t reqId = ntohs( req->header.requestid );
if( reqId == kXR_write || reqId == kXR_writev || reqId == kXR_pgwrite )
return true;
// checkpoint + execute
if( reqId == kXR_chkpoint && req->chkpoint.opcode == kXR_ckpXeq )
{
ClientRequest *xeq = (ClientRequest*)pRequest->GetBuffer( sizeof( ClientRequest ) );
reqId = ntohs( xeq->header.requestid );
return reqId != kXR_truncate; // only checkpointed truncate does not have raw data
}
return false;
}
//----------------------------------------------------------------------------
// Write the message body
//----------------------------------------------------------------------------
XRootDStatus XRootDMsgHandler::WriteMessageBody( Socket *socket,
uint32_t &bytesWritten )
{
//--------------------------------------------------------------------------
// First check if it is a PgWrite
//--------------------------------------------------------------------------
if( !pChunkList->empty() && !pCrc32cDigests.empty() )
{
//------------------------------------------------------------------------
// PgWrite will have just one chunk
//------------------------------------------------------------------------
ChunkInfo chunk = pChunkList->front();
//------------------------------------------------------------------------
// Calculate the size of the first and last page (in case the chunk is not
// 4KB aligned)
//------------------------------------------------------------------------
int fLen = 0, lLen = 0;
size_t nbpgs = XrdOucPgrwUtils::csNum( chunk.offset, chunk.length, fLen, lLen );
//------------------------------------------------------------------------
// Set the crc32c buffer if not ready yet
//------------------------------------------------------------------------
if( pPgWrtCksumBuff.GetCursor() == 0 )
{
uint32_t digest = htonl( pCrc32cDigests[pPgWrtCurrentPageNb] );
memcpy( pPgWrtCksumBuff.GetBuffer(), &digest, sizeof( uint32_t ) );
}
uint32_t btsLeft = chunk.length - pAsyncOffset;
uint32_t pglen = ( pPgWrtCurrentPageNb == 0 ? fLen : XrdSys::PageSize ) - pPgWrtCurrentPageOffset;
if( pglen > btsLeft ) pglen = btsLeft;
char* pgbuf = static_cast<char*>( chunk.buffer ) + pAsyncOffset;