femul.cpp 68.3 KB
Newer Older
1 2 3 4 5 6
//
// This is femul (previously named WinCtest), a Narval emulator written as a standalone program
//   to help developing and debugging the AGATA data acquisition and analysis (replay) software.
//
// The development started in ~2008, inspired by Joa's C_Test.c (which uses the .so libraries via dlopen, dlsym,...)
//   and has evolved towards an almost complete emulation of the Narval environment.
7
// The main difference/limitation with the Narval implementation is the use of a single process on a single computer.
8 9 10
// To speed-up execution in multi-core computers it is possible to run parallel threads 
//  - in the PSAFilter library using boost:thread or std::future if the compiler upports the c++11 standard 
//  - in the driver program (using boost::thread or std::thread) (if #define WCT_THREADED in ChainLocker.h).
11 12 13 14 15 16 17 18
//
// All libraries used so far in Agata Demonstrator experiments and analyses are available, using the same source code;
//   indeed, a large part of that code has been developed and/or tested by various contributors using this emulator.
//
// A C++ implementation of the EventBuilder replaces that of Narval (which is written in Ada).
//
// The program is supposed to be multi-platform and has been tested in Windows, [Cygwin??] and GNU/Linux.
//
19
// Dino Bazzacco 2008-2014
20 21 22 23 24 25 26 27 28 29
//

#include <cstdlib>
#include <cstdio>
#include <csignal>
#include <ctime>
#include <string>
#include <iostream>
#include <fstream>
#include <vector>
30
#include <algorithm>
31

32 33 34 35
#if OS_TYPE != OS_WINDOWS
# include <unistd.h> 
#endif

36 37 38 39 40
#define FEMBUF_MINSIZE               1024     // Minimum size (bytes) of the data buffers connecting the actors
#define FEMBUF_DEFSIZE      (10*1024*1024)    // Default size (bytes) of the data buffers connecting the actors
#define FEMBUF_MAXSIZE      (30*1024*1024)    // Maximum size (bytes) of the data buffers connecting the actors

#include "commonDefs.h"
41
#include "Misc.h"
42
#include "ChainOfActors.h"
43
#include "ChainLocker.h"                      // WCT_THREADED is  defined in ChainLocker.h
44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62

//enum      EActor     { NONE,         BUILDER,      PRODUCER,     FILTER,       CONSUMER,     DISPATCHER };   // THIS IS NOW DEFINED IN ChainOfActors.h
std::string NActor[] = {"NONE      ", "BUILDER   ", "PRODUCER  ", "FILTER    ", "CONSUMER  ", "DISPATCHER"};

/*********************************************************
The processing chains can have the following actors
BUILDER     EventBuilder          (can be derived from NarvalInterface as a PRODUCER)
PRODUCER    BasicAFP
PRODUCER    CrystalProducerATCA
PRODUCER    AncillaryProducerTCP
FILTER      PreprocessingFilterPSA
FILTER      PSAFilterGridSearch
FILTER      PostPSAFilter
FILTER      AncillaryFilterVME
FILTER      AncillaryFilterATCA
FILTER      GlobalFilter
FILTER      TrackingFilterOFT
FILTER      TrackingFilterMGT
CONSUMER    BasicAFC
63 64
CONSUMER    None           pseudo-actor to close a chain without output
DISPATCHER  BuilderName    pseudo actor to connect the output of a chain to an input queue of a BUILDER
65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88
*********************************************************/

// implemented actors

//  type                                 subtype   identifier
//
//   1  BUILDER                              
#include "EventBuilder.h"               //  10        100

//   2  PRODUCER                                  
#include "BasicAFP.h"                   //  20        200     no mother-daughter model

#include "CrystalProducer.h"            //  21        210
#include "CrystalProducerATCA.h"        //            211

#include "AncillaryProducerTCP.h"       //  22        220     no mother-daughter model

//   3  FILTER
#include "PreprocessingFilter.h"        //  30        300
#include "PreprocessingFilterPSA.h"     //            301

#include "PSAFilter.h"                  //  31        310
#include "PSAFilterGridSearch.h"        //            311

89
#include "AncillaryFilter.h"            //  33        330     must find out why this cannot be included after TrackingFilterMGT.h
90 91 92 93 94 95 96 97 98
#include "AncillaryFilterVME.h"         //            331
#include "AncillaryFilterATCA.h"        //            332

#include "TrackingFilter.h"             //  32        320
#include "TrackingFilterOFT.h"          //            321
#include "TrackingFilterMGT.h"          //            322

#include "PostPSAFilter.h"              //  34        340

99
#ifdef ENABLE_GLOBAL_FILTER
100
#include "GlobalFilter.h"               //  35        350
101
#endif
102 103 104 105 106 107 108 109
//   4  CONSUMER
//        None                          //  40        400     fake, used as last of a chain
#include "BasicAFC.h"                   //  41        410     no mother-daughter model

//   5  DISPATCHER                                            femul mechanism to connect to an EventBuilder
//        BuilderName                   //  50        destination_chain

#ifdef WCT_THREADED
110 111 112 113
  std::vector <thrLib::thread *> chThread;  // pointers of the threads, needed to be able to join them
  thrLib::thread              *ctrlThread;  // pointer of the control thread for cyclic actions
  bool  stopControl = false;                    // to force the control thread to exit
  bool  runThreaded = true;                     // set it to false (from the command line) to run the unthreaded main loop
114
#else
115
  bool  runThreaded = false;            // will of course run unthreaded
116 117 118
#endif

#if defined(COUT_LOCKED)
119
  thrLib::mutex  ioMutex;               // mutex for LOCK_COUT
120 121 122 123 124 125 126 127 128 129 130
#endif

// Replacement of Xavier's variable to ask producers to return from process_block even
// if the buffer is not yet full. This is just to avoid complaints from the compiler, not
// an implementation of the time-out mechanism (which is not very meaningful in off-line).
unsigned int library_timeout = 0;

// to control verbosity of the LogCollector (in topologyConfNew)
#include "CentralLog.h"
#include "LogCollector.h"

131
int   adfVerbose  = 0;                  // 0=LogMessage::kError 1=LogMessage::kWarning 3=LogMessage::kInfo
132 133 134

std::string topologyFile;
std::string confPrefix("Conf/");
135 136
std::string StopFile("StopFile");       // presence of this file in cwd ends the analysis in an ordered way
std::string KillFile("KillFile");       // presence of this file in cwd ends the analysis immediately
137

138 139
int  maxTurn = 0;       // if using threads, the analysis will run for approximately maxTurn seconds
int  theTurn = 0;       // counter of turns
140 141 142 143 144 145
int  nSIGINT = 0;       // count number of SIGINT (CTRL_C)
bool stopSig = false;   // used to check StopFile
bool killSig = false;   // used to check KillFile

bool listKeys = false;  // rudimentary help on the keywords accepted by the various actors

146 147 148
double  wTstart;
double  cTstart;
time_t  tTstart;
149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165

using namespace std;
using namespace ADF;

// the specific analysis is recorded here
vector<ChainOfActors *> theChains;

// this part used only during setup
struct builder_t {
  builder_t(std::string name) : pEventBuilder(NULL), theName(name), numInputs(0), indChain(-1) {}
  EventBuilder *pEventBuilder;
  std::string   theName;
  int           numInputs;
  int           indChain;
};
vector<builder_t *> theBuilders;

