Missing #ifdef ZMQ added in AliEveEventManager.cxx
[u/mrichter/AliRoot.git] / EVE / EveBase / AliEveEventManager.cxx
index 68f9e75..bb2bab6 100644 (file)
@@ -1,4 +1,4 @@
-// $Id$
+// $Id: AliEveEventManager.cxx 64557 2013-10-16 20:03:08Z hristov $
 // Main authors: Matevz Tadel & Alja Mrak-Tadel: 2006, 2007
 
 /**************************************************************************
@@ -10,6 +10,8 @@
 #include "AliEveEventManager.h"
 #include "AliEveEventSelector.h"
 #include "AliEveMacroExecutor.h"
+#include "AliEveConfigManager.h"
+#include "AliEveVSDCreator.h"
 
 #include <THashList.h>
 #include <TEveElement.h>
 #include <TEnv.h>
 #include <TString.h>
 #include <TMap.h>
+#include <TROOT.h>
 
+#ifdef ZMQ
+#include "AliStorageEventManager.h"
+#include "AliOnlineReconstructionUtil.h"
+#include "AliGRPPreprocessor.h"
+#endif
+
+using std::cout;
+using std::endl;
+using std::vector;
 //==============================================================================
 //==============================================================================
 // AliEveEventManager
@@ -96,11 +108,14 @@ Bool_t AliEveEventManager::fgAssertAOD       = kFALSE;
 Bool_t AliEveEventManager::fgAssertRaw       = kFALSE;
 
 TString  AliEveEventManager::fgESDFileName("AliESDs.root");
+AliEveEventManager::EVisibleESDTrees  AliEveEventManager::fgESDvisibleTrees(AliEveEventManager::kOfflineTree);
 TString  AliEveEventManager::fgESDfriendsFileName("AliESDfriends.root");
 TString  AliEveEventManager::fgAODFileName("AliAOD.root");
 TString  AliEveEventManager::fgGAliceFileName("galice.root");
 TString  AliEveEventManager::fgRawFileName("raw.root");
 TString  AliEveEventManager::fgCdbUri;
+TString  AliEveEventManager::fgSpecificCdbUriValue;
+TString  AliEveEventManager::fgSpecificCdbUriPath;
 
 TList*   AliEveEventManager::fgAODfriends = 0;
 
@@ -114,103 +129,285 @@ Bool_t   AliEveEventManager::fgUniformField = kFALSE;
 AliEveEventManager* AliEveEventManager::fgMaster  = 0;
 AliEveEventManager* AliEveEventManager::fgCurrent = 0;
 
-void AliEveEventManager::InitInternals()
-{
-    // Initialize internal members.
-
-    static const TEveException kEH("AliEveEventManager::InitInternals ");
-
-    if (fgCurrent != 0)
-    {
-        throw(kEH + "Dependent event-managers should be created via static method AddDependentManager().");
-    }
-
-    if (fgMaster == 0)
-    {
-        fgMaster = this;
-    }
-
-    fgCurrent = this;
-
-    fAutoLoadTimer = new TTimer;
-    fAutoLoadTimer->Connect("Timeout()", "AliEveEventManager", this, "AutoLoadNextEvent()");
-    fAutoLoadTimer->Connect("Timeout()", "AliEveEventManager", this, "Timeout()");
-
-    fExecutor = new AliEveMacroExecutor;
-
-    fTransients = new TEveElementList("Transients", "Transient per-event elements.");
-    fTransients->IncDenyDestroy();
-    gEve->AddToListTree(fTransients, kFALSE);
-
-    fTransientLists = new TEveElementList("Transient Lists", "Containers of transient elements.");
-    fTransientLists->IncDenyDestroy();
-    gEve->AddToListTree(fTransientLists, kFALSE);
-
-    fPEventSelector = new AliEveEventSelector(this);
-
-    fGlobal = new TMap; fGlobal->SetOwnerKeyValue();
-}
-
 AliEveEventManager::AliEveEventManager(const TString& name, Int_t ev) :
     TEveEventManager(name, ""),
-
     fEventId(-1),
     fRunLoader (0),
-    fESDFile   (0), fESDTree (0), fESD (0),
+    fESDFile   (0), fESDTree (0), fHLTESDTree(0), fESD (0),
     fESDfriend (0), fESDfriendExists(kFALSE),
     fAODFile   (0), fAODTree (0), fAOD (0),
     fRawReader (0), fEventInfo(),
-    fAutoLoad  (kFALSE), fAutoLoadTime (5),      fAutoLoadTimer(0),
+    fAutoLoad  (kFALSE),fLoopMarked(kFALSE), fAutoLoadTime (5),      fAutoLoadTimer(0),
     fIsOpen    (kFALSE), fHasEvent     (kFALSE), fExternalCtrl (kFALSE),
     fGlobal    (0), fGlobalReplace (kTRUE), fGlobalUpdate (kTRUE),
     fExecutor    (0), fTransients(0), fTransientLists(0),
     fPEventSelector(0),
     fSubManagers (0),
-    fAutoLoadTimerRunning(kFALSE)
+    fAutoLoadTimerRunning(kFALSE),
+    fMutex(new TMutex()),
+    fgSubSock(EVENTS_SERVER_SUB),
+    fCurrentRun(-1),
+    fEventInUse(1),
+    fWritingToEventIndex(0),
+    fIsNewEventAvaliable(false),
+       fOnlineMode(kFALSE),
+    fStorageDown(false),
+    fFinished(false)
 {
     // Constructor with event-id.
+  if (0 == name.CompareTo("online")) {fOnlineMode = kTRUE;}
+  else{fOnlineMode = kFALSE;}  
+  
+  InitInternals();
 
-    InitInternals();
-
-    Open();
-    if (ev >= 0)
+  Open();
+  if (ev >= 0)
     {
         GotoEvent(ev);
     }
+    
+#ifdef ZMQ
+    if(fOnlineMode)
+      {
+    cout<<"ZMQ FOUND. Starting subscriber thread."<<endl;
+    fEventListenerThread = new TThread("fEventListenerThread",DispatchEventListener,(void*)this);
+    fEventListenerThread->Run();
+    
+    // fStorageManagerWatcherThread = new TThread("fStorageManagerWatcherThread",DispatchStorageManagerWatcher,(void*)this);
+    //fStorageManagerWatcherThread->Run();
+      }
+#else
+    cout<<"NO ZMQ FOUND. Online events not avaliable."<<endl;
+#endif
 }
 
 AliEveEventManager::~AliEveEventManager()
 {
     // Destructor.
+    
+    fFinished = true;
+    if(fEventListenerThread)
+    {
+        fEventListenerThread->Join();
+        fEventListenerThread->Kill();
+        delete fEventListenerThread;
+        cout<<"listener thread killed and deleted"<<endl;
+    }
+    if(fStorageManagerWatcherThread)
+    {
+        fStorageManagerWatcherThread->Join();
+        fStorageManagerWatcherThread->Kill();
+        delete fStorageManagerWatcherThread;
+        cout<<"storage watcher thread killed and deleted"<<endl;
+    }
+    
     fAutoLoadTimer->Stop();
     fAutoLoadTimer->Disconnect("Timeout");
+    fAutoLoadTimer->Disconnect("AutoLoadNextEvent");
 
-    delete fSubManagers;
+    if(fSubManagers){delete fSubManagers;}
+    if(fMutex){delete fMutex;}
+    if (fIsOpen){Close();}
 
-    if (fIsOpen)
+//    fTransients->DecDenyDestroy();
+//    fTransients->Destroy();
+
+//    fTransientLists->DecDenyDestroy();
+//    fTransientLists->Destroy();
+
+    //delete fExecutor;
+}
+
+void AliEveEventManager::GetNextEvent()
+{
+#ifdef ZMQ
+  if(!fOnlineMode){return;}
+  cout<<"\n\nGet next event called\n\n"<<endl;
+
+    AliStorageEventManager *eventManager = AliStorageEventManager::GetEventManagerInstance();
+    eventManager->CreateSocket(EVENTS_SERVER_SUB);
+    eventManager->CreateSocket(SERVER_COMMUNICATION_REQ);
+    
+    fCurrentEvent[0]=0;
+    fCurrentEvent[1]=0;
+
+    AliESDEvent *tmpEvent = NULL;
+    
+    // get list of marked events:
+    struct listRequestStruct list;
+
+    list.runNumber[0]=0;
+    list.runNumber[1]=999999;
+    list.eventNumber[0]=0;
+    list.eventNumber[1]=999999;
+    list.marked[0]=1;
+    list.marked[1]=1;
+    list.multiplicity[0]=0;
+    list.multiplicity[1]=999999;
+    strcpy(list.system[0],"p-p");
+    strcpy(list.system[1],"");
+    
+    struct serverRequestStruct *requestMessage = new struct serverRequestStruct;
+    requestMessage->messageType = REQUEST_LIST_EVENTS;
+    requestMessage->list = list;
+    
+    eventManager->Send(requestMessage,SERVER_COMMUNICATION_REQ);
+    vector<serverListStruct> receivedList = eventManager->GetServerListVector(SERVER_COMMUNICATION_REQ,3000);
+    
+    cout<<"EVENT DISPLAY -- received list of marked events"<<endl;
+    
+    for(int i=0;i<receivedList.size();i++)
     {
-        Close();
+        cout<<"ev:"<<receivedList[i].eventNumber<<endl;
     }
+    
+    int iter=0;
+    while(!fFinished)
+    {
+      cout<<"not finished"<<endl;
+        if(!fLoopMarked || receivedList.size()<=0)
+        {
+            cout<<"taking event from reco server"<<endl;
+            tmpEvent = eventManager->GetEvent(EVENTS_SERVER_SUB,5000);
+           cout<<"after get event"<<endl;
+            if(!tmpEvent){sleep(1);}
+        }
+        else
+        {
+            cout<<"taking event from storage manager"<<endl;
+            if(iter<receivedList.size())
+            {
+                cout<<"i:"<<iter<<endl;
+                struct eventStruct mark;
+                mark.runNumber = receivedList[iter].runNumber;
+                mark.eventNumber = receivedList[iter].eventNumber;
+             
+                requestMessage->messageType = REQUEST_GET_EVENT;
+                requestMessage->event = mark;
+                
+                eventManager->Send(requestMessage,SERVER_COMMUNICATION_REQ);
+                tmpEvent = eventManager->GetEvent(SERVER_COMMUNICATION_REQ);
+
+                iter++;
+                sleep(1);
+            }
+            else{iter=0;}
+        }
+        
+        if(tmpEvent)
+        {
+            cout<<"tmpEvent:"<<tmpEvent->GetRunNumber()<<endl;
+            if(tmpEvent->GetRunNumber()>=0)
+            {
+                fMutex->Lock();
+                if(fEventInUse == 0){fWritingToEventIndex = 1;}
+                else if(fEventInUse == 1){fWritingToEventIndex = 0;}
+                cout<<"Received new event:"<<tmpEvent->GetEventNumberInFile()<<endl;
+                if(fCurrentEvent[fWritingToEventIndex])
+                {
+                    delete fCurrentEvent[fWritingToEventIndex];
+                    fCurrentEvent[fWritingToEventIndex]=0;
+                }
+                fCurrentEvent[fWritingToEventIndex] = tmpEvent;
+                fIsNewEventAvaliable = true;
+                NewEventLoaded();
+                fMutex->UnLock();
+            }
+        }
+        else{cout<<"didn't receive new event"<<endl;}
+     
+    }
+    delete requestMessage;
+    
+#endif
+}
 
-    fTransients->DecDenyDestroy();
-    fTransients->Destroy();
+void AliEveEventManager::CheckStorageStatus()
+{
+#ifdef ZMQ
+  if(!fOnlineMode){return;}
 
-    fTransientLists->DecDenyDestroy();
-    fTransientLists->Destroy();
+    AliEveConfigManager *configManager = AliEveConfigManager::GetMaster();
+    configManager->ConnectEventManagerSignals();
+    
+    AliStorageEventManager *eventManager = AliStorageEventManager::GetEventManagerInstance();
+    eventManager->CreateSocket(CLIENT_COMMUNICATION_REQ);
+    
+    struct clientRequestStruct *request = new struct clientRequestStruct;
+    request->messageType = REQUEST_CONNECTION;
+    
+    while (!fFinished)
+    {
+        if(eventManager->Send(request,CLIENT_COMMUNICATION_REQ,5000))
+        {
+            StorageManagerOk();
+            long response = eventManager->GetLong(CLIENT_COMMUNICATION_REQ);
+           fStorageDown = kFALSE;
+        }
+        else
+        {
+            StorageManagerDown();
+            cout<<"WARNING -- Storage Manager is DOWN!!"<<endl;
+            fStorageDown = kTRUE;
+        }
+        sleep(1);
+    }
+    
+    AliEveEventManager *manager = AliEveEventManager::GetCurrent();
+    manager->Disconnect("StorageManagerOk");
+    manager->Disconnect("StorageManagerDown");
+    
+#endif
+}
 
-    //delete fExecutor;
+void AliEveEventManager::InitInternals()
+{
+    // Initialize internal members.
+    
+    static const TEveException kEH("AliEveEventManager::InitInternals ");
+    
+    if (fgCurrent != 0)
+    {
+        throw(kEH + "Dependent event-managers should be created via static method AddDependentManager().");
+    }
+    
+    if (fgMaster == 0)
+    {
+        fgMaster = this;
+    }
+    
+    fgCurrent = this;
+    
+    fAutoLoadTimer = new TTimer;
+    fAutoLoadTimer->Connect("Timeout()", "AliEveEventManager", this, "AutoLoadNextEvent()");
+    fAutoLoadTimer->Connect("Timeout()", "AliEveEventManager", this, "Timeout()");
+    
+    fExecutor = new AliEveMacroExecutor;
+    
+    fTransients = new TEveElementList("Transients", "Transient per-event elements.");
+    fTransients->IncDenyDestroy();
+    gEve->AddToListTree(fTransients, kFALSE);
+    
+    fTransientLists = new TEveElementList("Transient Lists", "Containers of transient elements.");
+    fTransientLists->IncDenyDestroy();
+    gEve->AddToListTree(fTransientLists, kFALSE);
+    
+    fPEventSelector = new AliEveEventSelector(this);
+    
+    fGlobal = new TMap; fGlobal->SetOwnerKeyValue();
 }
 
 /******************************************************************************/
 
