xrootd
XrdClientConn.hh
Go to the documentation of this file.
00001 #ifndef XRD_CONN_H
00002 #define XRD_CONN_H
00003 /******************************************************************************/
00004 /*                                                                            */
00005 /*                    X r d C l i e n t C o n n . h h                         */
00006 /*                                                                            */
00007 /* Author: Fabrizio Furano (INFN Padova, 2004)                                */
00008 /* Adapted from TXNetFile (root.cern.ch) originally done by                   */
00009 /*  Alvise Dorigo, Fabrizio Furano                                            */
00010 /*          INFN Padova, 2003                                                 */
00011 /*                                                                            */
00012 /* This file is part of the XRootD software suite.                            */
00013 /*                                                                            */
00014 /* XRootD is free software: you can redistribute it and/or modify it under    */
00015 /* the terms of the GNU Lesser General Public License as published by the     */
00016 /* Free Software Foundation, either version 3 of the License, or (at your     */
00017 /* option) any later version.                                                 */
00018 /*                                                                            */
00019 /* XRootD is distributed in the hope that it will be useful, but WITHOUT      */
00020 /* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or      */
00021 /* FITNESS FOR A PARTICULAR PURPOSE.  See the GNU Lesser General Public       */
00022 /* License for more details.                                                  */
00023 /*                                                                            */
00024 /* You should have received a copy of the GNU Lesser General Public License   */
00025 /* along with XRootD in a file called COPYING.LESSER (LGPL license) and file  */
00026 /* COPYING (GPL license).  If not, see <http://www.gnu.org/licenses/>.        */
00027 /*                                                                            */
00028 /* The copyright holder's institutional names and contributor's names may not */
00029 /* be used to endorse or promote products derived from this software without  */
00030 /* specific prior written permission of the institution or contributor.       */
00031 /******************************************************************************/
00032 
00034 //                                                                      //
00035 // High level handler of connections to xrootd.                         //
00036 //                                                                      //
00038 
00039 #include "XrdClient/XrdClientConst.hh"
00040 
00041 #include "time.h"
00042 #include "XrdClient/XrdClientConnMgr.hh"
00043 #include "XrdClient/XrdClientMessage.hh"
00044 #include "XrdClient/XrdClientUrlInfo.hh"
00045 #include "XrdClient/XrdClientReadCache.hh"
00046 #include "XrdOuc/XrdOucHash.hh"
00047 #include "XrdSys/XrdSysPthread.hh"
00048 
00049 #define ConnectionManager XrdClientConn::GetConnectionMgr()
00050 
00051 class XrdClientAbs;
00052 class XrdSecProtocol;
00053 
00054 class XrdClientConn {
00055 
00056 public:
00057 
00058     enum ESrvErrorHandlerRetval {
00059         kSEHRReturnMsgToCaller   = 0,
00060         kSEHRBreakLoop           = 1,
00061         kSEHRContinue            = 2,
00062         kSEHRReturnNoMsgToCaller = 3,
00063         kSEHRRedirLimitReached   = 4
00064     };
00065     enum EThreeStateReadHandler {
00066         kTSRHReturnMex     = 0,
00067         kTSRHReturnNullMex = 1,
00068         kTSRHContinue      = 2
00069     };
00070 
00071     // To keep info about an open session
00072     struct                     SessionIDInfo {
00073         char id[16];
00074     };
00075 
00076     int                        fLastDataBytesRecv;
00077     int                        fLastDataBytesSent;
00078     XErrorCode                 fOpenError;      
00079 
00080     XrdOucString               fRedirOpaque;        // Opaque info returned by the server when
00081 
00082     // redirecting. To be used in the next opens
00083     XrdClientConn();
00084     virtual ~XrdClientConn();
00085 
00086     inline bool                CacheWillFit(long long bytes) {
00087         if (!fMainReadCache)
00088             return FALSE;
00089         return fMainReadCache->WillFit(bytes);
00090     }
00091 
00092     bool                       CheckHostDomain(XrdOucString hostToCheck);
00093     short                      Connect(XrdClientUrlInfo Host2Conn,
00094                                        XrdClientAbsUnsolMsgHandler *unsolhandler);
00095     void                       Disconnect(bool ForcePhysicalDisc);
00096     virtual bool               GetAccessToSrv();
00097     XReqErrorType              GoBackToRedirector();
00098 
00099     XrdOucString               GetClientHostDomain() { return fgClientHostDomain; }
00100 
00101 
00102     static XrdClientPhyConnection     *GetPhyConn(int LogConnID);
00103 
00104 
00105     // --------- Cache related stuff
00106 
00107     long                       GetDataFromCache(const void *buffer,
00108                                                 long long begin_offs,
00109                                                 long long end_offs,
00110                                                 bool PerfCalc,
00111                                                 XrdClientIntvList &missingblks,
00112                                                 long &outstandingblks );
00113 
00114     bool                       SubmitDataToCache(XrdClientMessage *xmsg,
00115                                                  long long begin_offs,
00116                                                  long long end_offs);
00117 
00118     bool                       SubmitRawDataToCache(const void *buffer,
00119                                                  long long begin_offs,
00120                                                  long long end_offs);
00121 
00122     void                       SubmitPlaceholderToCache(long long begin_offs,
00123                                                         long long end_offs) {
00124         if (fMainReadCache)
00125             fMainReadCache->PutPlaceholder(begin_offs, end_offs);
00126     }
00127 
00128   
00129     void                       RemoveAllDataFromCache(bool keepwriteblocks=true) {
00130         if (fMainReadCache)
00131             fMainReadCache->RemoveItems(keepwriteblocks);
00132     }
00133 
00134     void                       RemoveDataFromCache(long long begin_offs,
00135                                                    long long end_offs, bool remove_overlapped = false) {
00136         if (fMainReadCache)
00137           fMainReadCache->RemoveItems(begin_offs, end_offs, remove_overlapped);
00138     }
00139 
00140     void                       RemovePlaceholdersFromCache() {
00141         if (fMainReadCache)
00142             fMainReadCache->RemovePlaceholders();
00143     }
00144 
00145     void                       PrintCache() {
00146         if (fMainReadCache)
00147             fMainReadCache->PrintCache();
00148     }
00149 
00150 
00151   bool                       GetCacheInfo(
00152                                           // The actual cache size
00153                                           int &size,
00154 
00155                                           // The number of bytes submitted since the beginning
00156                                           long long &bytessubmitted,
00157 
00158                                           // The number of bytes found in the cache (estimate)
00159                                           long long &byteshit,
00160 
00161                                           // The number of reads which did not find their data
00162                                           // (estimate)
00163                                           long long &misscount,
00164 
00165                                           // miss/totalreads ratio (estimate)
00166                                           float &missrate,
00167 
00168                                           // number of read requests towards the cache
00169                                           long long &readreqcnt,
00170 
00171                                           // ratio between bytes found / bytes submitted
00172                                           float &bytesusefulness
00173                                           ) {
00174       if (!fMainReadCache) return false;
00175 
00176       fMainReadCache->GetInfo(size,
00177                               bytessubmitted,
00178                               byteshit,
00179                               misscount,
00180                               missrate,
00181                               readreqcnt,
00182                               bytesusefulness);
00183       return true;
00184     }  
00185                                           
00186 
00187     void                       SetCacheSize(int CacheSize) {
00188         if (!fMainReadCache && CacheSize)
00189           fMainReadCache = new XrdClientReadCache();
00190 
00191         if (fMainReadCache)
00192            fMainReadCache->SetSize(CacheSize);
00193     }
00194 
00195     void                       SetCacheRmPolicy(int RmPolicy) {
00196         if (fMainReadCache)
00197            fMainReadCache->SetBlkRemovalPolicy(RmPolicy);
00198     }
00199 
00200     void                       UnPinCacheBlk(long long begin_offs, long long end_offs) {
00201         fMainReadCache->UnPinCacheBlk(begin_offs, end_offs);
00202         // Also use this to signal the possibility to proceed for a hard checkpoint
00203         fWriteWaitAck->Broadcast();
00204     }
00205 
00206 
00207     // -------------------
00208 
00209 
00210     int                        GetLogConnID() const { return fLogConnID; }
00211 
00212     ERemoteServerType          GetServerType() const { return fServerType; }
00213 
00214     kXR_unt16                  GetStreamID() const { return fPrimaryStreamid; }
00215 
00216     inline XrdClientUrlInfo    *GetLBSUrl() { return fLBSUrl; }
00217     inline XrdClientUrlInfo    *GetMetaUrl() { return fMetaUrl; }
00218     inline XrdClientUrlInfo    GetCurrentUrl() { return fUrl; }
00219     inline XrdClientUrlInfo    GetRedirUrl() { return fREQUrl; }
00220 
00221     XErrorCode                 GetOpenError() const { return fOpenError; }
00222     virtual XReqErrorType      GoToAnotherServer(XrdClientUrlInfo &newdest);
00223     virtual XReqErrorType      GoToMetaManager();
00224     bool                       IsConnected() const { return fConnected; }
00225     bool                       IsPhyConnConnected();
00226 
00227     struct ServerResponseHeader
00228                                LastServerResp;
00229 
00230     struct ServerResponseBody_Error
00231                                LastServerError;
00232 
00233     void                       ClearLastServerError() {
00234                                    memset(&LastServerError, 0, sizeof(LastServerError));
00235                                    LastServerError.errnum = kXR_noErrorYet;
00236                                }
00237 
00238     UnsolRespProcResult        ProcessAsynResp(XrdClientMessage *unsolmsg);
00239 
00240     virtual bool               SendGenCommand(ClientRequest *req, 
00241                                               const void *reqMoreData,       
00242                                               void **answMoreDataAllocated,
00243                                               void *answMoreData, bool HasToAlloc,
00244                                               char *CmdName, int substreamid = 0);
00245 
00246     int                        GetOpenSockFD() const { return fOpenSockFD; }
00247 
00248     void                       SetClientHostDomain(const char *src) { fgClientHostDomain = src; }
00249     void                       SetConnected(bool conn) { fConnected = conn; }
00250 
00251     void                       SetOpenError(XErrorCode err) { fOpenError = err; }
00252 
00253     // Gets a parallel stream id to use to set the return path for a re
00254     int                        GetParallelStreamToUse(int reqsperstream);
00255     int                        GetParallelStreamCount();     // Returns the total number of connected streams
00256 
00257     void                       SetRedirHandler(XrdClientAbs *rh) { fRedirHandler = rh; }
00258 
00259     void                       SetRequestedDestHost(char *newh, kXR_int32 port) {
00260         fREQUrl = fUrl;
00261         fREQUrl.Host = newh;
00262         fREQUrl.Port = port;
00263         fREQUrl.SetAddrFromHost();
00264     }
00265 
00266     // Puts this instance in pause state for wsec seconds.
00267     // A value <= 0 revokes immediately the pause state
00268     void                       SetREQPauseState(kXR_int32 wsec) {
00269         // Lock mutex
00270         fREQWait->Lock();
00271 
00272         if (wsec > 0)
00273             fREQWaitTimeLimit = time(0) + wsec;
00274         else {
00275             fREQWaitTimeLimit = 0;
00276             fREQWait->Broadcast();
00277         }
00278 
00279         // UnLock mutex
00280         fREQWait->UnLock();
00281     }
00282 
00283     // Puts this instance in connect-pause state for wsec seconds.
00284     // Any future connection attempt will not happen before wsec
00285     //  and the first one will be towards the given host
00286     void                       SetREQDelayedConnectState(kXR_int32 wsec) {
00287         // Lock mutex
00288         fREQConnectWait->Lock();
00289 
00290         if (wsec > 0)
00291             fREQConnectWaitTimeLimit = time(0) + wsec;
00292         else {
00293             fREQConnectWaitTimeLimit = 0;
00294             fREQConnectWait->Broadcast();
00295         }
00296 
00297         // UnLock mutex
00298         fREQConnectWait->UnLock();
00299     }
00300 
00301     void                       SetSID(kXR_char *sid);
00302     inline void                SetUrl(XrdClientUrlInfo thisUrl) { fUrl = thisUrl; }
00303 
00304     // Sends the request to the server, through logconn with ID LogConnID
00305     // The request is sent with a streamid 'child' of the current one, then marked as pending
00306     // Its answer will be caught asynchronously
00307     XReqErrorType              WriteToServer_Async(ClientRequest *req, 
00308                                                    const void* reqMoreData,
00309                                                    int substreamid = 0);
00310 
00311     static XrdClientConnectionMgr *GetConnectionMgr()
00312     { return fgConnectionMgr;} //Instance of the conn manager
00313 
00314     static void DelSessionIDRepo()         {fSessionIDRMutex.Lock();
00315                                             fSessionIDRepo.Purge();
00316                                             fSessionIDRMutex.UnLock();
00317                                            }
00318 
00319     void GetSessionID(SessionIDInfo &sess) {sess = mySessionID;}
00320 
00321     long                       GetServerProtocol() { return fServerProto; }
00322 
00323     short                      GetMaxRedirCnt() const { return fMaxGlobalRedirCnt; }
00324     void                       SetMaxRedirCnt(short mx) {fMaxGlobalRedirCnt = mx; }
00325     short                      GetRedirCnt() const { return fGlobalRedirCnt; }
00326 
00327     bool                       DoWriteSoftCheckPoint();
00328     bool                       DoWriteHardCheckPoint();
00329     void                       UnPinCacheBlk();
00330 
00331 
00332     // To give a max number of seconds for an operation to complete, no matter what happens inside
00333     // e.g. redirections, sleeps, failed connection attempts etc.
00334     void                       SetOpTimeLimit(int delta_secs);
00335     bool                       IsOpTimeLimitElapsed(time_t timenow);
00336 
00337 
00338 protected:
00339     void                       SetLogConnID(int cid) { fLogConnID = cid; }
00340     void                       SetStreamID(kXR_unt16 sid) { fPrimaryStreamid = sid; }
00341 
00342 
00343 
00344     // The handler which first tried to connect somewhere
00345     XrdClientAbsUnsolMsgHandler *fUnsolMsgHandler;
00346 
00347     XrdClientUrlInfo           fUrl;                // The current URL
00348     XrdClientUrlInfo           *fLBSUrl;            // Needed to save the load balancer url
00349     XrdClientUrlInfo           fREQUrl;             // For explicitly requested redirs
00350 
00351     short                      fGlobalRedirCnt;    // Number of redirections
00352 
00353 private:
00354 
00355     static XrdOucString        fgClientHostDomain; // Save the client's domain name
00356     bool                       fConnected;
00357     bool                       fGettingAccessToSrv; // To avoid recursion in desperate situations
00358     time_t                     fGlobalRedirLastUpdateTimestamp; // Timestamp of last redirection
00359 
00360     int                        fLogConnID;        // Logical connection ID used
00361     kXR_unt16                  fPrimaryStreamid;  // Streamid used for normal communication
00362     // NB it's a copy of the one contained in
00363     // the logconn
00364 
00365     short                      fMaxGlobalRedirCnt;
00366     XrdClientReadCache         *fMainReadCache;
00367 
00368     // The time limit for a transaction
00369     time_t                     fOpTimeLimit;
00370 
00371     XrdClientAbs               *fRedirHandler;      // Pointer to a class inheriting from
00372     // XrdClientAbs providing methods
00373     // to handle a redir at higher level
00374 
00375     XrdOucString               fRedirInternalToken; // Token returned by the server when
00376     // redirecting. To be used in the next logins
00377 
00378     XrdSysCondVar              *fREQWaitResp;           // For explicitly requested delayed async responses
00379     ServerResponseBody_Attn_asynresp *
00380                                fREQWaitRespData;        // For explicitly requested delayed async responses
00381 
00382     time_t                     fREQWaitTimeLimit;   // For explicitly requested pause state
00383     XrdSysCondVar              *fREQWait;           // For explicitly requested pause state
00384     time_t                     fREQConnectWaitTimeLimit;   // For explicitly requested delayed reconnect
00385     XrdSysCondVar              *fREQConnectWait;           // For explicitly requested delayed reconnect
00386 
00387     long                       fServerProto;        // The server protocol
00388     ERemoteServerType          fServerType;         // Server type as returned by doHandShake() 
00389     SessionIDInfo              mySessionID;         // Login session ID
00390 
00391 
00392     static XrdSysMutex         fSessionIDRMutex;    // Mutex for the Repo
00393     static XrdOucHash<SessionIDInfo>
00394     fSessionIDRepo;      // The repository of session IDs, shared.
00395     // Association between
00396     // <hostname>:<port>.<user> and a SessionIDInfo struct
00397 
00398     int                        fOpenSockFD;         // Descriptor of the underlying socket
00399     static XrdClientConnectionMgr *fgConnectionMgr; //Instance of the Connection Manager
00400 
00401     XrdSysCondVar              *fWriteWaitAck;
00402     XrdClientVector<ClientRequest> fWriteReqsToRetry; // To store the write reqs to retry in case of a disconnection
00403 
00404     bool                       CheckErrorStatus(XrdClientMessage *, short &, char *);
00405     void                       CheckPort(int &port);
00406     void                       CheckREQPauseState();
00407     void                       CheckREQConnectWaitState();
00408     bool                       CheckResp(struct ServerResponseHeader *resp, const char *method);
00409     XrdClientMessage           *ClientServerCmd(ClientRequest *req,
00410                                                 const void *reqMoreData,
00411                                                 void **answMoreDataAllocated,
00412                                                 void *answMoreData,
00413                                                 bool HasToAlloc,
00414                                                 int substreamid = 0);
00415     XrdSecProtocol            *DoAuthentication(char *plist, int plsiz);
00416 
00417     ERemoteServerType          DoHandShake(short log);
00418 
00419     bool                       DoLogin();
00420     bool                       DomainMatcher(XrdOucString dom, XrdOucString domlist);
00421 
00422     XrdOucString               GetDomainToMatch(XrdOucString hostname);
00423 
00424     ESrvErrorHandlerRetval     HandleServerError(XReqErrorType &, XrdClientMessage *,
00425                                                  ClientRequest *);
00426     bool                       MatchStreamid(struct ServerResponseHeader *ServerResponse);
00427 
00428     // Sends a close request, without waiting for an answer
00429     // useful (?) to be sent just before closing a badly working stream
00430     bool                       PanicClose();
00431 
00432     XrdOucString               ParseDomainFromHostname(XrdOucString hostname);
00433 
00434     XrdClientMessage           *ReadPartialAnswer(XReqErrorType &, size_t &, 
00435                                                   ClientRequest *, bool, void**,
00436                                                   EThreeStateReadHandler &);
00437 
00438 //  void                       ClearSessionID();
00439 
00440     XReqErrorType              WriteToServer(ClientRequest *req, 
00441                                              const void* reqMoreData,
00442                                              short LogConnID,
00443                                              int substreamid = 0);
00444 
00445     bool                       WaitResp(int secsmax);
00446 
00447     XrdClientUrlInfo           *fMetaUrl;           // Meta manager url
00448     bool                        fLBSIsMeta;         // Is current redirector a meta manager?
00449 
00450 public:
00451     XrdOucString               fRedirCGI;           // Same as fRedirOpaque but persistent
00452 
00453 };
00454 #endif