166
void showWhat();
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
void getparams(int, char **);
void numparams(char *, int);
void listKeysAndExit();               // call GetParameters(doList=true) and exit
bool checkADFpath();                  // check presence of ADF.conf
int  eventLoop1();                    // non-threaded
int  eventLoop2();                    // threaded
bool topologyRead(std::string);       // reads the topology file
void topologyPrint(int nn = 0);       // listing of the topology
bool topologyConfNew();               // process_config+new
bool topologyInit();                  // process_initialise
bool topologyStart();                 // process_start
bool topologyStop();                  // process_stop
bool topologyDelete();                // call the destructors of the created objects

void threadWorker(int nn);            // managment of PRODUCER/BUILDER  chains in the threaded version
void threadControl();                 // the control thread for cyclic printouts and tests
bool CheckFile(std::string checkFile, bool remove); // check presence of checkFile and delete it

void catch_int(int /*sig_num*/)
{
  nSIGINT++;
  stopSig = true;
  if(nSIGINT > 1)
    killSig = true;
  if(nSIGINT > 2)  // give up immediately if multiple CTRL_C
    exit(EXIT_FAILURE);
  signal(SIGINT, catch_int);
}

int main(int argc, char **argv)
{
  cout << endl;
  cout << "######################################" << endl;
  cout << "# Using Narval actors without Narval #" << endl;
  cout << "######################################" << endl;

203 204
  showWhat();

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
  getparams(argc, argv);

  if(listKeys)
    listKeysAndExit();

  bool ok;

  ok = checkADFpath();
  if(!ok)
    exit(EXIT_FAILURE);

  ok = topologyRead(topologyFile);
  if(!ok)
    exit(EXIT_FAILURE);

  topologyPrint();

  ADF::CrystalInterface::kDefaultLength = defTraceLengthRaw;

  // Because of the static variables used to register and configure the actors in the Narval environment,
  // a flat emulator that creates multiple instances of the same class in the same process, has 2 options:
  // 1) call process_config immediately before creating each of the objects so that the constructors can
  // move the globals to local storage (essentially gConfPath --> fConfPath)
  // 2) create the objects and call process_config and process_initialise in sequence for all of them; in this
  // case it is process_initialise that moves gConfPath to fConfPath
  // In both cases it is not possible to call process_config for all actors and then process_initialise.
  // The present version follows 1), which is similar to the way of doing things in Narval
  // Be aware that to change the way of doing things one has to (slightly) modify the actors.

  // process_config + new
  ok = topologyConfNew();
  if(!ok)
    exit(EXIT_FAILURE);
  topologyPrint();

  ok = topologyInit();
  if(!ok)
    exit(EXIT_FAILURE);

  ok = topologyStart();
  if(!ok)
    exit(EXIT_FAILURE);

  // CNTRL_C can be used to stop execution
  signal(SIGINT, catch_int);
250
  printf("\nAnalysis can be terminated by typing CTRL_C  (or kill -2 PID) \n");
251 252 253 254 255 256 257 258 259 260

//#define DO_IT_AGAIN_LOOP          // enable this symbol to test the stop/start loop in main()
#ifdef DO_IT_AGAIN_LOOP
AGAIN_LOOP:
#endif

  //////////////////////////////////////////////////////////
  /////////////// the execution loop(s) ////////////////////
  //////////////////////////////////////////////////////////

261 262 263 264 265
  wTstart = get_wall_time();
  cTstart = get_cpu_time();
  time(&tTstart);

  string  sstart = ctime(&tTstart); sstart = sstart.substr(0, sstart.size()-1);
266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286
  cout << "\n********** START time : " << sstart << endl;

  CheckFile(StopFile, true);  // remove if present
  CheckFile(KillFile, true);  // remove if present
  nSIGINT = 0;
  stopSig = false;
  killSig = false;
  theTurn = 0;

  ////////////////// EVENT LOOP /////////////////////////
  if(!runThreaded)
    eventLoop1();
  else
    eventLoop2();
  ///////////////////////////////////////////////////////


  //////////////////////////////////////////////////////////
  //////////// end of execution loop ///////////////////////
  //////////////////////////////////////////////////////////

287
  // Statistics of chains
288 289 290 291 292 293 294 295 296 297 298 299 300 301
  cout << endl;
  cout << "chain" << setw(12) << "Started" << setw(12) << "Counted" << setw(12) << "DoSleep" << endl;
  for( size_t ich = 0; ich < theChains.size(); ich++) {
    cout << setw( 5) << theChains[ich]->myIndex;
    cout << setw(12) << theChains[ich]->statStarted;
    cout << setw(12) << theChains[ich]->statCounted;
    cout << setw(12) << theChains[ich]->statDoSleep;
    cout << endl;
  }

  ok = topologyStop();
  if(!ok)
    exit(EXIT_FAILURE);

302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320
  {
    double wTstop = get_wall_time();
    double cTstop = get_cpu_time();
    time_t tTstop; time(&tTstop); 

    double wstot = wTstop - wTstart;
    double cstot = cTstop - cTstart;
    string sstop = ctime(&tTstop); sstop = sstop.substr(0, sstop.size()-1);

    LOCK_COUT;
    cout << endl << endl;
    cout << "********** STOP time : " << sstop << endl;
    cout << "********** " << fixed << setprecision(1) << wstot << " elapsed seconds ("
         <<                  fixed << setprecision(1) << cstot << " CPU seconds)"
         << endl;

    cout << endl;
  }

321 322 323 324 325 326 327 328 329 330 331 332
#ifdef DO_IT_AGAIN_LOOP
  ok = topologyStart();
  if(!ok)
    exit(EXIT_FAILURE);
  goto AGAIN_LOOP;
#endif

  topologyDelete();

  return 1;
}

333 334 335
void showWhat()
{
  cout << endl;
336

337 338 339 340 341 342 343 344 345
#if   OS_TYPE == OS_WINDOWS
  cout << "OS is Windows " << endl;
#elif OS_TYPE == OS_LINUX
  cout << "OS is Linux   " << endl;
#elif OS_TYPE == OS_APPLE
  cout << "OS is Apple   " << endl;
#elif OS_TYPE == OS_CYGWIN
  cout << "OS is Cygwin  " << endl;
#endif
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


#if THR_TYPE == THR_BOOST
  cout << "Using boost   " << BOOST_VERSION/100000 << "_" << (BOOST_VERSION/100)%1000 << "_" << BOOST_VERSION%100 << endl;
#elif THR_TYPE == THR_STD
  cout << "Using std threads" << endl;
#else
  cout << "Not using threads" << endl;
#endif

#if defined(TRF_ROOTTREE) || defined(GLF_ROOTTREE) || defined(ANF_ROOTTREE)
  cout << "Using root    " << ROOT_RELEASE << endl;
#else
  cout << "Not using root" << endl;
#endif

  string sadf = ADF::GetPathToConfFile();
  sadf += "/ADF.conf";
  if( !fileExists(sadf) ) {
    cout << endl;
    cout << "File not found: " << sadf << endl;
    cout << "This file is required to properly initialize the adf library.  Please check" << endl;
    cout << "the definition of ADFPATHCONFFILE in AgataSoftware/include/standalone/Env.h" << endl;
    exit(EXIT_FAILURE);
  }
  else {
    cout << "Library ADF is " << sadf << endl;
  }
374 375
}

