forked from root-project/root
-
Notifications
You must be signed in to change notification settings - Fork 0
/
TXSocket.cxx
2398 lines (2043 loc) · 73.1 KB
/
TXSocket.cxx
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
// @(#)root/proofx:$Id$
// Author: Gerardo Ganis 12/12/2005
/*************************************************************************
* Copyright (C) 1995-2005, Rene Brun and Fons Rademakers. *
* All rights reserved. *
* *
* For the licensing terms see $ROOTSYS/LICENSE. *
* For the list of contributors see $ROOTSYS/README/CREDITS. *
*************************************************************************/
/** \class TXSocket
\ingroup proofx
High level handler of connections to XProofD.
See TSocket for details.
*/
#include "MessageTypes.h"
#include "TEnv.h"
#include "TError.h"
#include "TException.h"
#include "TMonitor.h"
#include "TObjString.h"
#include "TProof.h"
#include "TSlave.h"
#include "TRegexp.h"
#include "TROOT.h"
#include "TUrl.h"
#include "TXHandler.h"
#include "TXSocket.h"
#include "XProofProtocol.h"
#include "XrdProofConn.h"
#include "XrdClient/XrdClientConnMgr.hh"
#include "XrdClient/XrdClientConst.hh"
#include "XrdClient/XrdClientEnv.hh"
#include "XrdClient/XrdClientLogConnection.hh"
#include "XrdClient/XrdClientMessage.hh"
#ifndef WIN32
#include <sys/socket.h>
#else
#include <Winsock2.h>
#endif
#include "XpdSysError.h"
#include "XpdSysLogger.h"
// ---- Tracing utils ----------------------------------------------------------
#include "XrdProofdTrace.h"
XrdOucTrace *XrdProofdTrace = 0;
static XrdSysLogger eLogger;
static XrdSysError eDest(0, "Proofx");
#ifdef WIN32
ULong64_t TSocket::fgBytesSent;
ULong64_t TSocket::fgBytesRecv;
#endif
//______________________________________________________________________________
//---- error handling ----------------------------------------------------------
////////////////////////////////////////////////////////////////////////////////
/// Interface to ErrorHandler (protected).
void TXSocket::DoError(int level, const char *location, const char *fmt, va_list va) const
{
::ErrorHandler(level, Form("TXSocket::%s", location), fmt, va);
}
//----- Ping handler -----------------------------------------------------------
////////////////////////////////////////////////////////////////////////////////
class TXSocketPingHandler : public TFileHandler {
TXSocket *fSocket;
public:
TXSocketPingHandler(TXSocket *s, Int_t fd)
: TFileHandler(fd, 1) { fSocket = s; }
Bool_t Notify();
Bool_t ReadNotify() { return Notify(); }
};
////////////////////////////////////////////////////////////////////////////////
/// Ping the socket
Bool_t TXSocketPingHandler::Notify()
{
fSocket->Ping("ping handler");
return kTRUE;
}
// Env variables init flag
Bool_t TXSocket::fgInitDone = kFALSE;
// Static variables for input notification
TXSockPipe TXSocket::fgPipe; // Pipe for input monitoring
TString TXSocket::fgLoc = "undef"; // Location string
// Static buffer manager
std::mutex TXSocket::fgSMtx; // To protect spare list
std::list<TXSockBuf *> TXSocket::fgSQue; // list of spare buffers
Long64_t TXSockBuf::fgBuffMem = 0; // Total allocated memory
Long64_t TXSockBuf::fgMemMax = 10485760; // Max allowed allocated memory [10 MB]
////////////////////////////////////////////////////////////////////////////////
/// Constructor
/// Open the connection to a remote XrdProofd instance and start a PROOF
/// session.
/// The mode 'm' indicates the role of this connection:
/// 'a' Administrator; used by an XPD to contact the head XPD
/// 'i' Internal; used by a TXProofServ to call back its creator
/// (see XrdProofUnixConn)
/// 'C' PROOF manager: open connection only (do not start a session)
/// 'M' Client creating a top master
/// 'A' Client attaching to top master
/// 'm' Top master creating a submaster
/// 's' Master creating a slave
/// The buffer 'logbuf' is a null terminated string to be sent over at
/// login.
TXSocket::TXSocket(const char *url, Char_t m, Int_t psid, Char_t capver,
const char *logbuf, Int_t loglevel, TXHandler *handler)
: TSocket(), fMode(m), fLogLevel(loglevel),
fBuffer(logbuf), fConn(0), fASem(0), fAsynProc(1),
fDontTimeout(kFALSE), fRDInterrupt(kFALSE), fXrdProofdVersion(-1)
{
fUrl = url;
// Enable tracing in the XrdProof client. if not done already
eDest.logger(&eLogger);
if (!XrdProofdTrace)
XrdProofdTrace = new XrdOucTrace(&eDest);
// Init envs the first time
if (!fgInitDone)
InitEnvs();
// Async queue related stuff
fAQue.clear();
// Interrupts queue related stuff
fILev = -1;
fIForward = kFALSE;
// Init some variables
fByteLeft = 0;
fByteCur = 0;
fBufCur = 0;
fServType = kPROOFD; // for consistency
fTcpWindowSize = -1;
fRemoteProtocol = -1;
// By default forward directly to end-point
fSendOpt = (fMode == 'i') ? (kXPD_internal | kXPD_async) : kXPD_async;
fSessionID = (fMode == 'C') ? -1 : psid;
fSocket = -1;
// This is used by external code to create a link between this object
// and another one
fReference = 0;
// The global pipe
if (!fgPipe.IsValid()) {
Error("TXSocket", "internal pipe is invalid");
return;
}
// Some initial values
TUrl u(url);
fAddress = gSystem->GetHostByName(u.GetHost());
u.SetProtocol("proof", kTRUE);
fAddress.fPort = (u.GetPort() > 0) ? u.GetPort() : 1093;
// Set the asynchronous handler
fHandler = handler;
if (url) {
// Create connection (for managers the type of the connection is the same
// as for top masters)
char md = (fMode !='A' && fMode !='C') ? fMode : 'M';
fConn = new XrdProofConn(url, md, psid, capver, this, fBuffer.Data());
if (!fConn || !(fConn->IsValid())) {
if (fConn->GetServType() != XrdProofConn::kSTProofd)
if (gDebug > 0)
Error("TXSocket", "fatal error occurred while opening a connection"
" to server [%s]: %s", url, fConn->GetLastErr());
return;
}
// Fill some info
fUser = fConn->fUser.c_str();
fHost = fConn->fHost.c_str();
fPort = fConn->fPort;
// Create new proofserv if not client manager or administrator or internal mode
if (fMode == 'm' || fMode == 's' || fMode == 'M' || fMode == 'A'|| fMode == 'L') {
// We attach or create
if (!Create()) {
// Failure
Error("TXSocket", "create or attach failed (%s)",
((fConn->fLastErrMsg.length() > 0) ? fConn->fLastErrMsg.c_str() : "-"));
Close();
return;
}
}
// Fill some other info available if Create is successful
if (fMode == 'C') {
fXrdProofdVersion = fConn->fRemoteProtocol;
fRemoteProtocol = fConn->fRemoteProtocol;
}
// Also in the base class
fUrl = fConn->fUrl.GetUrl().c_str();
fAddress = gSystem->GetHostByName(fConn->fUrl.Host.c_str());
fAddress.fPort = fPort;
// This is needed for the reader thread to signal an interrupt
fPid = gSystem->GetPid();
}
}
////////////////////////////////////////////////////////////////////////////////
/// Destructor
TXSocket::~TXSocket()
{
// Disconnect from remote server (the connection manager is
// responsible of the underlying physical connection, so we do not
// force its closing)
Close();
}
////////////////////////////////////////////////////////////////////////////////
/// Set location string
void TXSocket::SetLocation(const char *loc)
{
if (loc) {
fgLoc = loc;
fgPipe.SetLoc(loc);
} else {
fgLoc = "";
fgPipe.SetLoc("");
}
}
////////////////////////////////////////////////////////////////////////////////
/// Set session ID to 'id'. If id < 0, disable also the asynchronous handler.
void TXSocket::SetSessionID(Int_t id)
{
if (id < 0 && fConn)
fConn->SetAsync(0);
fSessionID = id;
}
////////////////////////////////////////////////////////////////////////////////
/// Disconnect a session. Use opt= "S" or "s" to
/// shutdown remote session.
/// Default is opt = "".
void TXSocket::DisconnectSession(Int_t id, Option_t *opt)
{
// Make sure we are connected
if (!IsValid()) {
if (gDebug > 0)
Info("DisconnectSession","not connected: nothing to do");
return;
}
Bool_t shutdown = opt && (strchr(opt,'S') || strchr(opt,'s'));
Bool_t all = opt && (strchr(opt,'A') || strchr(opt,'a'));
if (id > -1 || all) {
// Prepare request
XPClientRequest Request;
memset(&Request, 0, sizeof(Request) );
fConn->SetSID(Request.header.streamid);
if (shutdown)
Request.proof.requestid = kXP_destroy;
else
Request.proof.requestid = kXP_detach;
Request.proof.sid = id;
// Send request
XrdClientMessage *xrsp =
fConn->SendReq(&Request, (const void *)0, 0, "DisconnectSession");
// Print error msg, if any
if (!xrsp && fConn->GetLastErr())
Printf("%s: %s", fHost.Data(), fConn->GetLastErr());
// Cleanup
SafeDelete(xrsp);
}
}
////////////////////////////////////////////////////////////////////////////////
/// Close connection. Available options are (case insensitive)
/// 'P' force closing of the underlying physical connection
/// 'S' shutdown remote session, is any
/// A session ID can be given using #...# signature, e.g. "#1#".
/// Default is opt = "".
void TXSocket::Close(Option_t *opt)
{
Int_t to = gEnv->GetValue("XProof.AsynProcSemTimeout", 60);
if (fAsynProc.Wait(to*1000) != 0)
Warning("Close", "could not hold semaphore for async messages after %d sec: closing anyhow (may give error messages)", to);
// Remove any reference in the global pipe and ready-sock queue
TXSocket::fgPipe.Flush(this);
// Make sure we have a connection
if (!fConn) {
if (gDebug > 0)
Info("Close","no connection: nothing to do");
fAsynProc.Post();
return;
}
// Disconnect the asynchronous requests handler
fConn->SetAsync(0);
// If we are connected we disconnect
if (IsValid()) {
// Parse options
TString o(opt);
Int_t sessID = fSessionID;
if (o.Index("#") != kNPOS) {
o.Remove(0,o.Index("#")+1);
if (o.Index("#") != kNPOS) {
o.Remove(o.Index("#"));
sessID = o.IsDigit() ? o.Atoi() : sessID;
}
}
if (sessID > -1) {
// Warn the remote session, if any (after destroy the session is gone)
DisconnectSession(sessID, opt);
} else {
// We are the manager: close underlying connection
fConn->Close(opt);
}
}
// Delete the connection module
SafeDelete(fConn);
// Post semaphore
fAsynProc.Post();
}
////////////////////////////////////////////////////////////////////////////////
/// We are here if an unsolicited response comes from a logical conn
/// The response comes in the form of an XrdClientMessage *, that must NOT be
/// destroyed after processing. It is destroyed by the first sender.
/// Remember that we are in a separate thread, since unsolicited
/// responses are asynchronous by nature.
UnsolRespProcResult TXSocket::ProcessUnsolicitedMsg(XrdClientUnsolMsgSender *,
XrdClientMessage *m)
{
UnsolRespProcResult rc = kUNSOL_KEEP;
// If we are closing we will not do anything
TXSemaphoreGuard semg(&fAsynProc);
if (!semg.IsValid()) {
Error("ProcessUnsolicitedMsg", "%p: async semaphore taken by Close()! Should not be here!", this);
return kUNSOL_CONTINUE;
}
if (!m) {
if (gDebug > 2)
Info("ProcessUnsolicitedMsg", "%p: got empty message: skipping", this);
// Some one is perhaps interested in empty messages
return kUNSOL_CONTINUE;
} else {
if (gDebug > 2)
Info("ProcessUnsolicitedMsg", "%p: got message with status: %d, len: %d bytes (ID: %d)",
this, m->GetStatusCode(), m->DataLen(), m->HeaderSID());
}
// Error notification
if (m->IsError()) {
if (m->GetStatusCode() != XrdClientMessage::kXrdMSC_timeout) {
if (gDebug > 0)
Info("ProcessUnsolicitedMsg","%p: got error from underlying connection", this);
XHandleErr_t herr = {1, 0};
if (!fHandler || fHandler->HandleError((const void *)&herr)) {
if (gDebug > 0)
Info("ProcessUnsolicitedMsg","%p: handler undefined or recovery failed", this);
// Avoid to contact the server any more
fSessionID = -1;
} else {
// Connection still usable: update usage timestamp
Touch();
}
} else {
// Time out
if (gDebug > 2)
Info("ProcessUnsolicitedMsg", "%p: underlying connection timed out", this);
}
// Propagate the message to other possible handlers
return kUNSOL_CONTINUE;
}
// From now on make sure is for us (but only if not during setup, i.e. fConn == 0; otherwise
// we may miss some important server message)
if (fConn && !m->MatchStreamid(fConn->fStreamid)) {
if (gDebug > 1)
Info("ProcessUnsolicitedMsg", "%p: IDs do not match: {%d, %d}", this, fConn->fStreamid, m->HeaderSID());
return kUNSOL_CONTINUE;
}
// Local processing ...
Int_t len = 0;
if ((len = m->DataLen()) < (int)sizeof(kXR_int32)) {
Error("ProcessUnsolicitedMsg", "empty or bad-formed message - disabling");
PostMsg(kPROOF_STOP);
return rc;
}
// Activity on the line: update usage timestamp
Touch();
// The first 4 bytes contain the action code
kXR_int32 acod = 0;
memcpy(&acod, m->GetData(), sizeof(kXR_int32));
if (acod > 10000)
Info("ProcessUnsolicitedMsg", "%p: got acod %d (%x): message has status: %d, len: %d bytes (ID: %d)",
this, acod, acod, m->GetStatusCode(), m->DataLen(), m->HeaderSID());
//
// Update pointer to data
void *pdata = (void *)((char *)(m->GetData()) + sizeof(kXR_int32));
len -= sizeof(kXR_int32);
if (gDebug > 1)
Info("ProcessUnsolicitedMsg", "%p: got action: %d (%d bytes) (ID: %d)",
this, acod, len, m->HeaderSID());
if (gDebug > 3)
fgPipe.DumpReadySock();
// Case by case
kXR_int32 ilev = -1;
const char *lab = 0;
switch (acod) {
case kXPD_ping:
//
// Special interrupt
ilev = TProof::kPing;
lab = "kXPD_ping";
case kXPD_interrupt:
//
// Interrupt
lab = !lab ? "kXPD_interrupt" : lab;
{ std::lock_guard<std::recursive_mutex> lock(fIMtx);
if (acod == kXPD_interrupt) {
memcpy(&ilev, pdata, sizeof(kXR_int32));
ilev = net2host(ilev);
// Update pointer to data
pdata = (void *)((char *)pdata + sizeof(kXR_int32));
len -= sizeof(kXR_int32);
}
// The next 4 bytes contain the forwarding option
kXR_int32 ifw = 0;
if (len > 0) {
memcpy(&ifw, pdata, sizeof(kXR_int32));
ifw = net2host(ifw);
if (gDebug > 1)
Info("ProcessUnsolicitedMsg","%s: forwarding option: %d", lab, ifw);
}
//
// Save the interrupt
fILev = ilev;
fIForward = (ifw == 1) ? kTRUE : kFALSE;
// Handle this input in this thread to avoid queuing on the
// main thread
XHandleIn_t hin = {acod, 0, 0, 0};
if (fHandler)
fHandler->HandleInput((const void *)&hin);
else
Error("ProcessUnsolicitedMsg","handler undefined");
}
break;
case kXPD_timer:
//
// Set shutdown timer
{
kXR_int32 opt = 1;
kXR_int32 delay = 0;
// The next 4 bytes contain the shutdown option
if (len > 0) {
memcpy(&opt, pdata, sizeof(kXR_int32));
opt = net2host(opt);
if (gDebug > 1)
Info("ProcessUnsolicitedMsg","kXPD_timer: found opt: %d", opt);
// Update pointer to data
pdata = (void *)((char *)pdata + sizeof(kXR_int32));
len -= sizeof(kXR_int32);
}
// The next 4 bytes contain the delay
if (len > 0) {
memcpy(&delay, pdata, sizeof(kXR_int32));
delay = net2host(delay);
if (gDebug > 1)
Info("ProcessUnsolicitedMsg","kXPD_timer: found delay: %d", delay);
// Update pointer to data
pdata = (void *)((char *)pdata + sizeof(kXR_int32));
len -= sizeof(kXR_int32);
}
// Handle this input in this thread to avoid queuing on the
// main thread
XHandleIn_t hin = {acod, opt, delay, 0};
if (fHandler)
fHandler->HandleInput((const void *)&hin);
else
Error("ProcessUnsolicitedMsg","handler undefined");
}
break;
case kXPD_inflate:
//
// Set inflate factor
{
kXR_int32 inflate = 1000;
if (len > 0) {
memcpy(&inflate, pdata, sizeof(kXR_int32));
inflate = net2host(inflate);
if (gDebug > 1)
Info("ProcessUnsolicitedMsg","kXPD_inflate: factor: %d", inflate);
// Update pointer to data
pdata = (void *)((char *)pdata + sizeof(kXR_int32));
len -= sizeof(kXR_int32);
}
// Handle this input in this thread to avoid queuing on the
// main thread
XHandleIn_t hin = {acod, inflate, 0, 0};
if (fHandler)
fHandler->HandleInput((const void *)&hin);
else
Error("ProcessUnsolicitedMsg","handler undefined");
}
break;
case kXPD_priority:
//
// Broadcast group priority
{
kXR_int32 priority = -1;
if (len > 0) {
memcpy(&priority, pdata, sizeof(kXR_int32));
priority = net2host(priority);
if (gDebug > 1)
Info("ProcessUnsolicitedMsg","kXPD_priority: priority: %d", priority);
// Update pointer to data
pdata = (void *)((char *)pdata + sizeof(kXR_int32));
len -= sizeof(kXR_int32);
}
// Handle this input in this thread to avoid queuing on the
// main thread
XHandleIn_t hin = {acod, priority, 0, 0};
if (fHandler)
fHandler->HandleInput((const void *)&hin);
else
Error("ProcessUnsolicitedMsg","handler undefined");
}
break;
case kXPD_flush:
//
// Flush request
{
// Handle this input in this thread to avoid queuing on the
// main thread
XHandleIn_t hin = {acod, 0, 0, 0};
if (fHandler)
fHandler->HandleInput((const void *)&hin);
else
Error("ProcessUnsolicitedMsg","handler undefined");
}
break;
case kXPD_urgent:
//
// Set shutdown timer
{
// The next 4 bytes contain the urgent msg type
kXR_int32 type = -1;
if (len > 0) {
memcpy(&type, pdata, sizeof(kXR_int32));
type = net2host(type);
if (gDebug > 1)
Info("ProcessUnsolicitedMsg","kXPD_urgent: found type: %d", type);
// Update pointer to data
pdata = (void *)((char *)pdata + sizeof(kXR_int32));
len -= sizeof(kXR_int32);
}
// The next 4 bytes contain the first info container
kXR_int32 int1 = -1;
if (len > 0) {
memcpy(&int1, pdata, sizeof(kXR_int32));
int1 = net2host(int1);
if (gDebug > 1)
Info("ProcessUnsolicitedMsg","kXPD_urgent: found int1: %d", int1);
// Update pointer to data
pdata = (void *)((char *)pdata + sizeof(kXR_int32));
len -= sizeof(kXR_int32);
}
// The next 4 bytes contain the second info container
kXR_int32 int2 = -1;
if (len > 0) {
memcpy(&int2, pdata, sizeof(kXR_int32));
int2 = net2host(int2);
if (gDebug > 1)
Info("ProcessUnsolicitedMsg","kXPD_urgent: found int2: %d", int2);
// Update pointer to data
pdata = (void *)((char *)pdata + sizeof(kXR_int32));
len -= sizeof(kXR_int32);
}
// Handle this input in this thread to avoid queuing on the
// main thread
XHandleIn_t hin = {acod, type, int1, int2};
if (fHandler)
fHandler->HandleInput((const void *)&hin);
else
Error("ProcessUnsolicitedMsg","handler undefined");
}
break;
case kXPD_msg:
//
// Data message
{ std::lock_guard<std::recursive_mutex> lock(fAMtx);
// Get a spare buffer
TXSockBuf *b = PopUpSpare(len);
if (!b) {
Error("ProcessUnsolicitedMsg","could allocate spare buffer");
return rc;
}
memcpy(b->fBuf, pdata, len);
b->fLen = len;
// Update counters
fBytesRecv += len;
// Produce the message
fAQue.push_back(b);
// Post the global pipe
fgPipe.Post(this);
// Signal it and release the mutex
if (gDebug > 2)
Info("ProcessUnsolicitedMsg","%p: %s: posting semaphore: %p (%d bytes)",
this, GetTitle(), &fASem, len);
fASem.Post();
}
break;
case kXPD_feedback:
Info("ProcessUnsolicitedMsg",
"kXPD_feedback treatment not yet implemented");
break;
case kXPD_srvmsg:
//
// Service message
{
// The next 4 bytes may contain a flag to control the way the message is displayed
kXR_int32 opt = 0;
memcpy(&opt, pdata, sizeof(kXR_int32));
opt = net2host(opt);
if (opt >= 0 && opt <= 4) {
// Update pointer to data
pdata = (void *)((char *)pdata + sizeof(kXR_int32));
len -= sizeof(kXR_int32);
} else {
opt = 1;
}
if (opt == 0) {
// One line
Printf("| %.*s", len, (char *)pdata);
} else if (opt == 2) {
// Raw displaying
Printf("%.*s", len, (char *)pdata);
} else if (opt == 3) {
// Incremental displaying
fprintf(stderr, "%.*s", len, (char *)pdata);
} else if (opt == 4) {
// Rewind
fprintf(stderr, "%.*s\r", len, (char *)pdata);
} else {
// A small header
Printf(" ");
Printf("| Message from server:");
Printf("| %.*s", len, (char *)pdata);
}
}
break;
case kXPD_errmsg:
//
// Error condition with message
Printf("\n\n");
Printf("| Error condition occured: message from server:");
Printf("| %.*s", len, (char *)pdata);
Printf("\n");
// Handle error
if (fHandler)
fHandler->HandleError();
else
Error("ProcessUnsolicitedMsg","handler undefined");
break;
case kXPD_msgsid:
//
// Data message
{ std::lock_guard<std::recursive_mutex> lock(fAMtx);
// The next 4 bytes contain the sessiond id
kXR_int32 cid = 0;
memcpy(&cid, pdata, sizeof(kXR_int32));
cid = net2host(cid);
if (gDebug > 1)
Info("ProcessUnsolicitedMsg","found cid: %d", cid);
// Update pointer to data
pdata = (void *)((char *)pdata + sizeof(kXR_int32));
len -= sizeof(kXR_int32);
// Get a spare buffer
TXSockBuf *b = PopUpSpare(len);
if (!b) {
Error("ProcessUnsolicitedMsg","could allocate spare buffer");
return rc;
}
memcpy(b->fBuf, pdata, len);
b->fLen = len;
// Set the sid
b->fCid = cid;
// Update counters
fBytesRecv += len;
// Produce the message
fAQue.push_back(b);
// Post the global pipe
fgPipe.Post(this);
// Signal it and release the mutex
if (gDebug > 2)
Info("ProcessUnsolicitedMsg","%p: cid: %d, posting semaphore: %p (%d bytes)",
this, cid, &fASem, len);
fASem.Post();
}
break;
case kXPD_wrkmortem:
//
// A worker died
{ TString what = TString::Format("%.*s", len, (char *)pdata);
if (what.BeginsWith("idle-timeout")) {
// Notify the idle timeout
PostMsg(kPROOF_FATAL, kPROOF_WorkerIdleTO);
} else {
Printf(" ");
Printf("| %s", what.Data());
// Handle error
if (fHandler)
fHandler->HandleError();
else
Error("ProcessUnsolicitedMsg","handler undefined");
}
}
break;
case kXPD_touch:
//
// Request for remote touch: post a message to do that
PostMsg(kPROOF_TOUCH);
break;
case kXPD_resume:
//
// process the next query (in the TXProofServ)
PostMsg(kPROOF_STARTPROCESS);
break;
case kXPD_clusterinfo:
//
// Broadcast cluster information
{
kXR_int32 nsess = -1, nacti = -1, neffs = -1;
if (len > 0) {
// Total sessions
memcpy(&nsess, pdata, sizeof(kXR_int32));
nsess = net2host(nsess);
pdata = (void *)((char *)pdata + sizeof(kXR_int32));
len -= sizeof(kXR_int32);
// Active sessions
memcpy(&nacti, pdata, sizeof(kXR_int32));
nacti = net2host(nacti);
pdata = (void *)((char *)pdata + sizeof(kXR_int32));
len -= sizeof(kXR_int32);
// Effective sessions
memcpy(&neffs, pdata, sizeof(kXR_int32));
neffs = net2host(neffs);
pdata = (void *)((char *)pdata + sizeof(kXR_int32));
len -= sizeof(kXR_int32);
}
if (gDebug > 1)
Info("ProcessUnsolicitedMsg","kXPD_clusterinfo: # sessions: %d,"
" # active: %d, # effective: %f", nsess, nacti, neffs/1000.);
// Handle this input in this thread to avoid queuing on the
// main thread
XHandleIn_t hin = {acod, nsess, nacti, neffs};
if (fHandler)
fHandler->HandleInput((const void *)&hin);
else
Error("ProcessUnsolicitedMsg","handler undefined");
}
break;
default:
Error("ProcessUnsolicitedMsg","%p: unknown action code: %d received from '%s' - disabling",
this, acod, GetTitle());
PostMsg(kPROOF_STOP);
break;
}
// We are done
return rc;
}
////////////////////////////////////////////////////////////////////////////////
/// Post a message of type 'type' into the read messages queue.
/// If 'msg' is defined it is also added as TString.
/// This is used, for example, with kPROOF_FATAL to force the main thread
/// to mark this socket as bad, avoiding race condition when a worker
/// dies while in processing state.
void TXSocket::PostMsg(Int_t type, const char *msg)
{
// Create the message
TMessage m(type);
// Add the string if any
if (msg && strlen(msg) > 0)
m << TString(msg);
// Write length in first word of buffer
m.SetLength();
// Get pointer to the message buffer
char *mbuf = m.Buffer();
Int_t mlen = m.Length();
if (m.CompBuffer()) {
mbuf = m.CompBuffer();
mlen = m.CompLength();
}
//
// Data message
std::lock_guard<std::recursive_mutex> lock(fAMtx);
// Get a spare buffer
TXSockBuf *b = PopUpSpare(mlen);
if (!b) {
Error("PostMsg", "could allocate spare buffer");
return;
}
// Fill the pipe buffer
memcpy(b->fBuf, mbuf, mlen);
b->fLen = mlen;
// Update counters
fBytesRecv += mlen;
// Produce the message
fAQue.push_back(b);
// Post the global pipe
fgPipe.Post(this);
// Signal it and release the mutex
if (gDebug > 0)
Info("PostMsg", "%p: posting type %d to semaphore: %p (%d bytes)",
this, type, &fASem, mlen);
fASem.Post();
// Done
return;
}
////////////////////////////////////////////////////////////////////////////////
/// Wake up all threads waiting for at the semaphore (used by TXSlave)
void TXSocket::PostSemAll()
{
std::lock_guard<std::recursive_mutex> lock(fAMtx);
// Post semaphore to wake up anybody waiting; send as many posts as needed
while (fASem.TryWait() != 1)
fASem.Post();
return;
}
////////////////////////////////////////////////////////////////////////////////
/// Getter for logical connection ID
Int_t TXSocket::GetLogConnID() const
{
return (fConn ? fConn->GetLogConnID() : -1);
}
////////////////////////////////////////////////////////////////////////////////
/// Getter for last error
Int_t TXSocket::GetOpenError() const
{
return (fConn ? fConn->GetOpenError() : -1);
}
////////////////////////////////////////////////////////////////////////////////
/// Getter for server type
Int_t TXSocket::GetServType() const
{
return (fConn ? fConn->GetServType() : -1);
}
////////////////////////////////////////////////////////////////////////////////
/// Getter for session ID
Int_t TXSocket::GetSessionID() const
{
return (fConn ? fConn->GetSessionID() : -1);
}
////////////////////////////////////////////////////////////////////////////////
/// Getter for validity status
Bool_t TXSocket::IsValid() const
{
return (fConn ? (fConn->IsValid()) : kFALSE);
}
////////////////////////////////////////////////////////////////////////////////
/// Return kTRUE if the remote server is a 'proofd'
Bool_t TXSocket::IsServProofd()
{
if (fConn && (fConn->GetServType() == XrdProofConn::kSTProofd))
return kTRUE;
// Failure
return kFALSE;
}
////////////////////////////////////////////////////////////////////////////////
/// Get latest interrupt level and reset it; if the interrupt has to be
/// propagated to lower stages forward will be kTRUE after the call
Int_t TXSocket::GetInterrupt(Bool_t &forward)
{
if (gDebug > 2)
Info("GetInterrupt","%p: waiting to lock mutex", this);
std::lock_guard<std::recursive_mutex> lock(fIMtx);
// Reset values
Int_t ilev = -1;
forward = kFALSE;
// Check if filled
if (fILev == -1)
Error("GetInterrupt", "value is unset (%d) - protocol error",fILev);
// Fill output
ilev = fILev;
forward = fIForward;
// Reset values (we process it only once)
fILev = -1;
fIForward = kFALSE;
// Return what we got
return ilev;
}
////////////////////////////////////////////////////////////////////////////////
/// Flush the asynchronous queue.