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