]> git.treefish.org Git - phys/latlib.git/blob - configcache.cpp
...
[phys/latlib.git] / configcache.cpp
1 #include "configcache.h"
2
3 #include <stdlib.h>
4 #include <iostream>
5 #include <time.h>
6 #include <dirent.h>
7
8 #define HEADER_READOK   0
9 #define HEADER_READERR  1
10 #define HEADER_READLAST 2
11
12 configcache::configcache(const string& cacheid, const int& nequi, const int& nskip, const string& datadir, char **configmem, const int& configMemSize, const int& cachemode,
13                          ostream *_log){
14   log = _log;
15
16   NEQUI = nequi;
17   NSKIP = nskip;
18   DATADIR = datadir;
19   CACHEID = cacheid;
20
21   if ( cacheid.find("_") != -1 ) {
22     if(log) *log << "CCACHE: Invalid cacheid \"" << cacheid << "\" given. Cacheids must not contain underscores!" << endl << flush;
23     exit(1);
24   }
25
26   configMem = (char*)malloc(configMemSize);
27   tmpConfig = (char*)malloc(configMemSize);
28
29   *configmem = configMem;
30   configSize = configMemSize;
31
32   outBuffer = NULL;
33   inBuffer = NULL;
34
35   MODE = cachemode;
36
37   refetchDataFiles = false;
38 }
39
40 string configcache::getFileId(int actnequi, const bool& shortid)
41 {
42   stringstream fileid;
43
44   if(!shortid) fileid << CACHEID << "_" << actnequi << "_" << NSKIP;
45   for(int ipara=0; ipara<Paras.size(); ipara++)
46     fileid << "_" << Paras[ipara].id << Paras[ipara].val;
47
48   return fileid.str();
49 }
50
51 void configcache::fetchDataFiles()
52 {
53   struct dirent *de=NULL;
54   DIR *d=NULL;
55   static infiledesc filedesc;
56   
57   d=opendir(DATADIR.c_str());
58   if(d != NULL){
59     while(de = readdir(d)){
60       string filename = de->d_name;
61       if(isValidInFile(filename, &filedesc)) 
62         {
63           inFiles.push_back(filedesc);
64         }
65     }
66   }
67 }
68
69 bool configcache::isValidInFile(const string& infile, infiledesc *filedesc)
70 {
71   char *inchar, *inParts;
72   string truncIn, truncOut;
73
74   filedesc->filename = infile;
75
76   if( infile.size() < 4 ) return false;
77
78   if( infile.substr(infile.size()-4) == ".dat" )
79     filedesc->extended = false;
80   else if( infile.substr(infile.size()-4) == "edat" )
81     filedesc->extended = true;
82   else
83     return false;
84
85   inchar = new char [infile.size()+1];
86   strcpy (inchar, infile.c_str());
87
88   inParts = strtok( inchar, "_" );
89   for(int iPart=0; inParts!=NULL; iPart++)
90     {
91       if( iPart>3 ) { truncIn += "_"; truncIn += inParts; }
92
93       switch(iPart)
94         {
95         case 1: if(inParts != CACHEID)
96             return false;
97           break;
98         case 2:
99           filedesc->nequi = atoi(inParts);
100           break;
101         case 3: 
102           if(atoi(inParts) != NSKIP) 
103             return false;
104           filedesc->nskip = atoi(inParts);
105           break;
106         }
107       inParts = strtok( NULL, "_");
108     }
109   truncIn = truncIn.substr(0, truncIn.size()-4);
110
111   delete[] inchar;
112
113   if( truncIn.find( getFileId(NEQUI, true) + "_" ) == string::npos ) return false;
114
115   return true;
116 }
117
118 int configcache::readHeader()
119 {
120   long unsigned int headersize;
121   
122   if( readDataToMem((char *)&headersize, sizeof(long unsigned int)) == sizeof(long unsigned int) && inFile.is_open() ) {
123     if ( headersize == 0 )
124       return HEADER_READLAST;
125
126     pair<unsigned long, void *> newHeader;
127
128     if( readDataToMem((char *)&newHeader.first, sizeof(unsigned long)) == sizeof(unsigned long) && inFile.is_open() ) {
129       newHeader.second = malloc(headersize);
130
131       if( readDataToMem((char *)newHeader.second, headersize) == headersize && inFile.is_open() ) {
132         headerStore.push_back(newHeader);
133         return HEADER_READOK;
134       }
135       else {
136         if(log) *log << "CCACHE: Could not read heade-data! Closing dat-file: " << openFileDesc.filename << endl << flush;
137         inFile.close();
138         return HEADER_READERR;
139       }
140     }
141     else {
142       if(log) *log << "CCACHE: Could not read headerid-hash! Closing dat-file: " << openFileDesc.filename << endl << flush;
143       inFile.close();
144       return HEADER_READERR;
145     }
146   }
147   else {
148     if(log) *log << "CCACHE: Could not read header size. Closing dat-file: " << openFileDesc.filename << endl << flush;
149     inFile.close();
150     return HEADER_READERR;
151   }
152 }
153
154 bool configcache::readAllHeaders()
155 {
156   int readHeaderStatus;
157
158   deleteHeaderStore();
159   
160   do {
161     readHeaderStatus = readHeader();
162   }
163   while ( readHeaderStatus == HEADER_READOK );
164
165   if ( readHeaderStatus == HEADER_READLAST ) return true;
166   else if ( readHeaderStatus == HEADER_READERR ) return false;
167 }
168
169 void * configcache::getHeader(const string& headerid) {
170   for (vector< pair<unsigned long, void *> >::iterator headerStoreIt = headerStore.begin(); headerStoreIt != headerStore.end(); ++headerStoreIt)
171     if ( headerStoreIt->first == hash(headerid) )
172       return headerStoreIt->second;
173   
174   return NULL;
175 }
176
177 /* returns number of equilibration-steps left with new read configuration 
178    or zero if no new configuration was read */
179 void configcache::readConfig(bool& readnewconfig, int& nequileft, vector<unsigned long> *excludeFileHashes)
180 {
181   readnewconfig = false;
182
183   if(DATADIR == "" || MODE == CACHE_MODE_DISABLED) return;
184
185   if(refetchDataFiles){
186     refetchDataFiles = false;
187     fetchDataFiles();
188   }
189
190   while(true)
191     {
192       vector<infiledesc>::iterator inFileIt = getNextInfile(excludeFileHashes);
193       int iDidVirtualSkips;
194
195       if( (!inFile.is_open()) && inFileIt == inFiles.end() ) {
196         cout << "RETURNING..." << endl;
197         nequileft = nequileft_internal;
198         return;
199       }
200
201       while( (!inFile.is_open()) && inFiles.size() > 0 ) {
202         openFileDesc = *inFileIt;
203
204         if (openFileDesc.nequi < NEQUI)
205           doVirtualEquilibration = true;
206         else
207           doVirtualEquilibration = false;
208
209         firstUsedConfig = true;
210
211         if(log) *log << "CCACHE: Opening dat-file: " << inFileIt->filename << endl << flush;
212         inFile.open( (DATADIR + "/" + inFileIt->filename).c_str(), std::ios::binary );
213         
214         inFiles.erase(inFileIt);
215         
216         if( !inFile.is_open() ) continue;
217
218         inBuffer = new boost::iostreams::filtering_istreambuf;
219         inBuffer->push( boost::iostreams::bzip2_decompressor() );
220         inBuffer->push(inFile);
221       }
222
223       if( inFile.is_open() ) 
224         {
225           if (doVirtualEquilibration) {
226             cout << nequileft_internal << endl;
227
228             if(log) *log << "CCACHE: Trying virtual equilibration." << endl << flush;
229             doVirtualEquilibration = false;
230             for (iDidVirtualSkips=0; iDidVirtualSkips < (NEQUI-openFileDesc.nequi)/openFileDesc.nskip; iDidVirtualSkips++) {
231               if( readFullBlock(tmpConfig, configSize) != configSize || ! inFile.is_open() )
232                 break;
233               else if ( (NEQUI-openFileDesc.nequi) - (iDidVirtualSkips+1)*openFileDesc.nskip < nequileft_internal ) {
234                 memcpy(configMem, tmpConfig, configSize);
235                 nequileft_internal = NEQUI - openFileDesc.nequi - (iDidVirtualSkips+1)*openFileDesc.nskip;
236                 cout << "blabla:" << nequileft_internal << endl;
237                 readnewconfig = true;
238                 firstUsedConfig = false;
239               }
240             }
241           }
242
243           if( readFullBlock(tmpConfig, configSize) == configSize && inFile.is_open() )
244             {
245               memcpy(configMem, tmpConfig, configSize);
246               readnewconfig = true;
247               if (firstUsedConfig) {
248                 firstUsedConfig = false;
249                 if (openFileDesc.nequi < NEQUI)
250                   nequileft_internal = NEQUI - openFileDesc.nequi - iDidVirtualSkips*openFileDesc.nskip;
251                 else
252                   nequileft_internal = NEQUI - openFileDesc.nequi;
253               }
254               nequileft_internal -= openFileDesc.nskip;
255               cout << "sadasd:" << nequileft_internal << endl;
256               nequileft = nequileft_internal;
257               return;
258             }
259           else {
260             if(log) *log << "CCACHE: Could not read configuration. Closing dat-file: " << openFileDesc.filename << endl << flush;
261             inFile.close();
262           }
263         }
264     }
265 }
266
267 void configcache::openOutFile(int actnequi)
268 {
269   time_t secstamp = time(NULL);
270
271   outFileName.str("");
272   outFileName << DATADIR << "/" << secstamp << "_" << getFileId(actnequi) << "_.edat.tmp";
273
274   outFile.open( outFileName.str().c_str(), std::ios::binary );
275
276   outBuffer = new boost::iostreams::filtering_ostreambuf;
277   outBuffer->push(boost::iostreams::bzip2_compressor());
278   outBuffer->push(outFile);
279 }
280
281 void configcache::writeHeader(const string& headerid, const char *header, long unsigned int size, int actnequi) {
282   unsigned long headeridhash;
283
284   if( DATADIR == "" || MODE < 2 ) return;
285
286   if(!outFile.is_open())
287     openOutFile(actnequi);
288
289   headeridhash = hash(headerid);
290
291   boost::iostreams::write(*outBuffer, (char*)&size, sizeof(long unsigned int));
292   boost::iostreams::write(*outBuffer, (char*)&headeridhash, sizeof(unsigned long));
293   boost::iostreams::write(*outBuffer, header, size);
294 }
295
296 void configcache::writeConfig(int actnequi)
297 {
298   long unsigned int zeroheader=0;
299
300   if ( DATADIR == "" || MODE < 2 ) return;
301
302   if ( ! outFile.is_open() )
303     openOutFile(actnequi);
304   
305   boost::iostreams::write(*outBuffer, (char*)&zeroheader, sizeof(long unsigned int));
306
307   boost::iostreams::write(*outBuffer, configMem, configSize);
308 }
309
310 void configcache::addPara(const string& parid, const double& val){
311   parameter newPara;
312   newPara.id = parid;
313   newPara.val = val;
314   Paras.push_back(newPara);
315 }
316
317 int configcache::getParIndex(const string& parid){
318   for(int ipara=0; ipara<Paras.size(); ipara++)
319     if(Paras[ipara].id == parid) return ipara;
320 }
321
322 void configcache::setPara(const string& parid, const double& value){
323   Paras[getParIndex(parid)].val = value;
324   finishOutFile();
325   if(inBuffer != NULL) { delete inBuffer; inBuffer=NULL; } 
326   inFile.close();
327   inFiles.clear();
328
329   refetchDataFiles = true;
330   nequileft_internal = NEQUI;
331 }
332
333 configcache::~configcache()
334 {
335   finishOutFile();
336   delete inBuffer;
337   inBuffer = NULL;
338 }
339
340 void configcache::finishOutFile()
341 {
342   if( outBuffer != NULL )
343     {
344       delete outBuffer;
345       outBuffer = NULL;
346     }
347
348   if( outFile.is_open() )
349     {
350       outFile.close();
351       rename( outFileName.str().c_str(), outFileName.str().substr(0, outFileName.str().size()-4).c_str() );
352     }
353 }
354
355 int configcache::readFullBlock(char *tmpData, long unsigned int dataSize)
356 {
357   /* try to read header */
358   if ( openFileDesc.extended )
359     if ( ! readAllHeaders() ) 
360       return -1;
361
362   /* read data */
363   return readDataToMem(tmpData, dataSize);
364 }
365
366 int configcache::readDataToMem(char *tmpData, long unsigned int dataSize)
367 {
368   int readturn = -1;
369
370   if ( dataSize == 0 ) return 0;
371
372   try { readturn = boost::iostreams::read(*inBuffer, tmpData, dataSize); }
373   catch(boost::iostreams::bzip2_error& error) { 
374     if(log) *log << "CCACHE: Caught bzip2 exception with error code: " << error.error() << endl << flush;
375     inFile.close();
376   } 
377   catch (std::exception const& ex) {
378     if(log) *log << "CCACHE: Caught exception: " << ex.what() << endl << flush;
379     inFile.close();
380   }
381   catch( ... ) {
382     if(log) *log << "CCACHE: Caught unknown exception while reading." << endl << flush;
383     inFile.close();
384   }
385
386   return readturn;
387 }
388
389 unsigned long configcache::hash(const string& str)
390 {
391   unsigned long hash = 5381;
392
393   for(string::const_iterator it=str.begin();it!=str.end();it++) 
394     hash = ((hash << 5) + hash) + *it; /* hash * 33 + character */
395
396   return hash;
397 }
398
399 void configcache::deleteHeaderStore()
400 {
401   while ( headerStore.size() > 0 ) {
402     free(headerStore.back().second);
403     headerStore.pop_back();
404   }
405 }
406
407 vector<infiledesc>::iterator configcache::getNextInfile(vector<unsigned long> *excludeFileHashes) {
408   for (vector<infiledesc>::iterator init = inFiles.begin(); init != inFiles.end(); ++init) {
409     if (excludeFileHashes != NULL) {
410       bool excludethisfile = false;
411
412       for (vector<unsigned long>::iterator exit = excludeFileHashes->begin(); exit != excludeFileHashes->end(); ++exit)
413         if ( *exit == hash(init->filename) ) {
414           excludethisfile = true;
415           break;
416         }
417
418       if (excludethisfile)
419         continue;
420     }
421     return init;
422   }
423   return inFiles.end();
424 }