376 377 378 379 380 381 382 383 384 385 386
void getparams(int argc, char *argv[])
{
  char *cmd  = NULL;
  int   ok;

  if(argc < 2 ) {
    ok = -1;
  }
  else if(!strcmp(argv[1], "-h")|| !strcmp(argv[1], "--help")) {
    ok = -1;
  }
387
  else if(!strcmp(argv[1], "-k") || !strcmp(argv[1], "--keys")) {
388 389 390 391 392 393 394 395 396 397 398 399
    listKeys = true;
    return;
  }
  else {
    topologyFile = argv[1];
    ok = (argc > 1) ? 1 : 0;
  }
  
  int argn = 2;
  while(ok == 1 && argn < argc) {
    cmd = argv[argn++];
    ok  = 1;
400
    if     (!strcmp(cmd, "-h") || !strcmp(cmd, "--help")) {
401 402
      ok = -1;
    }
403 404 405 406
    else if(!strcmp(cmd, "-k") || !strcmp(cmd, "--keys")) {
      listKeys = true;
      return;
    }
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
    else if(!strcmp(cmd, "-conf")) {
      numparams(cmd, argc-argn-1);
      confPrefix = argv[argn++];
      forceTailSlash(confPrefix);
    }
    else if(!strcmp(cmd, "-turns")) {
      numparams(cmd, argc-argn-1);
      maxTurn = abs(atoi(argv[argn++]));
    }
    else if(!strcmp(cmd, "-nothr") || !strcmp(cmd, "-nothreads")) {
      runThreaded = false;
    }
    else if(!strcmp(cmd, "-vadf")) {
      numparams(cmd, argc-argn-1);
      adfVerbose = abs(atoi(argv[argn++]));
    }
    else {
      ok = 0;
    }
  }

  if(ok < 1) {
    if(ok == 0 && argc > 2) cout << "\nInvalid switch " << argv[argn-1] << endl;

    cout << "\nUsage: " <<  argv[0]  << " TopologyFile  [OPTION]..." << endl;

    cout << "  -h                 print this list and exit" << endl ;
    cout << "  -k                 print the list of keywords accepted by the actors and exit" << endl ;
    cout << "  -conf   conf_dir   name of configuration directory [Conf]" << endl ;
    cout << "  -turns  nn         limit analysis to nn turns (unlimited if <=0) [0]" << endl ;
#ifdef WCT_THREADED
    cout << "  -nothr             run the non-threaded event loop" << endl ;
#endif
    cout << "  -vadf   nn         adf LogMessage level (0=kError, 1=kWarning, 2=kInfo, 3=kOut)" << endl ;
    cout << " " << endl ;
    if(argc > 1 || ok < 0)
      exit(EXIT_FAILURE);
  }

  // echo the command line
  time_t ltime;
  time(&ltime);

  cout << endl;
  cout << "# " << ctime(&ltime);
  cout << "#";
  for(int nn = 0; nn < argc; nn++)
    cout << " " << argv[nn];
  cout << endl << endl;

  cout << "Topology file            " << topologyFile << endl;
  cout << "Configuration directory  " << confPrefix << endl;
  if(maxTurn > 0)
    cout << "Analysis limited to      " << maxTurn << (runThreaded ? " seconds" : " turns") << endl;
#ifdef WCT_THREADED
  if(!runThreaded)
    cout << "Non-threaded main loop   " << endl;
#endif
}

void numparams(char * cmd, int nn)
{
  if(nn >= 0) return;
  nn = -nn;
  printf("error decoding command %s ==> %d parameter(s) missing \n", cmd, nn);
  exit(EXIT_FAILURE);
}

bool checkADFpath()
{
  bool found = false;
  string adfpath;
  if(getenv("ADF_CONF_PATH")) {
    adfpath = getenv("ADF_CONF_PATH");
    forceTailSlash(adfpath);
    adfpath += "ADF.conf";
    found = fileExists(adfpath);
  }
  else {
    cout << "\nThe symbol ADF_CONF_PATH is not set" << endl;
    cout << "Looking for ADF.conf in cwd ...";
    adfpath = "./ADF.conf";
    found = fileExists(adfpath);
    if(found)
      cout << " found"; 
  }

  if(found)
    cout << "\nThe ADF configuration file is   " << adfpath << endl;
  else
    cout << "\nERROR: The ADF configuration file ADF.conf was not found" << endl;

  return found;
}

