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