CMS 3D CMS Logo

refresh.cc
Go to the documentation of this file.
7 
10 
11 #include <boost/program_options.hpp>
12 
13 #include <algorithm>
14 #include <cstdlib>
15 #include <filesystem>
16 #include <fstream>
17 #include <functional>
18 #include <iostream>
19 #include <set>
20 #include <string>
21 #include <utility>
22 
23 #include <sys/wait.h>
24 
25 using namespace edmplugin;
26 
27 // We process DSOs by forking and processing them in the child, in bunches of
28 // PER_PROCESS_DSO. Once a bunch has been processed we exit the child and
29 // spawn a new one.
30 // Due to the different behavior of the linker on different platforms, we process
31 // a different number of DSOs per process.
32 // For macosx the cost is to actually resolve weak symbols and it grows with
33 // the number of libraries as well, so we try to process not too many libraries.
34 // In linux the main cost is to load the library itself, so we try to load as
35 // many as reasonable in a single process to avoid having to reload them in
36 // the subsequent process. Obviuously keeping the PER_PROCESS_DSO low keeps the
37 // memory usage low as well.
38 #ifdef __APPLE__
39 #define PER_PROCESS_DSO 20
40 #elif defined(__aarch64__)
41 #define PER_PROCESS_DSO 10
42 #else
43 #define PER_PROCESS_DSO 2000
44 #endif
45 
46 namespace std {
47  ostream& operator<<(std::ostream& o, vector<std::string> const& iValue) {
48  std::string sep("");
49  std::string commaSep(",");
50  for (std::vector<std::string>::const_iterator it = iValue.begin(), itEnd = iValue.end(); it != itEnd; ++it) {
51  o << sep << *it;
52  sep = commaSep;
53  }
54  return o;
55  }
56 } // namespace std
57 namespace {
58  struct Listener {
59  typedef edmplugin::CacheParser::NameAndType NameAndType;
60  typedef edmplugin::CacheParser::NameAndTypes NameAndTypes;
61 
62  void newFactory(edmplugin::PluginFactoryBase const* iBase) {
63  using std::placeholders::_1;
64  using std::placeholders::_2;
65  iBase->newPluginAdded_.connect(std::bind(std::mem_fn(&Listener::newPlugin), this, _1, _2));
66  }
67  void newPlugin(std::string const& iCategory, edmplugin::PluginInfo const& iInfo) {
68  nameAndTypes_.push_back(NameAndType(iInfo.name_, iCategory));
69  }
70 
71  NameAndTypes nameAndTypes_;
72  };
73 } // namespace
74 int main(int argc, char** argv) try {
75  using namespace boost::program_options;
76  using std::placeholders::_1;
77 
78  static char const* const kPathsOpt = "paths";
79  static char const* const kPathsCommandOpt = "paths,p";
80  //static char const* const kAllOpt = "all";
81  //static char const* const kAllCommandOpt = "all,a";
82  static char const* const kHelpOpt = "help";
83  static char const* const kHelpCommandOpt = "help,h";
84 
85  std::string descString(argv[0]);
86  descString += " [options] [[--";
87  descString += kPathsOpt;
88  descString += "] path [path]] \nAllowed options";
89  options_description desc(descString);
90  std::string defaultDir(".");
91  std::vector<std::string> defaultDirList = edmplugin::standard::config().searchPath();
92  if (!defaultDirList.empty()) {
93  defaultDir = defaultDirList[0];
94  }
95  desc.add_options()(kHelpCommandOpt, "produce help message")(
96  kPathsCommandOpt,
97  value<std::vector<std::string> >()->default_value(std::vector<std::string>(1, defaultDir)),
98  "a directory or a list of files to scan")
99  //(kAllCommandOpt, "when no paths given, try to update caches for all known directories [default is to only scan the first directory]")
100  ;
101 
102  positional_options_description p;
103  p.add(kPathsOpt, -1);
104 
105  variables_map vm;
106  try {
107  store(command_line_parser(argc, argv).options(desc).positional(p).run(), vm);
108  notify(vm);
109  } catch (error const& iException) {
110  std::cerr << iException.what();
111  return 1;
112  }
113 
114  if (vm.count(kHelpOpt)) {
115  std::cout << desc << std::endl;
116  return 0;
117  }
118 
119  using std::filesystem::path;
120 
121  /*if(argc == 1) {
122  std::cerr << "Requires at least one argument. Please pass either one directory or a list of files (all in the same directory)." << std::endl;
123  return 1;
124  } */
125 
126  int returnValue = EXIT_SUCCESS;
127 
128  try {
129  std::vector<std::string> requestedPaths(vm[kPathsOpt].as<std::vector<std::string> >());
130 
131  //first find the directory and create a list of files to look at in that directory
132  path directory(requestedPaths[0]);
133  std::vector<std::string> files;
134  bool removeMissingFiles = false;
135  if (std::filesystem::is_directory(directory)) {
136  if (requestedPaths.size() > 1) {
137  std::cerr << "if a directory is given then only one argument is allowed" << std::endl;
138  return 1;
139  }
140 
141  //if asked to look at whole directory, then we can also remove missing files
142  removeMissingFiles = true;
143 
144  std::filesystem::directory_iterator file(directory);
145  std::filesystem::directory_iterator end;
146 
147  path cacheFile(directory);
148  cacheFile /= standard::cachefileName();
149 
150  std::filesystem::file_time_type cacheLastChange = std::filesystem::file_time_type::min();
151  if (exists(cacheFile)) {
152  cacheLastChange = last_write_time(cacheFile);
153  }
154  for (; file != end; ++file) {
155  path filename(*file);
156  path shortName(file->path().filename());
157  const std::string& stringName = shortName.string();
158 
159  static std::string const kPluginPrefix(standard::pluginPrefix());
160  if (stringName.size() < kPluginPrefix.size()) {
161  continue;
162  }
163  if (stringName.substr(0, kPluginPrefix.size()) != kPluginPrefix) {
164  continue;
165  }
166 
167  if (last_write_time(filename) > cacheLastChange) {
168  files.push_back(stringName);
169  }
170  }
171  } else {
172  //we have files
173  directory = directory.parent_path();
174  for (std::vector<std::string>::iterator it = requestedPaths.begin(), itEnd = requestedPaths.end(); it != itEnd;
175  ++it) {
177  if (!exists(f)) {
178  std::cerr << "the file '" << f.string() << "' does not exist" << std::endl;
179  return 1;
180  }
181  if (is_directory(f)) {
182  std::cerr << "either one directory or a list of files are allowed as arguments" << std::endl;
183  return 1;
184  }
185  if (directory != f.parent_path()) {
186  std::cerr << "all files must have be in the same directory (" << directory.string()
187  << ")\n"
188  " the file "
189  << f.string() << " does not." << std::endl;
190  }
191 #if (BOOST_VERSION / 100000) >= 1 && ((BOOST_VERSION / 100) % 1000) >= 47
192  files.push_back(f.filename().string());
193 #else
194  files.push_back(f.leaf());
195 #endif
196  }
197  }
198 
199  path cacheFile(directory);
200  cacheFile /= edmplugin::standard::cachefileName(); //path(s_cacheFile);
201 
203  if (exists(cacheFile)) {
204  std::ifstream cf(cacheFile.string().c_str());
205  if (!cf) {
206  cms::Exception("FailedToOpen") << "unable to open file '" << cacheFile.string()
207  << "' for reading even though it is present.\n"
208  "Please check permissions on the file.";
209  }
210  CacheParser::read(cf, old);
211  }
212 
213  //load each file and 'listen' to which plugins are loaded
214  Listener listener;
216  pfm->newFactory_.connect(std::bind(std::mem_fn(&Listener::newFactory), &listener, _1));
217  edm::for_all(*pfm, std::bind(std::mem_fn(&Listener::newFactory), &listener, _1));
218 
219  // We open the cache file before forking so that all the children will
220  // use it.
221  std::string temporaryFilename = (cacheFile.string() + ".tmp");
222  std::ofstream cf(temporaryFilename.c_str());
223  if (!cf) {
224  cms::Exception("FailedToOpen") << "unable to open file '" << temporaryFilename
225  << "' for writing.\n"
226  "Please check permissions on the file.";
227  }
228  // Sort the files so that they are loaded "by subsystem", hopefully meaning
229  // they share more dependencies.
230  std::sort(files.begin(), files.end());
231 
232  for (size_t fi = 0, fe = files.size(); fi < fe; fi += PER_PROCESS_DSO) {
234  pid_t worker = fork();
235  if (worker == 0) {
236  // This the child process.
237  // We load the DSO and find out its plugins, write to the cache
238  // stream and exit, leaving the parent to spawn a new proces.
239  size_t ci = PER_PROCESS_DSO;
240  while (ci && fi != fe) {
241  path loadableFile(directory);
242  loadableFile /= (files[fi]);
243  listener.nameAndTypes_.clear();
244 
245  try {
246  try {
247  edmplugin::SharedLibrary lib(loadableFile);
248  //PluginCapabilities is special, the plugins do not call it. Instead, for each shared library load
249  // we need to ask it to try to find plugins
251  ltp[files[fi]] = listener.nameAndTypes_;
252 
253  } catch (cms::Exception const& iException) {
254  if (iException.category() == "PluginLibraryLoadError") {
255  std::cerr << "Caught exception " << iException.what() << " will ignore " << files[fi]
256  << " and continue." << std::endl;
257  } else {
258  throw;
259  }
260  }
261  } catch (std::exception& iException) {
262  std::cerr << "Caught exception " << iException.what() << std::endl;
263  exit(1);
264  }
265  ++fi;
266  --ci;
267  }
268  CacheParser::write(ltp, cf);
269  cf << std::flush;
270  _exit(0);
271  } else {
272  // Throw if any of the child died with non 0 status.
273  int status = 0;
274  waitpid(worker, &status, 0);
275  if (WIFEXITED(status) != 0 and WEXITSTATUS(status) != 0) {
276  std::cerr << "Error in child process while processing: " << WEXITSTATUS(status) << std::endl;
277  exit(WEXITSTATUS(status));
278  }
279  if (WIFSIGNALED(status) != 0) {
280  std::cerr << "Child process got signal while processing: " << WTERMSIG(status) << std::endl;
281  exit(128 + WTERMSIG(status));
282  }
283  }
284  }
285 
286  cf << std::flush;
287 
288  // We read the new cache and we merge it with the old one.
290  std::ifstream icf(temporaryFilename.c_str());
291  if (!icf) {
292  cms::Exception("FailedToOpen") << "unable to open file '" << temporaryFilename.c_str()
293  << "' for reading even though it is present.\n"
294  "Please check permissions on the file.";
295  }
296  CacheParser::read(icf, ltp);
297 
298  for (CacheParser::LoadableToPlugins::iterator itFile = ltp.begin(); itFile != ltp.end(); ++itFile) {
299  old[itFile->first] = itFile->second;
300  }
301 
302  // If required, we remove the plugins which are missing. Notice that old is
303  // now the most updated copy of the cache.
304  if (removeMissingFiles) {
305  for (CacheParser::LoadableToPlugins::iterator itFile = old.begin(); itFile != old.end();
306  /*don't advance the iterator here because it may have become invalid */) {
307  path loadableFile(directory);
308  loadableFile /= (itFile->first);
309  if (not exists(loadableFile)) {
310  std::cout << "removing file '" << temporaryFilename.c_str() << "'" << std::endl;
311  CacheParser::LoadableToPlugins::iterator itToItemBeingRemoved = itFile;
312  //advance the iterator while it is still valid
313  ++itFile;
314  old.erase(itToItemBeingRemoved);
315  } else {
316  //since we are not advancing the iterator in the for loop, do it here
317  ++itFile;
318  }
319  }
320  }
321 
322  // We finally write the final cache.
323  std::ofstream fcf(temporaryFilename.c_str());
324  if (!fcf) {
325  cms::Exception("FailedToOpen") << "unable to open file '" << temporaryFilename.c_str()
326  << "' for writing.\n"
327  "Please check permissions on the file.";
328  }
329  CacheParser::write(old, fcf);
330  rename(temporaryFilename.c_str(), cacheFile.string().c_str());
331  } catch (std::exception& iException) {
332  std::cerr << "Caught exception " << iException.what() << std::endl;
333  returnValue = EXIT_FAILURE;
334  }
335 
336  return returnValue;
337 } catch (std::exception const& iException) {
338  std::cerr << iException.what() << std::endl;
339  return 1;
340 }
#define PER_PROCESS_DSO
Definition: refresh.cc:43
Definition: rename.py:1
int main(int argc, char **argv)
Definition: refresh.cc:74
const std::filesystem::path & cachefileName()
Definition: standard.cc:47
bool tryToFind(const SharedLibrary &iLoadable)
Check to see if any capabilities are in the file, returns &#39;true&#39; if found.
static void read(std::istream &, const std::filesystem::path &iDirectory, CategoryToInfos &oOut)
Definition: CacheParser.cc:120
std::string const & category() const
Definition: Exception.cc:147
const std::string & pluginPrefix()
Definition: standard.cc:57
std::pair< std::string, std::string > NameAndType
Definition: CacheParser.h:42
Func for_all(ForwardSequence &s, Func f)
wrapper for std::for_each
Definition: Algorithms.h:14
std::map< std::filesystem::path, NameAndTypes > LoadableToPlugins
Definition: CacheParser.h:44
PluginManager::Config config()
Definition: standard.cc:21
edm::signalslot::Signal< void(const PluginFactoryBase *)> newFactory_
edm::signalslot::Signal< void(const std::string &, const PluginInfo &)> newPluginAdded_
signal containing plugin category, and plugin info for newly added plugin
static PluginCapabilities * get()
double f[11][100]
Definition: value.py:1
static void write(const CategoryToInfos &, std::ostream &)
Definition: CacheParser.cc:142
std::vector< NameAndType > NameAndTypes
Definition: CacheParser.h:43
static const char *const kHelpCommandOpt
Definition: CmsShowMain.cc:106
std::string name_
Definition: PluginInfo.h:29
Config & searchPath(const SearchPath &iPath)
Definition: PluginManager.h:56
char const * what() const noexcept override
Definition: Exception.cc:107
static const char *const kHelpOpt
Definition: CmsShowMain.cc:105
static PluginFactoryManager * get()
def exit(msg="")