// read topology file and classify actors as:
//  EActor::BUILDER
//  EActor::PRODUCER
//  EActor::FILTER
//  EActor::CONSUMER
//  EActor::DISPATCHER
bool topologyRead(string topo)
{
  if(topo.size() < 1) {
    cout << "Topology file is missing" << endl;
    return false;
  }

  ifstream ifs(topo.c_str());
  if( !ifs.good() ) {
    cout << "Could not open topology file " << topo << endl;
    return false;
  }

  cout << endl << "Reading topology from --> " << topo << endl;

  bool   loopState = false;
  size_t loopIndValue = 0;
  size_t loopIndActor = 0;
  string         loopSymbol;
  vector<string> loopValues;
  vector<string> loopActors;

530 531 532 533 534 535 536 537
//LOOP CRY 1R 1G 1B 2R 2G 2B 3R 3G 3B 4R 4G 4B
// Chain 3       CRY
// Producer      BasicAFP     1000000
// Filter        PostPSAFilter
// Dispatcher    EventBuilder
//ENDLOOP
//
//Chain 3       Ancillary
538 539
//Producer      AncillaryProducer  5000000
//Filter        AncillaryFilter
540 541 542 543 544 545 546 547
//Dispatcher    EventMerger
//
//Chain 2       Global/
//Builder       EventBuilder 10000000
//Dispatcher    EventMerger
//
//Chain 3       Global/
//Builder       EventMerger  5000000
548
//Filter        TrackingFilter
549
//Consumer      BasicAFC
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

  string line, keyw, data;
  while(true) {
    // read new line or get it from stored loop statements
    loopState &= loopIndValue < loopValues.size();
    if(loopState) {
      line = loopActors.at(loopIndActor++);
      if(loopIndActor >= loopActors.size()) {
        loopIndValue++;
        loopIndActor = 0;
      }
    }
    else {
      if(!getline(ifs, line))
        break;
    }

    if(!stringSplit(line, keyw, data))
      continue;       // empty or comment lines

    if( stringEq(keyw, "Loop") ) {
      cout << line << endl;
      string values, value1, value2;
      if(!stringSplit(data, loopSymbol, values)) {
        cout << "Format is: Loop Name Value1 Value2 ..." << endl;
        return false;
      }
577 578 579
      // reset vectors 
      loopValues.clear();
      loopActors.clear();
580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603
      // tokenize values
      while(stringSplit(values, value1, value2)) {
        loopValues.push_back(value1);
        values = value2;
      }
      // read and store until EndLoop
      bool hasEndLoop = false;
      while(getline(ifs, line)) {
        if(!stringSplit(line, keyw, data))
          continue;       // empty or comment lines
        cout << line << endl;
        if( stringEq(keyw, "EndLoop") || stringEq(keyw, "End_Loop") ) {
          hasEndLoop = true;
          break;
        }
        loopActors.push_back(line);
      }
      if(!hasEndLoop) {
        cout << "Missing ENDLOOP statement" << endl;
          return false;
      }
      loopIndValue = 0;
      loopIndActor = 0;
      loopState = true;
604
      //cout << endl;
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
      continue;
    }

    if( stringEq(keyw, "Chain") ) {
      cout << line;
      string count, conf;
      if(!stringSplit(data, count, conf)) {
        cout << "\nFormat is: Chain   numActors confDir" << endl;
        return false;
      }
      if(loopState && conf==loopSymbol) {   // replace conf with the next entry in loopNames
        conf = loopValues[loopIndValue];
        cout << " ==> " << conf;
      }
      cout << endl;
      int nacts = atoi(count.c_str());
      if(nacts < 2) {
        cout << "There should be at least 2 actors per chain" << endl;
        return false;
      }

      ChainOfActors * pChain  = new ChainOfActors( (int)theChains.size() );

      string lconf, lsize;
      stringSplit(conf, lconf, lsize);
      pChain->confDir = confPrefix+lconf;

      for(int nn = 0; nn < nacts; ) {
        actor theActor(nn);
        // read new line or get it from stored loop statements
        if(loopState) {
          line = loopActors[loopIndActor++];
          if(loopIndActor >= loopActors.size()) {
            loopIndValue++;
            loopIndActor = 0;
          }
        }
        else {
          if(!getline(ifs, line)) {
            cout << "Error reading line " << nn << " of chain " << theChains.size() << endl;
            return false;
          }
        }
        if(!stringSplit(line, keyw, data))
          continue;       // empty or comment lines
         cout << line << endl;

        string lname, lmore;
        stringSplit(data, lname, lmore);        // isolate the extra parts after the name of the library
        theActor.libName = lname;
        theActor.libMore = lmore;
        theActor.libConf = pChain->confDir;
        theActor.sizeOut = FEMBUF_DEFSIZE;      // size set to default value

        if( stringEq(keyw, "BUILDER") ) {
          if(nn) {
            cout << "BUILDER can only be the first actor in a chain" << endl;
            return false;
          }
          theActor.libType = BUILDER;
665 666
          if(lmore.size() > 0)
            theActor.sizeOut = atoi(lmore.c_str());
667 668 669 670 671 672 673 674 675
          if(theActor.sizeOut < FEMBUF_MINSIZE) theActor.sizeOut = FEMBUF_MINSIZE;  // not smaller than this
          if(theActor.sizeOut > FEMBUF_MAXSIZE) theActor.sizeOut = FEMBUF_MAXSIZE;  // not bigger  than this
        }
        else if( stringEq(keyw, "PRODUCER") ) {
          if(nn) {
            cout << "PRODUCER can only be the first actor in a chain" << endl;
            return false;
          }
          theActor.libType = PRODUCER;
676 677
          if(lmore.size() > 0)
            theActor.sizeOut = atoi(lmore.c_str());
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
          if(theActor.sizeOut < FEMBUF_MINSIZE) theActor.sizeOut = FEMBUF_MINSIZE;  // not smaller than this
          if(theActor.sizeOut > FEMBUF_MAXSIZE) theActor.sizeOut = FEMBUF_MAXSIZE;  // not bigger  than this
        }
        else if( stringEq(keyw, "FILTER") ) {
          if(!nn) {
            cout << "FILTER cannot be the first actor in a chain" << endl;
            return false;
          }
          theActor.libType = FILTER;
        }
        else if( stringEq(keyw, "CONSUMER") ) {
          if(!nn) {
            cout << "CONSUMER cannot be the first actor in a chain" << endl;
            return false;
          }
          theActor.libType = CONSUMER;
          if(lmore.size() > 0)
            theActor.libConf += lmore;
        }
        else if( stringEq(keyw, "DISPATCHER") ) {
          if(nn != nacts-1) {
            cout << "DISPATCHER can only be the last actor in a chain" << endl;
            return false;
          }
          theActor.libType = DISPATCHER;
          if(lmore.size() > 0)
            theActor.libConf += lmore;
        }
        else {
          cout << "Bad   keyword  in  " << data << endl;
          cout << "Valid keywords are: Builder Producer Filter Consumer Dispatcher" << endl;
          return false;
        }

        theActor.libItem    = -1;
        theActor.nrvPointer = NULL;
        theActor.evbPointer = NULL;
        pChain->theActors.push_back(theActor);
        pChain->ioBuffsSize = max(pChain->ioBuffsSize, theActor.sizeOut);
        pChain->numActors++;

        nn++; // actor was read correctly

      }
      if(pChain->theActors[nacts-1].libType != CONSUMER && pChain->theActors[nacts-1].libType != DISPATCHER) {
        cout << "The last item of each chain must be CONSUMER or DISPATCHER" << endl;
        return false;
      }
      pChain->myIndex = (int)theChains.size();
      theChains.push_back(pChain);
    }
    else {
      cout << " Invalid keyword: " << keyw  << "  (here, the only valid one is: Chain)" << endl;
      return false;
    }

  }

  for(unsigned int nc = 0; nc < theChains.size(); nc++) {
    ChainOfActors * pChain = theChains[nc];
    for(int na = 0; na < pChain->numActors; na++) {
      actor *pActor = &pChain->theActors[na];
dino's avatar
dino committed
740 741
      if(na)
        pActor->sizeOut = pChain->ioBuffsSize;    // in this way it is possible to have a smaller size for producer
742 743 744
#if 0
      // Tests on the size of the ioBuffers, done in the attempt to avoid buffer overflow in the filters
      // No more needed because ChainOfActors::Run() gives only 3/4 of the actual size to PRODUCERs and BUILDERs
745 746 747 748
      switch (pActor->libType) {
        case BUILDER :
          // This test is due to the fact that after a Builder there is often a TrackingFilter
          // which can produce an ouput buffer size larger than its input 
749
          pActor->sizeOut = min(pActor->sizeOut, (pChain->ioBuffsSize*8)/10);
750 751 752 753 754
          break;
        case PRODUCER :
          // PreprocessingFilter could also produce an ouput larger than the input, but
          // CrystalProducer already takes care of filling its output buffer only by ~80%
          // So, keep the value from the topology, if given, or the default FEMBUF_DEFSIZE
755
          pActor->sizeOut = min(pActor->sizeOut, (pChain->ioBuffsSize*8)/10);
756 757
          break;
      }
758
#endif
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
    }   // loop on actors

  }   // loop on chains

  return true;
}

// simple printout of the topology
void topologyPrint(int nchains)
{
  if(nchains < 1 || nchains > (int)theChains.size())
    nchains = (int)theChains.size();

  cout << endl;
  for(int nc = 0; nc < nchains; nc++) {
    ChainOfActors * pChain = theChains[nc];
    cout << setw(2) << nc << "   "; //<< setw(2) << pChain->numActors;
    cout << "  " << pChain->confDir << endl;
    for(int na = 0; na < pChain->numActors; na++) {
      actor *pActor = &pChain->theActors[na];
      cout << "  " << setw( 3) << na;
      cout << "  " << NActor[pActor->libType];
      cout << "  " << setw( 3) << pActor->libItem;
      cout << "  " << setw(25) << left << pActor->libName << right;
      if(pActor->libType == DISPATCHER || pActor->libName == "None") {
        cout << endl;
        continue;
      }
      cout << "  " << setw(10) << pActor->sizeOut;
      if(pActor->libType == BUILDER)
        cout << "  " << pActor->evbPointer;
      else
        cout << "  " << pActor->nrvPointer;
        cout << "  " << pActor->libConf;
        cout << endl;
    } 
  }
}