-void AliEveEventManager::SetESDFileName(const TString& esd)
+void AliEveEventManager::SetESDFileName(const TString& esd, EVisibleESDTrees shown)
 {
+    fgESDvisibleTrees = shown;
     // Set file-name for opening ESD, default "AliESDs.root".
     if (esd.IsNull()) return;
-   
+
     fgESDFileName = esd;
     if (esd.EndsWith(".zip")) fgESDFileName.Form("%s#AliESDs.root",esd.Data());
-    
+
 }
 
 void AliEveEventManager::SetESDfriendFileName(const TString& esdf)
@@ -232,7 +429,6 @@ void AliEveEventManager::SetAODFileName(const TString& aod)
     
     if (aod.EndsWith(".zip")) fgAODFileName.Form("%s#AliAOD.root",aod.Data());
     
-    
 }
 
 void AliEveEventManager::AddAODfriend(const TString& friendFileName)
@@ -262,34 +458,40 @@ void AliEveEventManager::SetRawFileName(const TString& raw)
 void AliEveEventManager::SetCdbUri(const TString& cdb)
 {
     // Set path to CDB, there is no default.
-
     if ( ! cdb.IsNull()) fgCdbUri = cdb;
 }
 
+void AliEveEventManager::SetSpecificCdbUri(const TString& path,const TString& value)
+{
+    // Set path to specific CDB object, there is no default.
+  if ( ! value.IsNull()) fgSpecificCdbUriValue = value;
+  if ( ! path.IsNull()) fgSpecificCdbUriPath = path;
+}
+
 void AliEveEventManager::SetGAliceFileName(const TString& galice)
 {
     // Set file-name for opening gAlice, default "galice.root".
 
     if ( galice.IsNull()) return;
-    fgGAliceFileName = galice; 
+    fgGAliceFileName = galice;
     
     if (galice.EndsWith(".zip")) fgGAliceFileName.Form("%s#galice.root",galice.Data());
 }
 
 void AliEveEventManager::SetFilesPath(const TString& urlPath)
 {
-   TString path = urlPath;
+    TString path = urlPath;
     gSystem->ExpandPathName(path);
     if (path.IsNull() || path == ".")
     {
         path = gSystem->WorkingDirectory();
     }
-   
-   TString sep;
-   if(path.EndsWith(".zip")) // if given a path to root_archive.zip
-      sep= "#";
-   else if(!path.EndsWith("/"))
-      sep = "/";
+
+    TString sep;
+    if(path.EndsWith(".zip")) // if given a path to root_archive.zip
+        sep= "#";
+    else if(!path.EndsWith("/"))
+        sep = "/";
     
     SetESDFileName( TString(Form("%s%sAliESDs.root", path.Data(), sep.Data())) );
     SetESDfriendFileName(  TString(Form("%s%sAliESDfriends.root", path.Data(), sep.Data())) );
@@ -348,60 +550,32 @@ void AliEveEventManager::Open()
     if ((fESDFile = TFile::Open(fgESDFileName)))
     {
         fESD = new AliESDEvent();
-        fESDTree = (TTree*) fESDFile->Get("esdTree");
-        if (fESDTree != 0)
-        {
-            // Check if ESDfriends exists and attach the branch.
-            // We use TFile::Open() instead of gSystem->AccessPathName
-            // as it seems to work better when attachine alieve to a
-            // running reconstruction process with auto-save on.
-            TFile *esdFriendFile = TFile::Open(fgESDfriendsFileName);
-            if (esdFriendFile)
-            {
-                if (!esdFriendFile->IsZombie())
-                {
-                    esdFriendFile->Close();
-                    fESDfriendExists = kTRUE;
-                    fESDTree->SetBranchStatus ("ESDfriend*", 1);
-                }
-                delete esdFriendFile;
-            }
-
-            fESD->ReadFromTree(fESDTree);
-            if (fESDfriendExists)
-            {
-                fESDfriend = (AliESDfriend*) fESD->FindListObject("AliESDfriend");
-                Info(kEH, "found and attached ESD friend.");
-            }
-            else
-            {
-                Warning(kEH, "ESDfriend not found.");
-            }
 
-            if (fESDTree->GetEntry(0) <= 0)
-            {
-                delete fESDFile; fESDFile = 0;
-                delete fESD; fESD = 0;
-                Warning(kEH, "failed getting the first entry from esdTree.");
-            }
-            else
-            {
-                if (runNo < 0)
-                    runNo = fESD->GetESDRun()->GetRunNumber();
-            }
+        switch(fgESDvisibleTrees){
+        case AliEveEventManager::kOfflineTree :
+            fESDTree = readESDTree("esdTree", runNo);
+            break;
+        case AliEveEventManager::kHLTTree :
+            fHLTESDTree = readESDTree("HLTesdTree", runNo);
+            break;
+        default:
+            fESDTree    = readESDTree("esdTree", runNo);
+            fHLTESDTree = readESDTree("HLTesdTree", runNo);
         }
-        else // esdtree == 0
-        {
+
+        if(!fESDTree && !fHLTESDTree){
+            // both ESD trees are == 0
             delete fESDFile; fESDFile = 0;
             delete fESD; fESD = 0;
-            Warning(kEH, "failed getting the esdTree.");
         }
+
+
     }
-    else // esd not readable
+    else // esd file not readable
     {
         Warning(kEH, "can not read ESD file '%s'.", fgESDFileName.Data());
     }
-    if (fESDTree == 0)
+    if (fESDTree == 0 && fHLTESDTree==0)
     {
         if (fgAssertESD)
         {
@@ -467,11 +641,15 @@ void AliEveEventManager::Open()
     }
 
     // Open RunLoader from galice.root
+//    fgGAliceFileName = "/Users/Jerus/galice.root"; // temp
+    
     TFile *gafile = TFile::Open(fgGAliceFileName);
+    cout<<"Opening galice"<<endl;
     if (gafile)
     {
         gafile->Close();
         delete gafile;
+        cout<<"SETTING RUN LOADER in Open()"<<endl;
         fRunLoader = AliRunLoader::Open(fgGAliceFileName, GetName());
         if (fRunLoader)
         {
@@ -586,15 +764,70 @@ void AliEveEventManager::Open()
         }
         else
         {
-            throw (kEH + "unknown run number.");
+            fExternalCtrl = kTRUE;
+             fEventId = 0;
+            return;
         }
     }
 
     // Initialize OCDB ... only in master event-manager
 
-    if (this == fgMaster)
+    InitOCDB(runNo);
+
+
+    fIsOpen = kTRUE;
+}
+
+void AliEveEventManager::InitOCDB(int runNo)
+{
+  TString cdbPath = Form("local://%s/ed_ocdb_objects/",gSystem->Getenv("HOME"));
+  AliCDBManager* cdb = AliCDBManager::Instance();
+#ifdef ZMQ
+  if(fOnlineMode)
+    {
+      if(runNo != fCurrentRun)
+       { 
+         cout<<"Loading OCDB for new run:"<<runNo<<" in online mode."<<endl;
+         TEnv settings;
+         settings.ReadFile(AliOnlineReconstructionUtil::GetPathToServerConf(), kEnvUser);
+         fCurrentRun = runNo;
+         cout<<"config read"<<endl;
+
+         // Retrieve GRP entry for given run from aldaqdb.
+         TString dbHost = settings.GetValue("logbook.host", DEFAULT_LOGBOOK_HOST);
+         Int_t   dbPort =  settings.GetValue("logbook.port", DEFAULT_LOGBOOK_PORT);
+         TString dbName =  settings.GetValue("logbook.db", DEFAULT_LOGBOOK_DB);
+         TString user =  settings.GetValue("logbook.user", DEFAULT_LOGBOOK_USER);
+         TString password = settings.GetValue("logbook.pass", DEFAULT_LOGBOOK_PASS);
+         
+         gSystem->cd(cdbPath.Data());
+         gSystem->Exec("rm -fr GRP/");
+         cout<<"CDB path for GRP:"<<cdbPath<<endl;
+
+         TString gdc;
+
+         Int_t ret=AliGRPPreprocessor::ReceivePromptRecoParameters(fCurrentRun, dbHost.Data(),
+                                                                   dbPort, dbName.Data(),
+                                                                   user.Data(), password.Data(),
+                                                                   Form("%s",cdbPath.Data()),
+                                                                   gdc);
+
+         if(ret>0) Info("RetrieveGRP","Last run of the same type is: %d",ret);
+         else if(ret==0) Warning("RetrieveGRP","No previous run of the same type found");
+         else if(ret<0) Error("Retrieve","Error code while retrieving GRP parameters returned: %d",ret);
+
+
+         cdb->SetDefaultStorage(settings.GetValue("cdb.defaultStorage", DEFAULT_CDB_STORAGE));
+         cdb->SetSpecificStorage("GRP/GRP/Data",cdbPath.Data());
+         cdb->SetRun(fCurrentRun);
+         cdb->Print();
+       }
+    }
+#endif
+
+  static const TEveException kEH("AliEveEventManager::InitOCDB ");
+    //if (this == fgMaster)
     {
-        AliCDBManager* cdb = AliCDBManager::Instance();
         if (cdb->IsDefaultStorageSet() == kTRUE)
         {
             Warning(kEH, "CDB already set - using the old storage:\n  '%s'",
@@ -607,7 +840,7 @@ void AliEveEventManager::Open()
                 gEnv->SetValue("Root.Stacktrace", "no");
                 Fatal("Open()", "OCDB path was not specified.");
             }
-
+           cout<<"Setting default storage:"<<fgCdbUri<<endl;
             // Handle some special cases for MC (should be in OCDBManager).
             if (fgCdbUri == "mcideal://")
                 cdb->SetDefaultStorage("MC", "Ideal");
@@ -615,18 +848,18 @@ void AliEveEventManager::Open()
                 cdb->SetDefaultStorage("MC", "Residual");
             else if (fgCdbUri == "mcfull://")
                 cdb->SetDefaultStorage("MC", "Full");
-            else if (fgCdbUri == "local://") {
-                fgCdbUri = Form("local://%s/OCDB", gSystem->Getenv("ALICE_ROOT"));
-                cdb->SetDefaultStorage(fgCdbUri);
-            } else
-                cdb->SetDefaultStorage(fgCdbUri);
-
+            else if (fgCdbUri == "local://"){
+               fgCdbUri = Form("local://%s/OCDB", gSystem->Getenv("ALICE_ROOT"));
+               cdb->SetDefaultStorage(fgCdbUri);
+             } 
+           else{
+             cdb->SetDefaultStorage(fgCdbUri);
+             }
             cdb->SetRun(runNo);
 
             if (cdb->IsDefaultStorageSet() == kFALSE)
                 throw kEH + "CDB initialization failed for '" + fgCdbUri + "'.";
-        }
-
+        }/*
         if (fgCdbUri.BeginsWith("local://"))
         {
             TString curPath = gSystem->WorkingDirectory();
@@ -646,10 +879,8 @@ void AliEveEventManager::Open()
                     cdb->SetSpecificStorage(grp, lpath);
                 }
             }
-        }
+           }*/
     }
-
-    fIsOpen = kTRUE;
 }
 
 void AliEveEventManager::SetEvent(AliRunLoader *runLoader, AliRawReader *rawReader, AliESDEvent *esd, AliESDfriend *esdf)
@@ -666,6 +897,8 @@ void AliEveEventManager::SetEvent(AliRunLoader *runLoader, AliRawReader *rawRead
         Close();
     }
 
+                       Info(kEH,"setting it!!! ============================");
+
     fRunLoader = runLoader;
     fRawReader = rawReader;
     fESD       = esd;
@@ -682,7 +915,8 @@ void AliEveEventManager::SetEvent(AliRunLoader *runLoader, AliRawReader *rawRead
 
     AfterNewEventLoaded();
 
-    if (fAutoLoad) StartAutoLoadTimer();
+    if (fAutoLoad || fLoopMarked) StartAutoLoadTimer();
+    
 }
 
 Int_t AliEveEventManager::GetMaxEventId(Bool_t refreshESD) const
@@ -702,14 +936,27 @@ Int_t AliEveEventManager::GetMaxEventId(Bool_t refreshESD) const
         return -1;
     }
 
-    if (fESDTree)
+    if ((fESDTree!=0) || (fHLTESDTree!=0))
     {
         if (refreshESD)
         {
-            fESDTree->Refresh();
+            if(fESDTree!=0) fESDTree->Refresh();
+            if(fHLTESDTree!=0) fHLTESDTree->Refresh();
             fPEventSelector->Update();
         }
-        return fESDTree->GetEntries() - 1;
+
+        Int_t maxEventId=0;
+        switch(fgESDvisibleTrees){
+        default:
+        case AliEveEventManager::kOfflineTree :
+            maxEventId = fESDTree->GetEntries() - 1;
+            break;
+        case AliEveEventManager::kHLTTree :
+            maxEventId = fHLTESDTree->GetEntries() - 1;
+            break;
+       }
+
+        return maxEventId;
     }
     else if (fAODTree)
     {
@@ -732,6 +979,7 @@ Int_t AliEveEventManager::GetMaxEventId(Bool_t refreshESD) const
 
 void AliEveEventManager::GotoEvent(Int_t event)
 {
+    cout<<"Go to event:"<<event<<endl;
     // Load data for specified event.
     // If event is out of range an exception is thrown and old state
     // is preserved.
@@ -752,7 +1000,89 @@ void AliEveEventManager::GotoEvent(Int_t event)
     }
     if (fExternalCtrl)
     {
-        throw (kEH + "Event-loop is under external control.");
+      // throw (kEH + "Event-loop is under external control.");
+#ifdef ZMQ
+      if(fOnlineMode)
+       {
+         if (fStorageDown && -1 == event) 
+           {
+             NextEvent();
+             return;
+           }
+
+         if (fESD)
+           {
+             // create new server request:
+             struct serverRequestStruct *requestMessage = new struct serverRequestStruct;
+            
+             // set request type:
+             if (event == -1)      {requestMessage->messageType = REQUEST_GET_LAST_EVENT;}
+             else  if (event == 0) {requestMessage->messageType = REQUEST_GET_FIRST_EVENT;}
+             else  if (event == 1) {requestMessage->messageType = REQUEST_GET_PREV_EVENT;}
+             else  if (event == 2) {requestMessage->messageType = REQUEST_GET_NEXT_EVENT;}
+            
+             // set event struct:
+             struct eventStruct eventToLoad;
+             eventToLoad.runNumber = fESD->GetRunNumber();
+             eventToLoad.eventNumber = fESD->GetEventNumberInFile();
+             requestMessage->event = eventToLoad;
+            
+             // create event manager:
+             AliStorageEventManager *eventManager =
+               AliStorageEventManager::GetEventManagerInstance();
+             AliESDEvent *resultEvent = NULL;
+            
+             eventManager->CreateSocket(SERVER_COMMUNICATION_REQ);
+             fMutex->Lock();
+            
+             // send request and receive event:
+             eventManager->Send(requestMessage,SERVER_COMMUNICATION_REQ);
+             resultEvent = eventManager->GetEvent(SERVER_COMMUNICATION_REQ);
+            
+             if(resultEvent)
+               {
+                 DestroyElements();
+                 InitOCDB(resultEvent->GetRunNumber());
+                 SetEvent(0,0,resultEvent,0);
+               }
+             else
+               {
+                 if(event==-1){cout<<"\n\nWARNING -- No last event is avaliable.\n\n"<<endl;}
+                 if(event==0){cout<<"\n\nWARNING -- No first event is avaliable.\n\n"<<endl;}
+                 if(event==1){cout<<"\n\nWARNING -- No previous event is avaliable.\n\n"<<endl;}
+                 if(event==2){cout<<"\n\nWARNING -- No next event is avaliable.\n\n"<<endl;}
+               }
+            
+             fMutex->UnLock();
+           }
+         else
+           {
+             cout<<"\n\nWARNING -- No event has been already loaded. Loading the most recent event...\n\n"<<endl;
+
+             struct serverRequestStruct *requestMessage = new struct serverRequestStruct;
+             requestMessage->messageType = REQUEST_GET_LAST_EVENT;
+            
+             AliStorageEventManager *eventManager = AliStorageEventManager::GetEventManagerInstance();
+             eventManager->CreateSocket(SERVER_COMMUNICATION_REQ);
+             AliESDEvent *resultEvent = NULL;
+            
+             fMutex->Lock();
+             eventManager->Send(requestMessage,SERVER_COMMUNICATION_REQ);
+             resultEvent = eventManager->GetEvent(SERVER_COMMUNICATION_REQ);
+            
+             if(resultEvent)
+               {
+                 fESD=resultEvent;
+                 DestroyElements();
+                 InitOCDB(resultEvent->GetRunNumber());
+                 SetEvent(0,0,resultEvent,0);
+               }
+             else{cout<<"\n\nWARNING -- The most recent event is not avaliable.\n\n"<<endl;}
+             fMutex->UnLock();
+           }
+       }
+#endif 
+
     }
     else if (!fIsOpen)
     {
@@ -764,13 +1094,24 @@ void AliEveEventManager::GotoEvent(Int_t event)
     fHasEvent = kFALSE;
 
     Int_t maxEvent = 0;
-    if (fESDTree)
+    if ((fESDTree!=0) || (fHLTESDTree!=0))
     {
-        if (event >= fESDTree->GetEntries())
-            fESDTree->Refresh();
-        maxEvent = fESDTree->GetEntries() - 1;
-        if (event < 0)
-            event = fESDTree->GetEntries() + event;
+        if(fESDTree){
+            if (event >= fESDTree->GetEntries())
+                fESDTree->Refresh();
+            maxEvent = fESDTree->GetEntries() - 1;
+            if (event < 0)
+                event = fESDTree->GetEntries() + event;
+        }
+
+        if(fHLTESDTree){
+            if (event >= fHLTESDTree->GetEntries())
+                fHLTESDTree->Refresh();
+            maxEvent = fHLTESDTree->GetEntries() - 1;
+            if (event < 0)
+                event = fHLTESDTree->GetEntries() + event;
+
+        }
     }
     else if (fAODTree)
     {
@@ -806,11 +1147,16 @@ void AliEveEventManager::GotoEvent(Int_t event)
     {
         throw (kEH + "neither RunLoader, ESD nor Raw loaded.");
     }
-    if (event < 0 || event > maxEvent)
+    if (event < 0)
     {
         throw (kEH + Form("event %d not present, available range [%d, %d].",
                           event, 0, maxEvent));
     }
+    if (event > maxEvent)
+    {
+      event=0;
+      cout<<"Event number out of range. Going to event 0"<<endl;
+    }
 
     TString sysInfoHeader;
     sysInfoHeader.Form("AliEveEventManager::GotoEvent(%d) - ", event);
@@ -841,6 +1187,14 @@ void AliEveEventManager::GotoEvent(Int_t event)
             fESD->SetESDfriend(fESDfriend);
     }
 
+    if (fHLTESDTree) {
+        if (fHLTESDTree->GetEntry(event) <= 0)
+            throw (kEH + "failed getting required event from HLT ESD.");
+
+        if (fESDfriendExists)
+            fESD->SetESDfriend(fESDfriend);
+    }
+
     if (fAODTree) {
         if (fAODTree->GetEntry(event) <= 0)
             throw (kEH + "failed getting required event from AOD.");
@@ -898,6 +1252,14 @@ void AliEveEventManager::Timeout()
     Emit("Timeout()");
 }
 
+void AliEveEventManager::PrepareForNewEvent(AliESDEvent *event)
+{      
+       DestroyElements();
+       InitOCDB(event->GetRunNumber());
+       printf("======================= setting event to %d\n", fEventId);
+       SetEvent(0,0,event,0);
+}
+
 void AliEveEventManager::NextEvent()
 {
     // Loads next event.
@@ -905,31 +1267,65 @@ void AliEveEventManager::NextEvent()
 
     static const TEveException kEH("AliEveEventManager::NextEvent ");
 
-    if (fAutoLoadTimerRunning)
-    {
-        throw (kEH + "Event auto-load timer is running.");
-    }
-
+    if (fAutoLoadTimerRunning){throw (kEH + "Event auto-load timer is running.");}
+    
     if (fExternalCtrl)
     {
-        // !!! This should really go somewhere else. It is done in GotoEvent(),
-        // so here we should do it in SetEvent().
-        DestroyElements();
-        gSystem->ExitLoop();
-
-    }
-    else if (fESDTree)
-    {
-        Int_t nextevent=0;
-        if (fPEventSelector->FindNext(nextevent))
-        {
-            GotoEvent(nextevent);
-        }
+#ifdef ZMQ
+      if(fOnlineMode)
+       {
+         if(fIsNewEventAvaliable)
+           {
+             fMutex->Lock();
+             if(fWritingToEventIndex == 0) fEventInUse = 0;
+             else if(fWritingToEventIndex == 1) fEventInUse = 1;
+            
+             if(fCurrentEvent[fEventInUse])
+               {
+                 if(fCurrentEvent[fEventInUse]->GetRunNumber() >= 0)
+                   {
+                     printf("======================= setting event to %d\n", fCurrentEvent[fEventInUse]->GetEventNumberInFile());
+                    
+                     DestroyElements();
+                     InitOCDB(fCurrentEvent[fEventInUse]->GetRunNumber());
+                     SetEvent(0,0,fCurrentEvent[fEventInUse],0);
+                    
+                   }
+               }
+             fIsNewEventAvaliable = false;
+             fMutex->UnLock();
+           }
+         else
+           {
+             cout<<"No new event is avaliable."<<endl;
+             NoEventLoaded();
+           }
+       }
+#endif
+    }
+    else if ((fESDTree!=0) || (fHLTESDTree!=0))
+    {
+      Int_t nextevent=0;
+      if (fPEventSelector->FindNext(nextevent))
+      {
+        GotoEvent(nextevent);
+      }
     }
     else if (fEventId < GetMaxEventId(kTRUE))
     {
-        GotoEvent(fEventId + 1);
+      GotoEvent(fEventId + 1);
     }
+    
+    gSystem->ProcessEvents();
+    
+    /*
+    cout<<"VSD"<<endl;
+    AliEveVSDCreator *vsdCreator = new AliEveVSDCreator();
+    cout<<"contructor called"<<endl;
+    vsdCreator->CreateVSD("myVSD.root");
+    cout<<"PO"<<endl;
+*/
+    //if(fEventListenerThread){delete fEventListenerThread;fEventListenerThread=0;}
 }
 
 void AliEveEventManager::PrevEvent()
@@ -947,7 +1343,7 @@ void AliEveEventManager::PrevEvent()
         throw (kEH + "Event-loop is under external control.");
     }
 
-    if (fESDTree)
+    if ((fESDTree!=0) || (fHLTESDTree!=0))
     {
         Int_t nextevent=0;
         if (fPEventSelector->FindPrev(nextevent))
@@ -961,11 +1357,66 @@ void AliEveEventManager::PrevEvent()
     }
 }
 
+void AliEveEventManager::MarkCurrentEvent()
+{
+#ifdef ZMQ
+  if(!fOnlineMode){return;}
+
+       struct serverRequestStruct *requestMessage = new struct serverRequestStruct;
+       struct eventStruct mark;
+       mark.runNumber = fESD->GetRunNumber();
+       mark.eventNumber = fESD->GetEventNumberInFile();
+       requestMessage->messageType = REQUEST_MARK_EVENT;
+       requestMessage->event = mark;
+
+       AliStorageEventManager *eventManager =
+               AliStorageEventManager::GetEventManagerInstance();
+       eventManager->CreateSocket(SERVER_COMMUNICATION_REQ);
+
+       /*
+       std::future<bool> unused = std::async([]()
+       {
+               eventManager->Send(requestMessage,SERVER_COMMUNICATION_REQ);
+               bool response =  eventManager->GetBool(SERVER_COMMUNICATION_REQ);
+
+               if(response)
+               {
+               //fStatusLabel->SetText("Event marked");
+               cout<<"ADMIN PANEL -- Event marked succesfully"<<endl;
+               }
+               else
+               {
+               //fStatusLabel->SetText("Couldn't mark this event");
+               cout<<"ADMIN PANEL -- Could not matk event"<<endl;
+               }
+       });
+       */
+       
+       eventManager->Send(requestMessage,SERVER_COMMUNICATION_REQ);
+       bool response =  eventManager->GetBool(SERVER_COMMUNICATION_REQ);
+       
+       
+       if(response)
+       {
+               //fStatusLabel->SetText("Event marked");
+               cout<<"ADMIN PANEL -- Event marked succesfully"<<endl;
+       }
+       else
+       {
+               //fStatusLabel->SetText("Couldn't mark this event");
+               cout<<"ADMIN PANEL -- Could not matk event"<<endl;
+       }
+       if(requestMessage){delete requestMessage;}
+#endif
+}
+
 void AliEveEventManager::Close()
 {
     // Close the event data-files and delete ESD, ESDfriend, run-loader
     // and raw-reader.
 
+    cout<<"\n\n\nClose() called!!\n\n\n"<<endl;
+    
     static const TEveException kEH("AliEveEventManager::Close ");
 
     if (!fIsOpen)
@@ -976,13 +1427,14 @@ void AliEveEventManager::Close()
     if (fAutoLoadTimerRunning)
         StopAutoLoadTimer();
 
-    if (fESDTree) {
+    if ((fESDTree!=0) || (fHLTESDTree!=0)) {
         delete fESD;       fESD       = 0;
         // delete fESDfriend; // friend tree is deleted with the tree
         fESDfriend = 0;
         fESDfriendExists = kFALSE;
 
-        delete fESDTree;   fESDTree = 0;
+        if(fESDTree) { delete fESDTree;   fESDTree = 0; }
+        if(fHLTESDTree) { delete fHLTESDTree;   fHLTESDTree = 0; }
         delete fESDFile;   fESDFile = 0;
     }
 
@@ -1222,7 +1674,7 @@ Bool_t AliEveEventManager::InitRecoParam()
     fgRecoParam = new AliRecoParam;
     const Int_t  kNDetectors = 14;
 
-    static const TEveException kEH("AliEveEventManager::InitRecoParam ");
+    static const TEveException kEH("AliEveEventManager::InitRecoParam");
 
     Bool_t isOK = kTRUE;
 
@@ -1309,6 +1761,58 @@ Bool_t AliEveEventManager::InitRecoParam()
     return isOK;
 }
 
+TTree *AliEveEventManager::readESDTree(const char *treeName, int &runNo)
+{
+    if(!fESDFile && !fESD) return 0;
+
+    static const TEveException kEH("AliEveEventManager::readESDTree ");
+
+    TTree* tempTree = 0;
+
+    tempTree =(TTree*) fESDFile->Get(treeName);
+    if (tempTree != 0)
+    {
+        TFile *esdFriendFile = TFile::Open(fgESDfriendsFileName);
+        if (esdFriendFile)
+        {
+            if (!esdFriendFile->IsZombie())
+            {
+                esdFriendFile->Close();
+                fESDfriendExists = kTRUE;
+                tempTree->SetBranchStatus ("ESDfriend*", 1);
+            }
+            delete esdFriendFile;
+        }
+
+        fESD->ReadFromTree(tempTree);
+        if (fESDfriendExists)
+        {
+            fESDfriend = (AliESDfriend*) fESD->FindListObject("AliESDfriend");
+            Info(kEH, "found and attached ESD friend.");
+        }
+        else
+        {
+            Warning(kEH, "ESDfriend not found.");
+        }
+
+        if (tempTree->GetEntry(0) <= 0)
+        {
+            Warning(kEH, "failed getting the first entry from tree: %s", treeName);
+        }
+        else
+        {
+            if (runNo < 0)
+                runNo = fESD->GetESDRun()->GetRunNumber();
+        }
+    }
+    else // tree == 0
+    {
+        Warning(kEH, "failed getting the tree:%s", treeName);
+    }
+
+    return tempTree;
+}
+
 
 //------------------------------------------------------------------------------
 
@@ -1420,6 +1924,23 @@ void AliEveEventManager::SetAutoLoad(Bool_t autoLoad)
     }
 }
 
