]> 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         nequileft = nequileft_internal;
197         return;
198       }
199
200       while( (!inFile.is_open()) && inFiles.size() > 0 ) {
201         openFileDesc = *inFileIt;
202
203         if (openFileDesc.nequi < NEQUI)
204           doVirtualEquilibration = true;
205         else
206           doVirtualEquilibration = false;
207
208         firstUsedConfig = true;
209
210         if(log) *log << "CCACHE: Opening dat-file: " << inFileIt->filename << endl << flush;
211         inFile.open( (DATADIR + "/" + inFileIt->filename).c_str(), std::ios::binary );
212         
213         inFiles.erase(inFileIt);
214         
215         if( !inFile.is_open() ) continue;
216
217         inBuffer = new boost::iostreams::filtering_istreambuf;
218         inBuffer->push( boost::iostreams::bzip2_decompressor() );
219         inBuffer->push(inFile);
220       }
221
222       if( inFile.is_open() ) 
223         {
224           if (doVirtualEquilibration) {
225             if(log) *log << "CCACHE: Trying virtual equilibration." << endl << flush;
226             doVirtualEquilibration = false;
227             for (iDidVirtualSkips=0; iDidVirtualSkips < (NEQUI-openFileDesc.nequi)/openFileDesc.nskip; iDidVirtualSkips++) {
228               if( readFullBlock(tmpConfig, configSize) != configSize || ! inFile.is_open() )
229                 break;
230               else if ( (NEQUI-openFileDesc.nequi) - (iDidVirtualSkips+1)*openFileDesc.nskip < nequileft_internal ) {
231                 memcpy(configMem, tmpConfig, configSize);
232                 nequileft_internal = NEQUI - openFileDesc.nequi - (iDidVirtualSkips+1)*openFileDesc.nskip;
233                 readnewconfig = true;
234                 firstUsedConfig = false;
235               }
236             }
237           }
238
239           if( readFullBlock(tmpConfig, configSize) == configSize && inFile.is_open() )
240             {
241               memcpy(configMem, tmpConfig, configSize);
242               readnewconfig = true;
243               if (firstUsedConfig) {
244                 firstUsedConfig = false;
245                 if (openFileDesc.nequi < NEQUI)
246                   nequileft_internal = NEQUI - openFileDesc.nequi - iDidVirtualSkips*openFileDesc.nskip;
247                 else
248                   nequileft_internal = NEQUI - openFileDesc.nequi;
249               }
250               nequileft_internal -= openFileDesc.nskip;
251               nequileft = nequileft_internal;
252               return;
253             }
254           else {
255             if(log) *log << "CCACHE: Could not read configuration. Closing dat-file: " << openFileDesc.filename << endl << flush;
256             inFile.close();
257           }
258         }
259     }
260 }
261
262 void configcache::openOutFile(int actnequi)
263 {
264   time_t secstamp = time(NULL);
265
266   outFileName.str("");
267   outFileName << DATADIR << "/" << secstamp << "_" << getFileId(actnequi) << "_.edat.tmp";
268
269   outFile.open( outFileName.str().c_str(), std::ios::binary );
270
271   outBuffer = new boost::iostreams::filtering_ostreambuf;
272   outBuffer->push(boost::iostreams::bzip2_compressor());
273   outBuffer->push(outFile);
274 }
275
276 void configcache::writeHeader(const string& headerid, const char *header, long unsigned int size, int actnequi) {
277   unsigned long headeridhash;
278
279   if( DATADIR == "" || MODE < 2 ) return;
280
281   if(!outFile.is_open())
282     openOutFile(actnequi);
283
284   headeridhash = hash(headerid);
285
286   boost::iostreams::write(*outBuffer, (char*)&size, sizeof(long unsigned int));
287   boost::iostreams::write(*outBuffer, (char*)&headeridhash, sizeof(unsigned long));
288   boost::iostreams::write(*outBuffer, header, size);
289 }
290
291 void configcache::writeConfig(int actnequi)
292 {
293   long unsigned int zeroheader=0;
294
295   if ( DATADIR == "" || MODE < 2 ) return;
296
297   if ( ! outFile.is_open() )
298     openOutFile(actnequi);
299   
300   boost::iostreams::write(*outBuffer, (char*)&zeroheader, sizeof(long unsigned int));
301
302   boost::iostreams::write(*outBuffer, configMem, configSize);
303 }
304
305 void configcache::addPara(const string& parid, const double& val){
306   parameter newPara;
307   newPara.id = parid;
308   newPara.val = val;
309   Paras.push_back(newPara);
310 }
311
312 int configcache::getParIndex(const string& parid){
313   for(int ipara=0; ipara<Paras.size(); ipara++)
314     if(Paras[ipara].id == parid) return ipara;
315 }
316
317 void configcache::setPara(const string& parid, const double& value){
318   Paras[getParIndex(parid)].val = value;
319   finishOutFile();
320   if(inBuffer != NULL) { delete inBuffer; inBuffer=NULL; } 
321   inFile.close();
322   inFiles.clear();
323
324   refetchDataFiles = true;
325   nequileft_internal = NEQUI;
326 }
327
328 configcache::~configcache()
329 {
330   finishOutFile();
331   delete inBuffer;
332   inBuffer = NULL;
333 }
334
335 void configcache::finishOutFile()
336 {
337   if( outBuffer != NULL )
338     {
339       delete outBuffer;
340       outBuffer = NULL;
341     }
342
343   if( outFile.is_open() )
344     {
345       outFile.close();
346       rename( outFileName.str().c_str(), outFileName.str().substr(0, outFileName.str().size()-4).c_str() );
347     }
348 }
349
350 int configcache::readFullBlock(char *tmpData, long unsigned int dataSize)
351 {
352   /* try to read header */
353   if ( openFileDesc.extended )
354     if ( ! readAllHeaders() ) 
355       return -1;
356
357   /* read data */
358   return readDataToMem(tmpData, dataSize);
359 }
360
361 int configcache::readDataToMem(char *tmpData, long unsigned int dataSize)
362 {
363   int readturn = -1;
364
365   if ( dataSize == 0 ) return 0;
366
367   try { readturn = boost::iostreams::read(*inBuffer, tmpData, dataSize); }
368   catch(boost::iostreams::bzip2_error& error) { 
369     if(log) *log << "CCACHE: Caught bzip2 exception with error code: " << error.error() << endl << flush;
370     inFile.close();
371   } 
372   catch (std::exception const& ex) {
373     if(log) *log << "CCACHE: Caught exception: " << ex.what() << endl << flush;
374     inFile.close();
375   }
376   catch( ... ) {
377     if(log) *log << "CCACHE: Caught unknown exception while reading." << endl << flush;
378     inFile.close();
379   }
380
381   return readturn;
382 }
383
384 unsigned long configcache::hash(const string& str)
385 {
386   unsigned long hash = 5381;
387
388   for(string::const_iterator it=str.begin();it!=str.end();it++) 
389     hash = ((hash << 5) + hash) + *it; /* hash * 33 + character */
390
391   return hash;
392 }
393
394 void configcache::deleteHeaderStore()
395 {
396   while ( headerStore.size() > 0 ) {
397     free(headerStore.back().second);
398     headerStore.pop_back();
399   }
400 }
401
402 vector<infiledesc>::iterator configcache::getNextInfile(vector<unsigned long> *excludeFileHashes) {
403   for (vector<infiledesc>::iterator init = inFiles.begin(); init != inFiles.end(); ++init) {
404     if (excludeFileHashes != NULL) {
405       bool excludethisfile = false;
406
407       for (vector<unsigned long>::iterator exit = excludeFileHashes->begin(); exit != excludeFileHashes->end(); ++exit)
408         if ( *exit == hash(init->filename) ) {
409           excludethisfile = true;
410           break;
411         }
412
413       if (excludethisfile)
414         continue;
415     }
416     return init;
417   }
418   return inFiles.end();
419 }