// Call GetParameters(doList=true) for the relevant classes to get the list of accepted keys.
void listKeysAndExit()
{
801
  // get rid of adf messages
802 803 804 805 806 807 808
  CentralLog::theCentralLog()->GetCurrentLogCollector()->SetLevelFiltering(LogMessage::kError, (unsigned short)(0));

  // The first object is not deleted because, when this function is called at the very start of the program,
  // the next "new" ends-up in a crash.
  // Apparently AgataConfAgent::gTheGlobalAgent is not reset to NULL by the destructor

  AncillaryProducerTCP      *pa1  = new AncillaryProducerTCP;
809
  pa1->GetParameters("", true);
810 811 812
  //delete pa1; 

  AncillaryFilter           *pa2  = new AncillaryFilter;
813
  pa2->GetParameters("", true);
814 815 816
  delete pa2;

  CrystalProducer           *pp1  = new CrystalProducer;
817
  pp1->GetParameters("", true);
818 819 820
  delete pp1;

  PreprocessingFilter       *pf1  = new PreprocessingFilterPSA;
821
  pf1->GetParameters("", true);
822 823 824
  delete pf1;

  PSAFilter                 *pf2  = new PSAFilterGridSearch;
825
  pf2->GetParameters("", true);
826 827 828
  delete pf2;

  //                           pf2  = new PSAFilterFips;
829
  //pf2->GetParameters("", true);
830 831 832
  //delete pf2;

  PostPSAFilter             *pf3  = new PostPSAFilter;
833
  pf3->GetParameters("", true);
834 835 836
  delete pf3;

  EventBuilder              *pe1  = new EventBuilder("EventBuilder");
837
  pe1->GetParameters("", true);
838 839
  delete pe1;

840
#ifdef ENABLE_GLOBAL_FILTER
841
  GlobalFilter              *pf4 = new GlobalFilter;
842
  pf4->GetParameters("", true);
843
  delete pf4;
844
#endif
845 846

  TrackingFilter            *pf5  = new TrackingFilter;
847
  pf5->GetParameters("", true);
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
  delete pf5;

  exit(EXIT_SUCCESS);
}

#if 1

// process_config + generation of objects
// should change the behaviour to be more compliant to the adf/narval definition
// 1) the topology file should only contain the name of the mother class 
// 2) the actual class should be obtained by the static method MotherClass::process_config(...)
// 3) the object should be created after checking which daughter was given
// See the example for TrackingFilter

