ROOT logo
//
// This macro attaches to a PROOF session, possibly at the indicated URL.
// If no existing PROOF session is found and no URL is given, the macro
// tries to start a local PROOF session.

#include "Getline.h"
#include "TEnv.h"
#include "TProof.h"
#include "TString.h"
#include "TSystem.h"

Int_t getXrootdPid(Int_t port);

// By default we start a cluster on the local machine
const char *refloc = "proof://localhost:11093";

TProof *getProof(const char *url = "proof://localhost:11093", Int_t nwrks = -1, const char *dir = 0,
                 const char *opt = "ask", Bool_t dyn = kFALSE, Bool_t tutords = kFALSE)
{
   // Arguments:
   //     'url'      URL of the master where to start/attach the PROOF session;
   //                this is also the place where to force creation of a new session,
   //                if needed (use option 'N', e.g. "proof://mymaster:myport/?N")
   //
   // The following arguments apply to xrootd responding at 'refloc' only:
   //     'nwrks'    Number of workers to be started. []
   //     'dir'      Directory to be used for the files and working areas [].
   //     'opt'      Defines what to do if an existing xrootd uses the same ports; possible
   //                options are: "ask", ask the user; "force", kill the xrootd and start
   //                a new one; if any other string is specified the existing xrootd will be
   //                used ["ask"].
   //                NB: for a change in 'nwrks' to be effective you need to specify opt = "force"
   //     'dyn'      This flag can be used to switch on dynamic, per-job worker setup scheduling
   //                [kFALSE].
   //     'tutords'  This flag can be used to force a dataset dir under the tutorial dir [kFALSE]
   //

   TProof *p = 0;

   // If an URL has specified get a session there
   TUrl uu(url), uref(refloc);
   Bool_t ext = (strcmp(uu.GetHost(), uref.GetHost()) ||
                 (uu.GetPort() != uref.GetPort())) ? kTRUE : kFALSE;
   if (ext && url && strlen(url) > 0) {
      if (!strcmp(url, "lite") && nwrks > 0)
         uu.SetOptions(Form("workers=%d", nwrks));
      p = TProof::Open(uu.GetUrl());
      if (p && p->IsValid()) {
         // Check consistency
         if (ext && nwrks > 0) {
            Printf("getProof: WARNING: started/attached a session on external cluster (%s):"
                   " 'nwrks=%d' ignored", url, nwrks);
         }
         if (ext && dir && strlen(dir) > 0) {
            Printf("getProof: WARNING: started/attached a session on external cluster (%s):"
                   " 'dir=\"%s\"' ignored", url, dir);
         }
         if (ext && !strcmp(opt,"force")) {
            Printf("getProof: WARNING: started/attached a session on external cluster (%s):"
                   " 'opt=\"force\"' ignored", url);
         }
         if (ext && dyn) {
            Printf("getProof: WARNING: started/attached a session on external cluster (%s):"
                   " 'dyn=kTRUE' ignored", url);
         }
         // Done
         return p;
      } else {
         if (ext)
            Printf("getProof: could not get/start a valid session at %s - try local", url);
      }
      if (p) delete p;
      p = 0;
   }

#ifdef WIN32
   // No support for local PROOF on Win32 (yet; the optimized local Proof will work there too)
   Printf("getProof: local PROOF not yet supported on Windows, sorry!");
   return p;
#else

   // Temp dir for tutorial daemons
   TString tutdir = dir;
   if (tutdir.IsNull() || gSystem->AccessPathName(dir, kWritePermission)) {
      Printf("getProof: tutorial dir missing or not writable - try temp ");
      tutdir = gSystem->TempDirectory();
      TString us;
      UserGroup_t *ug = gSystem->GetUserInfo(gSystem->GetUid());
      if (!ug) {
         printf("getProof: could not get user info");
         return p;
      }
      us.Form("/%s", ug->fUser.Data());
      if (!tutdir.EndsWith(us.Data())) tutdir += us;
      gSystem->mkdir(tutdir.Data(), kTRUE);
      if (gSystem->AccessPathName(tutdir, kWritePermission)) {
         Printf("getProof: unable to get a writable tutorial directory (tried: %s)"
                " - cannot continue", tutdir.Data());
         return p;
      }
      Printf("getProof: tutorial dir: %s", tutdir.Data());
   }

   // Dataset dir
   TString datasetdir;
   if (tutords) {
      datasetdir = Form("%s/dataset", tutdir.Data());
      if (gSystem->AccessPathName(datasetdir, kWritePermission)) {
         gSystem->mkdir(datasetdir, kTRUE);
         if (gSystem->AccessPathName(datasetdir, kWritePermission)) {
            Printf("getProof: unable to get a writable dataset directory (tried: %s)"
                   " - cannot continue", datasetdir.Data());
            return p;
         }
         Printf("getProof: dataset dir: %s", datasetdir.Data());
      }
   }
   
   // Local url (use a special port to try to not disturb running daemons)
   TUrl u(refloc);
   u.SetProtocol("proof");
   Int_t lportp = u.GetPort();
   Int_t lportx = lportp + 1;
   TString lurl = u.GetUrl();

   // Prepare to start the daemon
   TString workarea = Form("%s/proof", tutdir.Data());
   TString xpdcf(Form("%s/xpd.cf",tutdir.Data()));
   TString xpdlog(Form("%s/xpd.log",tutdir.Data()));
   TString xpdlogprt(Form("%s/xpd-tutorial/xpd.log",tutdir.Data()));
   TString xpdpid(Form("%s/xpd.pid",tutdir.Data()));
   TString proofsessions(Form("%s/sessions",tutdir.Data()));
   TString cmd;
   Int_t rc = 0;

   // Is there something listening already ?
   Int_t pid = -1;
   Bool_t restart = kTRUE;
   gEnv->SetValue("XProof.FirstConnectMaxCnt",1);
   Printf("getProof: checking for an existing daemon ...");
   TProofMgr *mgr = TProof::Mgr(lurl);
   if (mgr && mgr->IsValid()) {

      restart = kFALSE;

      pid = getXrootdPid(lportx);
      Printf("getProof: daemon found listening on dedicated ports {%d,%d} (pid: %d)",
              lportx, lportp, pid);
      if (!strcmp(opt,"ask")) {
         char *answer = Getline("getProof: would you like to restart it (N,Y)? [N] ");
         if (answer && (answer[0] == 'Y' || answer[0] == 'y'))
            restart = kTRUE;
      }
      if (!strcmp(opt,"force"))
         // Always restart
         restart = kTRUE;

      // Cleanup, if required
      if (restart) {

         Printf("getProof: cleaning existing instance ...");

         // Disconnect the manager
         delete mgr;

         // Cleanimg up existing daemon
         cmd = Form("kill -9 %d", pid);
         if ((rc = gSystem->Exec(cmd)) != 0)
            Printf("getProof: problems stopping xrootd process %p (%d)", pid, rc);
      }
   }

   if (restart) {
      // Try to start something locally; make sure that everything is there
      char *xrootd = gSystem->Which(gSystem->Getenv("PATH"), "xrootd", kExecutePermission);
      if (!xrootd) {
         Printf("getProof: xrootd not found: please check the environment!");
         return p;
      }

      // Remove the tutorial dir
      cmd = Form("rm -fr %s/*", tutdir.Data());
      gSystem->Exec(cmd);

      // Try to start something locally; create the xrootd config file
      FILE *fcf = fopen(xpdcf.Data(), "w");
      if (!fcf) {
         Printf("getProof: could not create config file for XPD (%s)", xpdcf.Data());
         return p;
      }
      fprintf(fcf,"### Use admin path at %s/admin to avoid interferences with other users\n", tutdir.Data());
      fprintf(fcf,"xrd.adminpath %s/admin\n", tutdir.Data());
      fprintf(fcf,"### Run data serving on port %d\n", lportp+1);
      fprintf(fcf,"xrd.port %d\n", lportp+1);
      fprintf(fcf,"### Load the XrdProofd protocol on port %d\n", lportp);
      fprintf(fcf,"xrd.protocol xproofd libXrdProofd.so\n");
      fprintf(fcf,"xpd.port %d\n", lportp);
      if (nwrks > 0) {
         fprintf(fcf,"### Force number of local workers\n");
         fprintf(fcf,"xpd.localwrks %d\n", nwrks);
      }
      fprintf(fcf,"### Root path for working dir\n");
      fprintf(fcf,"xpd.workdir %s\n", workarea.Data());
      fprintf(fcf,"### Allow different users to connect\n");
      fprintf(fcf,"xpd.multiuser 1\n");
      fprintf(fcf,"### Limit the number of query results kept in the master sandbox\n");
      fprintf(fcf,"xpd.putrc ProofServ.UserQuotas: maxquerykept=10\n");
      if (tutords) {
         fprintf(fcf,"### Use dataset directory under the tutorial dir\n");
         fprintf(fcf,"xpd.datasetsrc file url:%s opt:-Cq:Av:As:\n", datasetdir.Data());
      }
      if (dyn) {
         fprintf(fcf,"### Use dynamic, per-job scheduling\n");
         fprintf(fcf,"xpd.putrc Proof.DynamicStartup 1\n");
      }
      fclose(fcf);
      Printf("getProof: xrootd config file at %s", xpdcf.Data());

      // Start xrootd in the background
      Printf("getProof: xrootd log file at %s", xpdlogprt.Data());
      cmd = Form("%s -c %s -b -l %s -n xpd-tutorial -p %d",
               xrootd, xpdcf.Data(), xpdlog.Data(), lportx);
      Printf("(NB: any error line from XrdClientSock::RecvRaw and XrdClientMessage::ReadRaw should be ignored)");
      if ((rc = gSystem->Exec(cmd)) != 0) {
         Printf("getProof: problems starting xrootd (%d)", rc);
         return p;
      }
      delete[] xrootd;

      // Wait a bit
      Printf("getProof: waiting for xrootd to start ...");
      gSystem->Sleep(2000);

      pid = getXrootdPid(lportx);
      Printf("getProof: xrootd pid: %d", pid);

      // Save it in the PID file
      FILE *fpid = fopen(xpdpid.Data(), "w");
      if (!fpid) {
         Printf("getProof: could not create pid file for XPD");
      } else {
         fprintf(fpid,"%d\n", pid);
         fclose(fpid);
      }
   }
   Printf("getProof: start / attach the PROOF session ...");

   // Start / attach the session now
   p = TProof::Open(lurl);
   if (!p || !(p->IsValid())) {
      Printf("getProof: starting local session failed");
      if (p) delete p;
      p = 0;
      return p;
   }

   // Return the session
   return p;
#endif
}