+void AliEveEventManager::SetLoopMarked(Bool_t loopMarked)
+{
+    // Set the automatic event loading mode
+  if(fLoopMarked == loopMarked)
+    {
+      cout<<"loop marked has the same value - ignoring"<<endl;
+      return;
+    }
+  else
+    {
+      cout<<"Setting loof marked to:"<<loopMarked<<endl;
+      fLoopMarked = loopMarked;
+      if (fLoopMarked){StartAutoLoadTimer();}
+      else{StopAutoLoadTimer();}
+    }
+}
+
 void AliEveEventManager::SetTrigSel(Int_t trig)
 {
     static const TEveException kEH("AliEveEventManager::SetTrigSel ");
@@ -1458,21 +1979,23 @@ void AliEveEventManager::StopAutoLoadTimer()
 
 void AliEveEventManager::AutoLoadNextEvent()
 {
-    // Called from auto-load timer, so it has to be public.
-    // Do NOT call it directly.
-
-    static const TEveException kEH("AliEveEventManager::AutoLoadNextEvent ");
-
-    if ( ! fAutoLoadTimerRunning || ! fAutoLoadTimer->HasTimedOut())
-    {
-        Warning(kEH, "Called unexpectedly - ignoring the call. Should ONLY be called from an internal timer.");
-        return;
-    }
-
-    StopAutoLoadTimer();
-    NextEvent();
-    if (fAutoLoad && !fExternalCtrl)
-        StartAutoLoadTimer();
+       // Called from auto-load timer, so it has to be public.
+       // Do NOT call it directly.
+
+       static const TEveException kEH("AliEveEventManager::AutoLoadNextEvent ");
+         
+       Info(kEH, "called!");
+
+       if ( ! fAutoLoadTimerRunning || ! fAutoLoadTimer->HasTimedOut())
+       {
+               Warning(kEH, "Called unexpectedly - ignoring the call. Should ONLY be called from an internal timer.");
+               return;
+       }
+
+       StopAutoLoadTimer();
+       NextEvent();
+       if (fAutoLoad || fLoopMarked)
+               StartAutoLoadTimer();
 }
 
 //------------------------------------------------------------------------------
@@ -1481,57 +2004,70 @@ void AliEveEventManager::AutoLoadNextEvent()
 
 void AliEveEventManager::AfterNewEventLoaded()
 {
-    // Execute registered macros and commands.
-    // At the end emit NewEventLoaded signal.
-    //
-    // Virtual from TEveEventManager.
-
-    static const TEveException kEH("AliEveEventManager::AfterNewEventLoaded ");
-
-    NewEventDataLoaded();
-
-    if (fExecutor)
-        fExecutor->ExecMacros();
-
-    TEveEventManager::AfterNewEventLoaded();
-
-    NewEventLoaded();
-
-    if (this == fgMaster && fSubManagers != 0)
-    {
-        TIter next(fSubManagers);
-        while ((fgCurrent = dynamic_cast<AliEveEventManager*>(next())) != 0)
-        {
-            gEve->SetCurrentEvent(fgCurrent);
-            try
-            {
-                fgCurrent->GotoEvent(fEventId);
-            }
-            catch (TEveException& exc)
-            {
-                // !!! Should somehow tag / disable / remove it?
-                Error(kEH, "Getting event %d for sub-event-manager '%s' failed: '%s'.",
-                      fEventId, fgCurrent->GetName(), exc.Data());
-            }
-        }
-        fgCurrent = fgMaster;
-        gEve->SetCurrentEvent(fgMaster);
+  // Execute registered macros and commands.
+  // At the end emit NewEventLoaded signal.
+  //
+  // Virtual from TEveEventManager.
+
+  static const TEveException kEH("AliEveEventManager::AfterNewEventLoaded ");
+
+  Info(kEH, "------------------!!!------------");
+                      
+  NewEventDataLoaded();
+  if (fExecutor) fExecutor->ExecMacros();
+
+  TEveEventManager::AfterNewEventLoaded();
+  NewEventLoaded();
+
+  if (this == fgMaster && fSubManagers != 0)
+  {
+    TIter next(fSubManagers);
+    while ((fgCurrent = dynamic_cast<AliEveEventManager*>(next())) != 0)
+    {
+      gEve->SetCurrentEvent(fgCurrent);
+      try
+      {
+        fgCurrent->GotoEvent(fEventId);
+      }
+      catch (TEveException& exc)
+      {
+        // !!! Should somehow tag / disable / remove it?
+        Error(kEH, "Getting event %d for sub-event-manager '%s' failed: '%s'.",
+              fEventId, fgCurrent->GetName(), exc.Data());
+      }
+      Info(kEH, "------------------!!! while() gEve->SetCurrentEvent() ------------");
     }
+    fgCurrent = fgMaster;
+    Info(kEH, "------------------!!! while() gEve->SetCurrentEvent(MASTER) ------------");
+    gEve->SetCurrentEvent(fgMaster);
+  }
 }
 
 void AliEveEventManager::NewEventDataLoaded()
 {
     // Emit NewEventDataLoaded signal.
-
     Emit("NewEventDataLoaded()");
 }
-
 void AliEveEventManager::NewEventLoaded()
 {
     // Emit NewEventLoaded signal.
-
     Emit("NewEventLoaded()");
 }
+void AliEveEventManager::NoEventLoaded()
+{
+    // Emit NoEventLoaded signal.
+    Emit("NoEventLoaded()");
+}
+void AliEveEventManager::StorageManagerOk()
+{
+    // Emit StorageManagerOk signal.
+    Emit("StorageManagerOk()");
+}
+void AliEveEventManager::StorageManagerDown()
+{
+    // Emit StorageManagerOk signal.
+    Emit("StorageManagerDown()");
+}
 
 
 //------------------------------------------------------------------------------
@@ -1851,3 +2387,14 @@ TEveElement* AliEveEventManager::FindGlobal(const TString& tag)
 {
     return dynamic_cast<TEveElement*>(fGlobal->GetValue(tag));
 }
+Int_t AliEveEventManager::NewEventAvailable()
+{
+  if (fIsNewEventAvaliable)
+  {
+    return 1;
+  }
+  else
+  {
+    return 0;
+  }
+}