// actualClass from configuration
bool topologyConfNew()
{
  // Reduce verbosity of LogCollector
  //CentralLog::theCentralLog()->GetCurrentLogCollector()->SetLevelFiltering(LogMessage::kError, LogMessage::kError);
  //CentralLog::theCentralLog()->GetCurrentLogCollector()->SetLevelFiltering(LogMessage::kError, LogMessage::kWarning);
  CentralLog::theCentralLog()->GetCurrentLogCollector()->SetLevelFiltering(LogMessage::kError, (unsigned short)(adfVerbose));

#define IF_ERRORCONFIG(error_config)  if(error_config) {cout << pActor->libName << "::process_config failed"  << endl; return false;}
#define ELSE_UNKNOWNCLASS(nc)  else {cout << "Unknown class [ " << nc << " " << nc << " ] " << pActor->libName << endl; return false;         }

873
  int numChains = (int)theChains.size();
874 875
  UInt_t error_config = 0;

876
  for(int nc = 0; nc < numChains; nc++) {
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 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046
    ChainOfActors * pChain = theChains[nc];
    cout << "\n-- Calling process_config and instantiating objects for chain " << nc << endl;
    for(int na = 0; na < pChain->numActors; na++) {
      cout << "Actor " << nc << " " << na << " ---> ";
      actor *pActor = &pChain->theActors[na];
      bool printmsg = true;
      switch (pChain->theActors[na].libType) {
        case BUILDER:   //// 1
          // 10
          for(size_t ib = 0; ib < theBuilders.size(); ib++) {
            if(pActor->libName == theBuilders[ib]->theName) {
              cout << pActor->libName << " ..." << endl;
              if(theBuilders[ib]->indChain >= 0 ) {
                cout << "There can be at most one " << pActor->libName << endl;
                return false;
              }
              if(theBuilders[ib]->numInputs < 1 ) {
                cout << pActor->libName << " must have at least one input" << endl;
                return false;
              }
              pActor->libItem = 0;
              //EventBuilder::process_config(pActor->libConf.c_str(), &error_config); // see comment in EventBuilder::process_config()
              EventBuilder::process_config((pActor->libConf+"/"+pActor->libName+".conf").data(), &error_config);
              IF_ERRORCONFIG(error_config);
              pActor->libName = EventBuilder::gActualClass;
              pActor->evbPointer = new EventBuilder(pActor->libName, theBuilders[ib]->numInputs);
#ifdef EVB_INHERITS_FROM_NARVAL_PRODUCER
              pActor->nrvPointer = pActor->evbPointer; 
#endif
              pActor->libItem = 100;
              theBuilders[ib]->pEventBuilder = pActor->evbPointer;
              theBuilders[ib]->indChain = nc;
              break;
            }
            else {
              if(ib == theBuilders.size()-1) {
                // This builder has never (or not yet) been invoked by a DISPATCHER
                cout << "Unknown class [ " << nc << " " << nc << " ] " << pActor->libName << endl;
                return false;
              }
            }
          }
          break;
        case PRODUCER:    //// 2
          // 20
          if(pActor->libName == "BasicAFP") {    // no mother-daughter model
            cout << "BasicAFP ..." << endl;
            BasicAFP::process_config(pActor->libConf.c_str(), &error_config);
            IF_ERRORCONFIG(error_config);
            pActor->nrvPointer = new BasicAFP(nc);
            pActor->libItem    = 200;
          }
          // 21
          else if( pActor->libName == "CrystalProducer" 
            ||     pActor->libName == "CrystalProducerATCA" ) {
            cout << "CrystalProducer ..." << endl;
            CrystalProducer::process_config(pActor->libConf.c_str(), &error_config);
            IF_ERRORCONFIG(error_config);
            pActor->libName = CrystalProducer::gActualClass.empty() ? "CrystalProducer" : CrystalProducer::gActualClass;
            if(pActor->libName == "CrystalProducer") {
              pActor->nrvPointer = new CrystalProducer;
              pActor->libItem    = 210;
            }
            else if(pActor->libName == "CrystalProducerATCA") {
              pActor->nrvPointer = new CrystalProducerATCA;
              pActor->libItem    = 211;
            }
            ELSE_UNKNOWNCLASS(nc);
          }
          // 22
          else if(pActor->libName == "AncillaryProducerTCP") {    //  not necessarily derived from ADF::NarvalProducer
            cout << "AncillaryProducerTCP ..." << endl;
            AncillaryProducerTCP::process_config(pActor->libConf.c_str(), &error_config);
            IF_ERRORCONFIG(error_config);
            pActor->nrvPointer = new AncillaryProducerTCP;
            pActor->libItem    = 220;
          }
          ELSE_UNKNOWNCLASS(nc);
          break;
        case FILTER:   //// 3
          // 30
          if( pActor->libName == "PreprocessingFilter"
           || pActor->libName == "PreprocessingFilterPSA") {
            cout << "PreprocessingFilter ..." << endl;
            PreprocessingFilter::process_config(pActor->libConf.c_str(), &error_config);
            IF_ERRORCONFIG(error_config);
            pActor->libName = PreprocessingFilter::gActualClass.empty() ? "PreprocessingFilter" : PreprocessingFilter::gActualClass;
            if(pActor->libName == "PreprocessingFilter") {
              pActor->nrvPointer = new PreprocessingFilter;
              pActor->libItem    = 300;
            }
            else if(pActor->libName == "PreprocessingFilterPSA") {
              pActor->nrvPointer = new PreprocessingFilterPSA;
              pActor->libItem    = 301;
            }
            ELSE_UNKNOWNCLASS(nc);
          }
          // 31
          else if( pActor->libName == "PSAFilter" 
            ||     pActor->libName == "PSAFilterGridSearch") {
            cout << "PSAFilter ..." << endl;
            PSAFilter::process_config(pActor->libConf.c_str(), &error_config);
            IF_ERRORCONFIG(error_config);
            pActor->libName = PSAFilter::gActualClass.empty() ? "PSAFilter" : PSAFilter::gActualClass;
            if(pActor->libName == "PSAFilter") {
              pActor->nrvPointer = new PSAFilter;
              pActor->libItem    = 310;
            }
            else if(pActor->libName == "PSAFilterGridSearch") {
              pActor->nrvPointer = new PSAFilterGridSearch;
              pActor->libItem    = 311;
            }
          }
          // 32
          else if( pActor->libName == "TrackingFilter" 
              ||   pActor->libName == "TrackingFilterOFT"
              ||   pActor->libName == "TrackingFilterMGT" ) {
            cout << "TrackingFilter ..." << endl;
            TrackingFilter::process_config(pActor->libConf.c_str(), &error_config);
            IF_ERRORCONFIG(error_config);
            pActor->libName = TrackingFilter::gActualClass.empty() ? "TrackingFilter" : TrackingFilter::gActualClass;
            // allow also to use the mother class ??
            if(pActor->libName == "TrackingFilter") {
              pActor->nrvPointer = new TrackingFilter;
              pActor->libItem    = 320;
            }
            else if(pActor->libName == "TrackingFilterOFT") {
              pActor->nrvPointer = new TrackingFilterOFT;
              pActor->libItem    = 321;
            }
            else if(pActor->libName == "TrackingFilterMGT") {
              pActor->nrvPointer = new TrackingFilterMGT;
              pActor->libItem    = 322;
            }
            ELSE_UNKNOWNCLASS(nc);
          }
          // 33
          else if( pActor->libName == "AncillaryFilter" 
            ||     pActor->libName == "AncillaryFilterVME"
            ||     pActor->libName == "AncillaryFilterATCA") {
            cout << "AncillaryFilter ..." << endl;
            AncillaryFilter::process_config(pActor->libConf.c_str(), &error_config);
            IF_ERRORCONFIG(error_config);
            pActor->libName = AncillaryFilter::gActualClass.empty() ? "AncillaryFilter" : AncillaryFilter::gActualClass;
            if(pActor->libName == "AncillaryFilter") {
              pActor->nrvPointer = new AncillaryFilter;
              pActor->libItem    = 330;
            }
            else if(pActor->libName == "AncillaryFilterVME") {
              pActor->nrvPointer = new AncillaryFilterVME;
              pActor->libItem    = 331;
            }
            else if(pActor->libName == "AncillaryFilterATCA") {
              pActor->nrvPointer = new AncillaryFilterATCA;
              pActor->libItem    = 332;
            }
            ELSE_UNKNOWNCLASS(nc);
          }
          // 34
          else if(pActor->libName == "PostPSAFilter") {
            cout << "PostPSAFilter ..." << endl;
            PostPSAFilter::process_config(pActor->libConf.c_str(), &error_config);
            IF_ERRORCONFIG(error_config);
            pActor->libName = PostPSAFilter::gActualClass.empty() ? "PostPSAFilter" : PostPSAFilter::gActualClass;
            if(pActor->libName == "PostPSAFilter") {
              pActor->nrvPointer = new PostPSAFilter;
              pActor->libItem    = 340;
            }
            ELSE_UNKNOWNCLASS(nc);
          }
1047
#ifdef ENABLE_GLOBAL_FILTER
1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059
          // 35
          else if(pActor->libName == "GlobalFilter") {
            cout << "GlobalFilter ..." << endl;
            GlobalFilter::process_config(pActor->libConf.c_str(), &error_config);
            IF_ERRORCONFIG(error_config);
            pActor->libName = GlobalFilter::gActualClass.empty() ? "GlobalFilter" : GlobalFilter::gActualClass;
            if(pActor->libName == "GlobalFilter") {
              pActor->nrvPointer = new GlobalFilter;
              pActor->libItem    = 350;
            }
            ELSE_UNKNOWNCLASS(nc);
          }
1060
#endif
1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186
          ELSE_UNKNOWNCLASS(nc);
          break;
        case CONSUMER:    //// 4
          // 40
          if(pActor->libName == "None" || pActor->libName == "none") {   // not a narval actor
            cout << "None ---" << endl;
            pActor->libName = "None";
            pActor->nrvPointer = NULL;
            pActor->libItem    = 410;
            printmsg = false;
          }
          // 41
          else if(pActor->libName == "BasicAFC") {    // no mother-daughter model
            cout << "BasicAFC ..." << endl;
            BasicAFC::process_config(pActor->libConf.c_str(), &error_config);
            IF_ERRORCONFIG(error_config);
            pActor->nrvPointer = new BasicAFC(nc);
            pActor->libItem    = 400;
          }
          ELSE_UNKNOWNCLASS(nc);
          break;
        case DISPATCHER:    //// 5                                        // not a narval actor
          { // check if destination already present
            int indPresent = -1;
            for(size_t ib = 0; ib < theBuilders.size(); ib++) {
              if(pActor->libName == theBuilders[ib]->theName) {
                indPresent = int(ib);
                break;
              }
            }
            if(indPresent < 0) { // add a new one
              builder_t *abuilder = new builder_t(pActor->libName);
              theBuilders.push_back(abuilder);
            }
          }
          for(size_t ib = 0; ib < theBuilders.size(); ib++) {
            if(pActor->libName == theBuilders[ib]->theName) {
              cout << theBuilders[ib]->theName << " ---" << endl;
              pActor->nrvPointer = NULL;
              pActor->libItem    = Int_t(ib);
              pChain->indQueue   = theBuilders[ib]->numInputs;
              theBuilders[ib]->numInputs++;
              printmsg = false;
              break;
            }
          }
          break;
        default:
          cout << "Unknown type for chain " << nc << " actor " << na << endl;
          return false;
      }
      if(printmsg)
        cout << "Actor " << nc << " " << na << " done" << endl;
    }
    pChain->thisLocker = new ChainLocker(nc, runThreaded);   // instantiate the (possibly fake) lock for this chain
    cout << "-- Chain " << nc << " done" << endl;
  }

  for(size_t ib = 0; ib < theBuilders.size(); ib++) {
    if(theBuilders[ib]->indChain < 0) {
      cout << "Class " << theBuilders[ib]->theName << " has not been instantiated"  << endl;
      return false;
    }
  }

  // Mark presence of a BUILDER and/or a DISPATCHER
  for(size_t nc = 0; nc < theChains.size(); nc++) {
    ChainOfActors * pChain = theChains[nc];
    pChain->hasBuilder    = false;
    pChain->hasDispatcher = false;
    for(int na = 0; na < pChain->numActors; na++) {
      actor *pActor = &pChain->theActors[na];
      if(pActor->libType == BUILDER) {
        pChain->hasBuilder = true;
      }
      if(pActor->libType == DISPATCHER) {
        pChain->hasDispatcher = true;
      }
    }
  }
  // Link the dispatchers to their builder chains
  for(size_t nc = 0; nc < theChains.size(); nc++) {
    ChainOfActors * pChain = theChains[nc];
    if(pChain->hasDispatcher) {
      // look for its builder
      actor *pActor = &pChain->theActors[pChain->numActors-1];
      for(size_t ib = 0; ib < theBuilders.size(); ib++) {
        if( pActor->libName == theBuilders[ib]->theName ) {
          pChain->indBuilder = theBuilders[ib]->indChain;
          pChain->ptrBuilder = theBuilders[ib]->pEventBuilder;
          pActor->evbPointer = theBuilders[ib]->pEventBuilder;
          pChain->pchBuilder = theChains[pChain->indBuilder];
          pActor->libItem    = theBuilders[ib]->indChain;
        }
      }
    }
  }
  // link the builders to their dispatching chains
  for(size_t nc = 0; nc < theChains.size(); nc++) {
    ChainOfActors * pChain = theChains[nc];
    if(pChain->hasBuilder) {
      for(size_t ic = 0; ic < theChains.size(); ic++) {
        if(ic != nc) {
          ChainOfActors * iChain = theChains[ic];
          if(iChain->hasDispatcher && iChain->indBuilder==nc)
            pChain->pchProducers.push_back(iChain);
        }
      }
    }
  }

  cout << "\nAll requested objects have been instantiated" << endl;

  return true;
}