Int_t getXrootdPid(Int_t port)
{
   // Get the pid of the started xrootd process
   Int_t pid = -1;
#if defined(__sun)
   const char *com = "-eo pid,comm";
#elif defined(__FreeBSD__) || defined(__OpenBSD__) || defined(__APPLE__)
   const char *com = "ax -w -w";
#else
   const char *com = "-w -w -eo pid,command";
#endif
   TString cmd = Form("ps %s | grep xrootd | grep \"\\-p %d\" | grep xpd-tutorial", com, port);
   FILE *fp = gSystem->OpenPipe(cmd.Data(), "r");
   if (fp) {
      char line[2048], rest[2048];
      while (fgets(line, sizeof(line), fp)) {
         sscanf(line,"%d %s", &pid, rest);
         break;
      }
      gSystem->ClosePipe(fp);
   }
   // Done
   return pid;
}
 getProof.C:1
 getProof.C:2
 getProof.C:3
 getProof.C:4
 getProof.C:5
 getProof.C:6
 getProof.C:7
 getProof.C:8
 getProof.C:9
 getProof.C:10
 getProof.C:11
 getProof.C:12
 getProof.C:13
 getProof.C:14
 getProof.C:15
 getProof.C:16
 getProof.C:17
 getProof.C:18
 getProof.C:19
 getProof.C:20
 getProof.C:21
 getProof.C:22
 getProof.C:23
 getProof.C:24
 getProof.C:25
 getProof.C:26
 getProof.C:27
 getProof.C:28
 getProof.C:29
 getProof.C:30
 getProof.C:31
 getProof.C:32
 getProof.C:33
 getProof.C:34
 getProof.C:35
 getProof.C:36
 getProof.C:37
 getProof.C:38
 getProof.C:39
 getProof.C:40
 getProof.C:41
 getProof.C:42
 getProof.C:43
 getProof.C:44
 getProof.C:45
 getProof.C:46
 getProof.C:47
 getProof.C:48
 getProof.C:49
 getProof.C:50
 getProof.C:51
 getProof.C:52
 getProof.C:53
 getProof.C:54
 getProof.C:55
 getProof.C:56
 getProof.C:57
 getProof.C:58
 getProof.C:59
 getProof.C:60
 getProof.C:61
 getProof.C:62
 getProof.C:63
 getProof.C:64
 getProof.C:65
 getProof.C:66
 getProof.C:67
 getProof.C:68
 getProof.C:69
 getProof.C:70
 getProof.C:71
 getProof.C:72
 getProof.C:73
 getProof.C:74
 getProof.C:75
 getProof.C:76
 getProof.C:77
 getProof.C:78
 getProof.C:79
 getProof.C:80
 getProof.C:81
 getProof.C:82
 getProof.C:83
 getProof.C:84
 getProof.C:85
 getProof.C:86
 getProof.C:87
 getProof.C:88
 getProof.C:89
 getProof.C:90
 getProof.C:91
 getProof.C:92
 getProof.C:93
 getProof.C:94
 getProof.C:95
 getProof.C:96
 getProof.C:97
 getProof.C:98
 getProof.C:99
 getProof.C:100
 getProof.C:101
 getProof.C:102
 getProof.C:103
 getProof.C:104
 getProof.C:105
 getProof.C:106
 getProof.C:107
 getProof.C:108
 getProof.C:109
 getProof.C:110
 getProof.C:111
 getProof.C:112
 getProof.C:113
 getProof.C:114
 getProof.C:115
 getProof.C:116
 getProof.C:117
 getProof.C:118
 getProof.C:119
 getProof.C:120
 getProof.C:121
 getProof.C:122
 getProof.C:123
 getProof.C:124
 getProof.C:125
 getProof.C:126
 getProof.C:127
 getProof.C:128
 getProof.C:129
 getProof.C:130
 getProof.C:131
 getProof.C:132
 getProof.C:133
 getProof.C:134
 getProof.C:135
 getProof.C:136
 getProof.C:137
 getProof.C:138
 getProof.C:139
 getProof.C:140
 getProof.C:141
 getProof.C:142
 getProof.C:143
 getProof.C:144
 getProof.C:145
 getProof.C:146
 getProof.C:147
 getProof.C:148
 getProof.C:149
 getProof.C:150
 getProof.C:151
 getProof.C:152
 getProof.C:153
 getProof.C:154
 getProof.C:155
 getProof.C:156
 getProof.C:157
 getProof.C:158
 getProof.C:159
 getProof.C:160
 getProof.C:161
 getProof.C:162
 getProof.C:163
 getProof.C:164
 getProof.C:165
 getProof.C:166
 getProof.C:167
 getProof.C:168
 getProof.C:169
 getProof.C:170
 getProof.C:171
 getProof.C:172
 getProof.C:173
 getProof.C:174
 getProof.C:175
 getProof.C:176
 getProof.C:177
 getProof.C:178
 getProof.C:179
 getProof.C:180
 getProof.C:181
 getProof.C:182
 getProof.C:183
 getProof.C:184
 getProof.C:185
 getProof.C:186
 getProof.C:187
 getProof.C:188
 getProof.C:189
 getProof.C:190
 getProof.C:191
 getProof.C:192
 getProof.C:193
 getProof.C:194
 getProof.C:195
 getProof.C:196
 getProof.C:197
 getProof.C:198
 getProof.C:199
 getProof.C:200
 getProof.C:201
 getProof.C:202
 getProof.C:203
 getProof.C:204
 getProof.C:205
 getProof.C:206
 getProof.C:207
 getProof.C:208
 getProof.C:209
 getProof.C:210
 getProof.C:211
 getProof.C:212
 getProof.C:213
 getProof.C:214
 getProof.C:215
 getProof.C:216
 getProof.C:217
 getProof.C:218
 getProof.C:219
 getProof.C:220
 getProof.C:221
 getProof.C:222
 getProof.C:223
 getProof.C:224
 getProof.C:225
 getProof.C:226
 getProof.C:227
 getProof.C:228
 getProof.C:229
 getProof.C:230
 getProof.C:231
 getProof.C:232
 getProof.C:233
 getProof.C:234
 getProof.C:235
 getProof.C:236
 getProof.C:237
 getProof.C:238
 getProof.C:239
 getProof.C:240
 getProof.C:241
 getProof.C:242
 getProof.C:243
 getProof.C:244
 getProof.C:245
 getProof.C:246
 getProof.C:247
 getProof.C:248
 getProof.C:249
 getProof.C:250
 getProof.C:251
 getProof.C:252
 getProof.C:253
 getProof.C:254
 getProof.C:255
 getProof.C:256
 getProof.C:257
 getProof.C:258
 getProof.C:259
 getProof.C:260
 getProof.C:261
 getProof.C:262
 getProof.C:263
 getProof.C:264
 getProof.C:265
 getProof.C:266
 getProof.C:267
 getProof.C:268
 getProof.C:269
 getProof.C:270
 getProof.C:271
 getProof.C:272
 getProof.C:273
 getProof.C:274
 getProof.C:275
 getProof.C:276
 getProof.C:277
 getProof.C:278
 getProof.C:279
 getProof.C:280
 getProof.C:281
 getProof.C:282
 getProof.C:283
 getProof.C:284
 getProof.C:285
 getProof.C:286