]> 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->firstUsedConfig = 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       int iDidVirtualSkips;
198
199       if( (!inFile.is_open()) && inFileIt == inFiles.end() ) {
200         cout << "RETURNING..." << endl;
201         nequileft = nequileft_internal;
202         return;
203       }
204
205       while( (!inFile.is_open()) && inFiles.size() > 0 ) {
206         openFileDesc = *inFileIt;
207
208         if(log) *log << "CCACHE: Opening dat-file: " << inFileIt->filename << endl << flush;
209         inFile.open( (DATADIR + "/" + inFileIt->filename).c_str(), std::ios::binary );
210         
211         inFiles.erase(inFileIt);
212         
213         if( !inFile.is_open() ) continue;
214
215         inBuffer = new boost::iostreams::filtering_istreambuf;
216         inBuffer->push( boost::iostreams::bzip2_decompressor() );
217         inBuffer->push(inFile);
218       }
219
220       if( inFile.is_open() ) 
221         {
222           if (openFileDesc.doVirtualEquilibration) {
223             if(log) *log << "CCACHE: Trying virtual equilibration." << endl << flush;
224             openFileDesc.doVirtualEquilibration = false;
225             for (iDidVirtualSkips=0; iDidVirtualSkips < (NEQUI-openFileDesc.nequi)/openFileDesc.nskip; iDidVirtualSkips++) {
226               if( readFullBlock(tmpConfig, configSize) != configSize || ! inFile.is_open() )
227                 break;
228               else if ( (NEQUI-openFileDesc.nequi) - (iDidVirtualSkips+1)*openFileDesc.nskip < nequileft_internal ) {
229                 memcpy(configMem, tmpConfig, configSize);
230                 nequileft_internal = NEQUI - openFileDesc.nequi - (iDidVirtualSkips+1)*openFileDesc.nskip;
231                 cout << "blabla:" << nequileft_internal << endl;
232                 readnewconfig = true;
233                 openFileDesc.firstUsedConfig = false;
234               }
235             }
236           }
237
238           if( readFullBlock(tmpConfig, configSize) == configSize && inFile.is_open() )
239             {
240               memcpy(configMem, tmpConfig, configSize);
241               readnewconfig = true;
242               if (openFileDesc.firstUsedConfig) {
243                 openFileDesc.firstUsedConfig = false;
244                 if (NEQUI < openFileDesc.nequi)
245                   nequileft_internal = NEQUI - openFileDesc.nequi - iDidVirtualSkips*openFileDesc.nskip;
246                 else
247                   nequileft_internal = NEQUI - openFileDesc.nequi;
248               }
249               nequileft_internal -= openFileDesc.nskip;
250               cout << "sadasd:" << nequileft_internal << endl;
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 }
326
327 configcache::~configcache()
328 {
329   finishOutFile();
330   delete inBuffer;
331   inBuffer = NULL;
332 }
333
334 void configcache::finishOutFile()
335 {
336   if( outBuffer != NULL )
337     {
338       delete outBuffer;
339       outBuffer = NULL;
340     }
341
342   if( outFile.is_open() )
343     {
344       outFile.close();
345       rename( outFileName.str().c_str(), outFileName.str().substr(0, outFileName.str().size()-4).c_str() );
346     }
347 }
348
349 int configcache::readFullBlock(char *tmpData, long unsigned int dataSize)
350 {
351   /* try to read header */
352   if ( openFileDesc.extended )
353     if ( ! readAllHeaders() ) 
354       return -1;
355
356   /* read data */
357   return readDataToMem(tmpData, dataSize);
358 }
359
360 int configcache::readDataToMem(char *tmpData, long unsigned int dataSize)
361 {
362   int readturn = -1;
363
364   if ( dataSize == 0 ) return 0;
365
366   try { readturn = boost::iostreams::read(*inBuffer, tmpData, dataSize); }
367   catch(boost::iostreams::bzip2_error& error) { 
368     if(log) *log << "CCACHE: Caught bzip2 exception with error code: " << error.error() << endl << flush;
369     inFile.close();
370   } 
371   catch (std::exception const& ex) {
372     if(log) *log << "CCACHE: Caught exception: " << ex.what() << endl << flush;
373     inFile.close();
374   }
375   catch( ... ) {
376     if(log) *log << "CCACHE: Caught unknown exception while reading." << endl << flush;
377     inFile.close();
378   }
379
380   return readturn;
381 }
382
383 unsigned long configcache::hash(const string& str)
384 {
385   unsigned long hash = 5381;
386
387   for(string::const_iterator it=str.begin();it!=str.end();it++) 
388     hash = ((hash << 5) + hash) + *it; /* hash * 33 + character */
389
390   return hash;
391 }
392
393 void configcache::deleteHeaderStore()
394 {
395   while ( headerStore.size() > 0 ) {
396     free(headerStore.back().second);
397     headerStore.pop_back();
398   }
399 }
400
401 vector<infiledesc>::iterator configcache::getNextInfile(vector<unsigned long> *excludeFileHashes) {
402   for (vector<infiledesc>::iterator init = inFiles.begin(); init != inFiles.end(); ++init) {
403     if (excludeFileHashes != NULL) {
404       bool excludethisfile = false;
405
406       for (vector<unsigned long>::iterator exit = excludeFileHashes->begin(); exit != excludeFileHashes->end(); ++exit)
407         if ( *exit == hash(init->filename) ) {
408           excludethisfile = true;
409           break;
410         }
411
412       if (excludethisfile)
413         continue;
414     }
415     return init;
416   }
417   return inFiles.end();
418 }