#else

// Actual class from Topology
bool topologyConfNew()
{
  // Reduce verbosity of LogCollector
  //CentralLog::theCentralLog()->GetCurrentLogCollector()->SetLevelFiltering(LogMessage::kError, LogMessage::kError);
  //CentralLog::theCentralLog()->GetCurrentLogCollector()->SetLevelFiltering(LogMessage::kError, LogMessage::kWarning);
  CentralLog::theCentralLog()->GetCurrentLogCollector()->SetLevelFiltering(LogMessage::kError, (unsigned short)(adfVerbose));

1187
  int numChains = (int)theChains.size();
1188 1189
  UInt_t error_config = 0;

1190
  for(int nc = 0; nc < numChains; nc++) {
1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307
    ChainOfActors * pChain = theChains[nc];
    cout << "\n Calling process_config and instantiating objects for chain " << nc << endl;
    for(int na = 0; na < pChain->numActors; na++) {
      cout << "Actor " << nc << " " << na << " ---> ";
      actor *pActor = &pChain->theActors[na];
      bool printmsg = true;
      switch (pChain->theActors[na].libType) {
        case BUILDER:
          for(size_t ib = 0; ib < theBuilders.size(); ib++) {
            if(pActor->libName == theBuilders[ib]->theName) {
              cout << pActor->libName << " ..." << endl;
              if(theBuilders[ib]->indChain >= 0 ) {
                cout << "There can be at most one " << pActor->libName << endl;
                return false;
              }
              if(theBuilders[ib]->numInputs < 1 ) {
                cout << pActor->libName << " must have at least one input" << endl;
                return false;
              }
              pActor->libItem = 0;
              //EventBuilder::process_config(pActor->libConf.c_str(), &error_config); // see comment in EventBuilder::process_config()
              EventBuilder::process_config((pActor->libConf+"/"+pActor->libName+".conf").data(), &error_config);
              if(error_config) {cout << pActor->libName << "::process_config failed"  << endl; return false;}
              pActor->evbPointer = new EventBuilder(pActor->libName, theBuilders[ib]->numInputs);
#ifdef EVB_INHERITS_FROM_NARVAL_PRODUCER
              pActor->nrvPointer = pActor->evbPointer; 
#endif
              theBuilders[ib]->pEventBuilder = pActor->evbPointer;
              theBuilders[ib]->indChain = nc;
              break;
            }
            else {
              if(ib == theBuilders.size()-1) {
                // This builder has never (or not yet) been invoked by a DISPATCHER
                cout << "Unknown class [ " << nc << " " << nc << " ] " << pActor->libName << endl;
                return false;
              }
            }
          }
          break;
        case PRODUCER:
          if(pActor->libName == "BasicAFP") {
            cout << "BasicAFP ..." << endl;
            BasicAFP::process_config(pActor->libConf.c_str(), &error_config);
            if(error_config) {cout << pActor->libName << "::process_config failed"  << endl; return false;}
            pActor->nrvPointer = new BasicAFP(nc);
            pActor->libItem    = 0;
          }
          else if(pActor->libName == "CrystalProducerATCA") {
            cout << "CrystalProducerATCA ..." << endl;
            CrystalProducer::process_config(pActor->libConf.c_str(), &error_config);
            if(error_config) {cout << pActor->libName << "::process_config failed"  << endl; return false;}
            pActor->nrvPointer = new CrystalProducerATCA;
            pActor->libItem    = 1;
          }
          else if(pActor->libName == "AncillaryProducerTCP") {
            cout << "AncillaryProducerTCP ..." << endl;
            AncillaryProducerTCP::process_config(pActor->libConf.c_str(), &error_config);
            if(error_config) {cout << pActor->libName << "::process_config failed"  << endl; return false;}
            pActor->nrvPointer = new AncillaryProducerTCP;
            pActor->libItem    = 2;
          }
          else {
            cout << "Unknown class [ " << nc << " " << nc << " ] " << pActor->libName << endl;
            return false;
          }
          break;
        case FILTER:
          if(pActor->libName == "PreprocessingFilterPSA") {
            cout << "PreprocessingFilterPSA ..." << endl;
            PreprocessingFilter::process_config(pActor->libConf.c_str(), &error_config);
            if(error_config) {cout << pActor->libName << "::process_config failed"  << endl; return false;}
            pActor->nrvPointer = new PreprocessingFilterPSA;
            pActor->libItem    = 0;
          }
          else if(pActor->libName == "PSAFilterGridSearch") {
            cout << "PSAFilterGridSearch ..." << endl;
            PSAFilter::process_config(pActor->libConf.c_str(), &error_config);
            if(error_config) {cout << pActor->libName << "::process_config failed"  << endl; return false;}
            pActor->nrvPointer = new PSAFilterGridSearch;
            pActor->libItem    = 1;
          }
          else if(pActor->libName == "TrackingFilterOFT") {
            cout << "TrackingFilterOFT ..." << endl;
            TrackingFilter::process_config(pActor->libConf.c_str(), &error_config);
            if(error_config) {cout << pActor->libName << "::process_config failed"  << endl; return false;}
            pActor->nrvPointer = new TrackingFilterOFT;
            pActor->libItem    = 2;
          }
          else if(pActor->libName == "AncillaryFilterVME") {
            cout << "AncillaryFilterVME ..." << endl;
            AncillaryFilter::process_config(pActor->libConf.c_str(), &error_config);
            if(error_config) {cout << pActor->libName << "::process_config failed"  << endl; return false;}
            pActor->nrvPointer = new AncillaryFilterVME;
            pActor->libItem    = 3;
          }
          else if(pActor->libName == "AncillaryFilterATCA") {
            cout << "AncillaryFilterATCA ..." << endl;
            AncillaryFilter::process_config(pActor->libConf.c_str(), &error_config);
            if(error_config) {cout << pActor->libName << "::process_config failed"  << endl; return false;}
            pActor->nrvPointer = new AncillaryFilterATCA;
            pActor->libItem    = 4;
          }
          else if(pActor->libName == "TrackingFilterMGT") {
            cout << "TrackingFilterMGT ..." << endl;
            TrackingFilter::process_config(pActor->libConf.c_str(), &error_config);
            if(error_config) {cout << pActor->libName << "::process_config failed"  << endl; return false;}
            pActor->nrvPointer = new TrackingFilterMGT;
            pActor->libItem    = 5;
          }
          else if(pActor->libName == "PostPSAFilter") {
            cout << "PostPSAFilter ..." << endl;
            PostPSAFilter::process_config(pActor->libConf.c_str(), &error_config);
            if(error_config) {cout << pActor->libName << "::process_config failed"  << endl; return false;}
            pActor->nrvPointer = new PostPSAFilter;
            pActor->libItem    = 6;
          }
1308
#ifdef ENABLE_GLOBAL_FILTER
1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319
          else if(pActor->libName == "GlobalFilter") {
            cout << "GlobalFilter ..." << endl;
            GlobalFilter::process_config(pActor->libConf.c_str(), &error_config);
            if(error_config) {cout << pActor->libName << "::process_config failed"  << endl; return false;}
            pActor->nrvPointer = new GlobalFilter;
            pActor->libItem    = 6;
          }
          else {
            cout << "Unknown class [ " << nc << " " << nc << " ] " << pActor->libName << endl;
            return false;
          }
1320
#endif
1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444
          break;
        case CONSUMER:
          if(pActor->libName == "None" || pActor->libName == "none") {
            cout << "None ---" << endl;
            pActor->libName = "None";
            pActor->nrvPointer = NULL;
            pActor->libItem    = 0;
            printmsg = false;
          }
          else if(pActor->libName == "BasicAFC") {
            cout << "BasicAFC ..." << endl;
            BasicAFC::process_config(pActor->libConf.c_str(), &error_config);
            if(error_config) {cout << pActor->libName << "::process_config failed"  << endl; return false;}
            pActor->nrvPointer = new BasicAFC(nc);
            pActor->libItem    = 1;
          }
          else {
            cout << "Unknown class [ " << nc << " " << nc << " ] " << pActor->libName << endl;
            return false;
          }
          break;
        case DISPATCHER:
          { // check if destination already present
            int indPresent = -1;
            for(size_t ib = 0; ib < theBuilders.size(); ib++) {
              if(pActor->libName == theBuilders[ib]->theName) {
                indPresent = int(ib);
                break;
              }
            }
            if(indPresent < 0) { // add a new one
              builder_t *abuilder = new builder_t(pActor->libName);
              theBuilders.push_back(abuilder);
            }
          }
          for(size_t ib = 0; ib < theBuilders.size(); ib++) {
            if(pActor->libName == theBuilders[ib]->theName) {
              cout << theBuilders[ib]->theName << " ---" << endl;
              pActor->nrvPointer = NULL;
              pActor->libItem    = Int_t(ib);
              pChain->indQueue   = theBuilders[ib]->numInputs;
              theBuilders[ib]->numInputs++;
              printmsg = false;
              break;
            }
          }
          break;
        default:
          cout << "Unknown type for chain " << nc << " actor " << na << endl;
          return false;
      }
      if(printmsg)
        cout << "Actor " << nc << " " << na << " done" << endl;
    }
    pChain->thisLocker = new ChainLocker(nc, runThreaded);   // instantiate the (possibly fake) lock for this chain
    cout << "Chain " << nc << " done" << endl;
  }

  for(size_t ib = 0; ib < theBuilders.size(); ib++) {
    if(theBuilders[ib]->indChain < 0) {
      cout << "Class " << theBuilders[ib]->theName << " has not been instantiated"  << endl;
      return false;
    }
  }

  // Mark presence of a BUILDER and/or a DISPATCHER
  for(size_t nc = 0; nc < theChains.size(); nc++) {
    ChainOfActors * pChain = theChains[nc];
    pChain->hasBuilder    = false;
    pChain->hasDispatcher = false;
    for(int na = 0; na < pChain->numActors; na++) {
      actor *pActor = &pChain->theActors[na];
      if(pActor->libType == BUILDER) {
        pChain->hasBuilder = true;
      }
      if(pActor->libType == DISPATCHER) {
        pChain->hasDispatcher = true;
      }
    }
  }
  // Link the dispatchers to their builder chains
  for(size_t nc = 0; nc < theChains.size(); nc++) {
    ChainOfActors * pChain = theChains[nc];
    if(pChain->hasDispatcher) {
      // look for its builder
      actor *pActor = &pChain->theActors[pChain->numActors-1];
      for(size_t ib = 0; ib < theBuilders.size(); ib++) {
        if( pActor->libName == theBuilders[ib]->theName ) {
          pChain->indBuilder = theBuilders[ib]->indChain;
          pChain->ptrBuilder = theBuilders[ib]->pEventBuilder;
          pActor->evbPointer = theBuilders[ib]->pEventBuilder;
          pChain->pchBuilder = theChains[pChain->indBuilder];;
        }
      }
    }
  }
  // link the builders to their dispatching chains
  for(size_t nc = 0; nc < theChains.size(); nc++) {
    ChainOfActors * pChain = theChains[nc];
    if(pChain->hasBuilder) {
      for(size_t ic = 0; ic < theChains.size(); ic++) {
        if(ic != nc) {
          ChainOfActors * iChain = theChains[ic];
          if(iChain->hasDispatcher && iChain->indBuilder==nc)
            pChain->pchProducers.push_back(iChain);
        }
      }
    }
  }

  cout << "\nAll requested objects have been instantiated" << endl;

  return true;
}
#endif

