CMS 3D CMS Logo

WatcherStreamFileReader.cc
Go to the documentation of this file.
5 
6 #include <cerrno>
7 #include <climits>
8 #include <cstdlib>
9 #include <cstdio>
10 #include <cstring>
11 #include <unistd.h>
12 #include <sys/types.h>
13 #include <sys/stat.h>
14 #include <sys/time.h>
15 #include <fcntl.h>
16 #include <libgen.h>
17 #include <fstream>
18 
19 //using namespace edm;
20 using namespace std;
21 
22 //std::string WatcherStreamFileReader::fileName_;
23 
24 
25 #if !defined(__linux__) && !(defined(__APPLE__) && __DARWIN_C_LEVEL >= 200809L)
26 /* getline implementation is copied from glibc. */
27 
28 #ifndef SIZE_MAX
29 # define SIZE_MAX ((size_t) -1)
30 #endif
31 #ifndef SSIZE_MAX
32 # define SSIZE_MAX ((ssize_t) (SIZE_MAX / 2))
33 #endif
34 namespace {
35 ssize_t getline (char **lineptr, size_t *n, FILE *fp)
36 {
37  ssize_t result = -1;
38  size_t cur_len = 0;
39 
40  if (lineptr == NULL || n == NULL || fp == NULL)
41  {
42  errno = EINVAL;
43  return -1;
44  }
45 
46  if (*lineptr == NULL || *n == 0)
47  {
48  *n = 120;
49  *lineptr = (char *) malloc (*n);
50  if (*lineptr == NULL)
51  {
52  result = -1;
53  goto end;
54  }
55  }
56 
57  for (;;)
58  {
59  int i;
60 
61  i = getc (fp);
62  if (i == EOF)
63  {
64  result = -1;
65  break;
66  }
67 
68  /* Make enough space for len+1 (for final NUL) bytes. */
69  if (cur_len + 1 >= *n)
70  {
71  size_t needed_max =
72  SSIZE_MAX < SIZE_MAX ? (size_t) SSIZE_MAX + 1 : SIZE_MAX;
73  size_t needed = 2 * *n + 1; /* Be generous. */
74  char *new_lineptr;
75 
76  if (needed_max < needed)
77  needed = needed_max;
78  if (cur_len + 1 >= needed)
79  {
80  result = -1;
81  goto end;
82  }
83 
84  new_lineptr = (char *) realloc (*lineptr, needed);
85  if (new_lineptr == NULL)
86  {
87  result = -1;
88  goto end;
89  }
90 
91  *lineptr = new_lineptr;
92  *n = needed;
93  }
94 
95  (*lineptr)[cur_len] = i;
96  cur_len++;
97 
98  if (i == '\n')
99  break;
100  }
101  (*lineptr)[cur_len] = '\0';
102  result = cur_len ? (ssize_t) cur_len : result;
103 
104 end:
105  return result;
106 }
107 }
108 #endif
109 
110 static std::string now(){
111  struct timeval t;
112  gettimeofday(&t, nullptr);
113 
114  char buf[256];
115  strftime(buf, sizeof(buf), "%F %R %S s", localtime(&t.tv_sec));
116  buf[sizeof(buf)-1] = 0;
117 
118  stringstream buf2;
119  buf2 << buf << " " << ((t.tv_usec+500)/1000) << " ms";
120 
121  return buf2.str();
122 }
123 
125  inputDir_(pset.getParameter<std::string>("inputDir")),
126  filePatterns_(pset.getParameter<std::vector<std::string> >("filePatterns")),
127  inprocessDir_(pset.getParameter<std::string>("inprocessDir")),
128  processedDir_(pset.getParameter<std::string>("processedDir")),
129  corruptedDir_(pset.getParameter<std::string>("corruptedDir")),
130  tokenFile_(pset.getUntrackedParameter<std::string>("tokenFile",
131  "watcherSourceToken")),
132  timeOut_(pset.getParameter<int>("timeOutInSec")),
133  end_(false),
134  verbosity_(pset.getUntrackedParameter<int>("verbosity", 0)){
135  struct stat buf;
136  if(stat(tokenFile_.c_str(), &buf)){
137  FILE* f = fopen(tokenFile_.c_str(), "w");
138  if(f){
139  fclose(f);
140  } else{
141  throw cms::Exception("WatcherSource") << "Failed to create token file.";
142  }
143  }
144  vector<string> dirs;
145  dirs.push_back(inprocessDir_);
146  dirs.push_back(processedDir_);
147  dirs.push_back(corruptedDir_);
148 
149  for(unsigned i = 0; i < dirs.size(); ++i){
150  const string& dir = dirs[i];
151  struct stat fileStat;
152  if(0==stat(dir.c_str(), &fileStat)){
153  if(!S_ISDIR(fileStat.st_mode)){
154  throw cms::Exception("[WatcherSource]")
155  << "File " << dir << " exists but is not a directory "
156  << " as expected.";
157  }
158  } else {//directory does not exists, let's try to create it
159  if(0!=mkdir(dir.c_str(), 0755)){
160  throw cms::Exception("[WatcherSource]")
161  << "Failed to create directory " << dir
162  << " for writing data.";
163  }
164  }
165  }
166 
167  std::stringstream fileListCmdBuf;
168  fileListCmdBuf.str("");
169  // fileListCmdBuf << "/bin/ls -rt " << inputDir_ << " | egrep '(";
170  //by default ls will sort the file alphabetically which will results
171  //in ordering the files in increasing LB number, which is the desired
172  //order.
173  // fileListCmdBuf << "/bin/ls " << inputDir_ << " | egrep '(";
174  fileListCmdBuf << "/bin/find " << inputDir_ << " -maxdepth 2 -print | egrep '(";
175  //TODO: validate patternDir (see ;, &&, ||) and escape special character
176  if(filePatterns_.empty()) throw cms::Exception("WacherSource", "filePatterns parameter is empty");
177  char curDir[PATH_MAX>0?PATH_MAX:4096];
178  if(getcwd(curDir, sizeof(curDir))==nullptr){
179  throw cms::Exception("WatcherSource")
180  << "Failed to retreived working directory path: "
181  << strerror(errno);
182  }
183  curDir_ = curDir;
184 
185  for(unsigned i = 0 ; i < filePatterns_.size(); ++i){
186  if(i>0) fileListCmdBuf << "|";
187  // if(filePatterns_[i].size()>0 && filePatterns_[0] != "/"){//relative path
188  // fileListCmdBuf << curDir << "/";
189  // }
190  fileListCmdBuf << filePatterns_[i];
191  }
192  fileListCmdBuf << ")' | sort";
193 
194  fileListCmd_ = fileListCmdBuf.str();
195 
196  cout << "[WatcherSource " << now() << "]"
197  << " Command to retrieve input files: "
198  << fileListCmd_ << "\n";
199 
200 }
201 
203 }
204 
207  return inputFile?inputFile->newHeader():false;
208 }
209 
211 
213 
214  //TODO: shall better send an exception...
215  if(inputFile==nullptr){
216  throw cms::Exception("WatcherSource") << "No input file found.";
217  }
218 
219  const InitMsgView* header = inputFile->startMessage();
220 
221  if(header->code() != Header::INIT) //INIT Msg
222  throw cms::Exception("readHeader","WatcherStreamFileReader")
223  << "received wrong message type: expected INIT, got "
224  << header->code() << "\n";
225 
226  return header;
227 }
228 
230  if(end_){ closeFile(); return nullptr;}
231 
233 
234  //go to next input file, till no new event is found
235  while((inputFile=getInputFile())!=nullptr
236  && inputFile->next()==0){
237  closeFile();
238  }
239 
240  return inputFile==nullptr?nullptr:inputFile->currentRecord();
241 }
242 
244  char* lineptr = nullptr;
245  size_t n = 0;
246 
247  struct stat buf;
248 
249  if(stat(tokenFile_.c_str(), &buf)!=0){
250  end_ = true;
251  }
252 
253  bool waiting = false;
254  static bool firstWait = true;
255  timeval waitStart;
256  //if no cached input file, look for new files until one is found:
257  if(!end_ && streamerInputFile_.get()==nullptr){
258  fileName_.assign("");
259 
260  //check if we have file in the queue, if not look for new files:
261  while(filesInQueue_.empty()){
262  if(stat(tokenFile_.c_str(), &buf)!=0){
263  end_ = true;
264  break;
265  }
266  FILE* s = popen(fileListCmd_.c_str(), "r");
267  if(s==nullptr){
268  throw cms::Exception("WatcherSource")
269  << "Failed to retrieve list of input file: " << strerror(errno);
270  }
271 
272  ssize_t len;
273  while(!feof(s)){
274  if((len=getline(&lineptr, &n, s))>0){
275  //remove end-of-line character:
276  lineptr[len-1] = 0;
277  string fileName;
278  if(lineptr[0] != '/'){
279  if(!inputDir_.empty() && inputDir_[0] != '/'){//relative path
280  fileName.assign(curDir_);
281  fileName.append("/");
282  fileName.append(inputDir_);
283  } else{
284  fileName.assign(inputDir_);
285  }
286  fileName.append("/");
287  }
288  fileName.append(lineptr);
289  filesInQueue_.push_back(fileName);
290  if(verbosity_) cout << "[WatcherSource " << now() << "]"
291  << " File to process: '"
292  << fileName << "'\n";
293  }
294  }
295  while(!feof(s)) fgetc(s);
296  pclose(s);
297  if(filesInQueue_.empty()){
298  if(!waiting){
299  cout << "[WatcherSource " << now() << "]"
300  << " No file found. Waiting for new file...\n";
301  cout << flush;
302  waiting = true;
303  gettimeofday(&waitStart, nullptr);
304  } else if(!firstWait){
305  timeval t;
306  gettimeofday(&t, nullptr);
307  float dt = (t.tv_sec-waitStart.tv_sec) * 1.
308  + (t.tv_usec-waitStart.tv_usec) * 1.e-6;
309  if((timeOut_ >= 0) && (dt > timeOut_)){
310  cout << "[WatcherSource " << now() << "]"
311  << " Having waited for new file for " << (int)dt << " sec. "
312  << "Timeout exceeded. Exits.\n";
313  //remove(tokenFile_.c_str()); //we do not delete the token, otherwise sorting process on the monitoring farm will not be restarted by the runloop.sh script.
314  end_ = true;
315  break;
316  }
317  }
318  }
319  sleep(1);
320  } //end of file queue update
321  firstWait = false;
322  free(lineptr); lineptr=nullptr;
323 
324  while(streamerInputFile_.get()==nullptr && !filesInQueue_.empty()){
325 
326  fileName_ = filesInQueue_.front();
327  filesInQueue_.pop_front();
328  int fd = open(fileName_.c_str(), 0);
329  if(fd!=0){
330  struct stat buf;
331  off_t size = -1;
332  //check that file transfer is finished, by monitoring its size:
333  time_t t = time(nullptr);
334  for(;;){
335  fstat(fd, &buf);
336  if(verbosity_) cout << "file size: " << buf.st_size << ", prev size: " << size << "\n";
337  if(buf.st_size==size) break; else size = buf.st_size;
338  if(difftime(t,buf.st_mtime)>60) break; //file older then 1 min=> tansfer must be finished
339  sleep(1);
340  }
341 
342  if(fd!=0 && buf.st_size == 0){//file is empty. streamer reader
343  // does not like empty file=> skip it
344  stringstream c;
345  c << "/bin/mv -f \"" << fileName_ << "\" \"" << corruptedDir_
346  << "/.\"";
347  if(verbosity_) cout << "[WatcherSource " << now() << "]"
348  << " Excuting "
349  << c.str() << "\n";
350  int i = system(c.str().c_str());
351  if(i!=0){
352  //throw cms::Exception("WatcherSource")
353  cout << "[WatcherSource " << now() << "] "
354  << "Failed to move empty file '" << fileName_ << "'"
355  << " to corrupted directory '" << corruptedDir_ << "'\n";
356  }
357  continue;
358  }
359 
360  close(fd);
361 
362  vector<char> buf1(fileName_.size()+1);
363  copy(fileName_.begin(), fileName_.end(), buf1.begin());
364  buf1[buf1.size()-1] = 0;
365 
366  vector<char> buf2(fileName_.size()+1);
367  copy(fileName_.begin(), fileName_.end(), buf2.begin());
368  buf2[buf1.size()-1] = 0;
369 
370  string dirnam(dirname(&buf1[0]));
371  string filenam(basename(&buf2[0]));
372 
373  string dest = inprocessDir_ + "/" + filenam;
374 
375  if(verbosity_) cout << "[WatcherSource " << now() << "]"
376  << " Moving file "
377  << fileName_ << " to " << dest << "\n";
378 
379  stringstream c;
380  c << "/bin/mv -f \"" << fileName_ << "\" \"" << dest
381  << "/.\"";
382 
383 
384  if(0!=rename(fileName_.c_str(), dest.c_str())){
385  //if(0!=system(c.str().c_str())){
386  throw cms::Exception("WatcherSource")
387  << "Failed to move file '" << fileName_ << "' "
388  << "to processing directory " << inprocessDir_
389  << ": " << strerror(errno);
390  }
391 
392  fileName_ = dest;
393 
394  cout << "[WatcherSource " << now() << "]"
395  << " Opening file " << fileName_ << "\n" << flush;
397  = unique_ptr<edm::StreamerInputFile>(new edm::StreamerInputFile(fileName_));
398 
399  ofstream f(".watcherfile");
400  f << fileName_;
401  } else{
402  cout << "[WatcherSource " << now() << "]"
403  << " Failed to open file " << fileName_ << endl;
404  }
405  } //loop on file queue to find one file which opening succeeded
406  }
407  return streamerInputFile_.get();
408 }
409 
411  if(streamerInputFile_.get()==nullptr) return;
412  //delete the streamer input file:
413  streamerInputFile_.reset();
414  stringstream cmd;
415  //TODO: validation of processDir
416  cmd << "/bin/mv -f \"" << fileName_ << "\" \"" << processedDir_ << "/.\"";
417  if(verbosity_) cout << "[WatcherSource " << now() << "]"
418  << " Excuting " << cmd.str() << "\n";
419  int i = system(cmd.str().c_str());
420  if(i!=0){
421  throw cms::Exception("WatcherSource")
422  << "Failed to move processed file '" << fileName_ << "'"
423  << " to processed directory '" << processedDir_ << "'\n";
424  //Stop further processing to prevent endless loop:
425  end_ = true;
426  }
427  cout << flush;
428 }
std::vector< std::string > filePatterns_
size
Write out results.
float dt
Definition: AMPTWrapper.h:126
const EventMsgView * getNextEvent()
Definition: rename.py:1
def copy(args, dbName)
std::deque< std::string > filesInQueue_
#define NULL
Definition: scimark2.h:8
WatcherStreamFileReader(edm::ParameterSet const &pset)
const InitMsgView * getHeader()
#define SIZE_MAX
double f[11][100]
#define end
Definition: vmac.h:39
InitMsgView const * startMessage() const
edm::StreamerInputFile * getInputFile()
static std::string now()
std::unique_ptr< edm::StreamerInputFile > streamerInputFile_
#define SSIZE_MAX
def mkdir(path)
Definition: eostools.py:251
EventMsgView const * currentRecord() const
uint32 code() const
Definition: InitMessage.h:72
list cmd
Definition: mps_setup.py:237
dbl *** dir
Definition: mlp_gen.cc:35