// process_initialise
bool topologyInit()
{
  unsigned int error_config;
  unsigned int error_init;

  for(unsigned int nc = 0; nc < theChains.size(); nc++) {
    ChainOfActors * pChain = theChains[nc];
1445
    cout << "\n INITIALIZING CHAIN " << nc << endl;
1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670 1671 1672 1673
    bool printmsg = true;
    for(int na = 0; na < pChain->numActors; na++) {
      error_config = 0; error_init = 0;
      actor *pActor = &pChain->theActors[na];
      if(!pActor->nrvPointer && !pActor->evbPointer)
        continue;
      printmsg = true;

      switch (pActor->libType) {

        case BUILDER :
          if(!pActor->evbPointer) {
            error_config = 100;
            break;
          }
          pActor->evbPointer->process_initialise(&error_init);
          // add info about the feeding chains;
          for(size_t np = 0; np < pChain->pchProducers.size(); np++) {
            pActor->evbPointer->setChain(int(np), pChain->pchProducers[np]->thisLocker);
          }
          break;

        case PRODUCER :
        case FILTER :
          if(!pActor->nrvPointer) {
            error_config = 100;
            break;
          }
          pActor->nrvPointer->process_initialise(&error_init);
          break;

        case CONSUMER :
          if(pActor->nrvPointer) { // initialize only real consumer; do nothing for None
            pActor->nrvPointer->process_initialise(&error_init);
          }
          else
            printmsg = false;
          break;

        case DISPATCHER :
          printmsg = false;
          break;

        // Unknown