Raven Core  3.0.0
P2P Digital Currency
util.h
Go to the documentation of this file.
1 // Copyright (c) 2009-2010 Satoshi Nakamoto
2 // Copyright (c) 2009-2016 The Bitcoin Core developers
3 // Copyright (c) 2017-2019 The Raven Core developers
4 // Distributed under the MIT software license, see the accompanying
5 // file COPYING or http://www.opensource.org/licenses/mit-license.php.
6 
11 #ifndef RAVEN_UTIL_H
12 #define RAVEN_UTIL_H
13 
14 #if defined(HAVE_CONFIG_H)
15 #include "config/raven-config.h"
16 #endif
17 
18 #include "compat.h"
19 #include "fs.h"
20 #include "sync.h"
21 #include "tinyformat.h"
22 #include "utiltime.h"
23 
24 #include <atomic>
25 #include <exception>
26 #include <map>
27 #include <stdint.h>
28 #include <string>
29 #include <vector>
30 
31 #include <boost/signals2/signal.hpp>
32 
33 // Application startup time (used for uptime calculation)
34 int64_t GetStartupTime();
35 
36 static const bool DEFAULT_LOGTIMEMICROS = false;
37 static const bool DEFAULT_LOGIPS = false;
38 static const bool DEFAULT_LOGTIMESTAMPS = true;
39 
42 {
43 public:
45  boost::signals2::signal<std::string(const char *psz)> Translate;
46 };
47 
48 extern bool fPrintToConsole;
49 extern bool fPrintToDebugLog;
50 
51 extern bool fLogTimestamps;
52 extern bool fLogTimeMicros;
53 extern bool fLogIPs;
54 extern std::atomic<bool> fReopenDebugLog;
56 
57 extern const char *const RAVEN_CONF_FILENAME;
58 extern const char *const RAVEN_PID_FILENAME;
59 
60 extern std::atomic<uint32_t> logCategories;
61 
66 inline std::string _(const char *psz)
67 {
68  boost::optional<std::string> rv = translationInterface.Translate(psz);
69  return rv ? (*rv) : psz;
70 }
71 
72 void SetupEnvironment();
73 
74 bool SetupNetworking();
75 
77 {
78  std::string category;
79  bool active;
80 };
81 
82 namespace BCLog
83 {
84  enum LogFlags : uint32_t
85  {
86  NONE = 0,
87  NET = (1 << 0),
88  TOR = (1 << 1),
89  MEMPOOL = (1 << 2),
90  HTTP = (1 << 3),
91  BENCH = (1 << 4),
92  ZMQ = (1 << 5),
93  DB = (1 << 6),
94  RPC = (1 << 7),
95  ESTIMATEFEE = (1 << 8),
96  ADDRMAN = (1 << 9),
97  SELECTCOINS = (1 << 10),
98  REINDEX = (1 << 11),
99  CMPCTBLOCK = (1 << 12),
100  RAND = (1 << 13),
101  PRUNE = (1 << 14),
102  PROXY = (1 << 15),
103  MEMPOOLREJ = (1 << 16),
104  LIBEVENT = (1 << 17),
105  COINDB = (1 << 18),
106  QT = (1 << 19),
107  LEVELDB = (1 << 20),
108  ALL = ~(uint32_t) 0,
109  };
110 }
111 
113 static inline bool LogAcceptCategory(uint32_t category)
114 {
115  return (logCategories.load(std::memory_order_relaxed) & category) != 0;
116 }
117 
119 std::string ListLogCategories();
120 
122 std::vector<CLogCategoryActive> ListActiveLogCategories();
123 
125 bool GetLogCategory(uint32_t *f, const std::string *str);
126 
128 int LogPrintStr(const std::string &str);
129 
131 template<typename... Args>
132 std::string FormatStringFromLogArgs(const char *fmt, const Args &... args)
133 { return fmt; }
134 
135 static inline void MarkUsed()
136 {}
137 
138 template<typename T, typename... Args>
139 static inline void MarkUsed(const T &t, const Args &... args)
140 {
141  (void) t;
142  MarkUsed(args...);
143 }
144 
145 #ifdef USE_COVERAGE
146 #define LogPrintf(...) do { MarkUsed(__VA_ARGS__); } while(0)
147 #define LogPrint(category, ...) do { MarkUsed(__VA_ARGS__); } while(0)
148 #else
149 #define LogPrintf(...) do { \
150  std::string _log_msg_; /* Unlikely name to avoid shadowing variables */ \
151  try { \
152  _log_msg_ = tfm::format(__VA_ARGS__); \
153  } catch (tinyformat::format_error &fmterr) { \
154  /* Original format string will have newline so don't add one here */ \
155  _log_msg_ = "Error \"" + std::string(fmterr.what()) + "\" while formatting log message: " + FormatStringFromLogArgs(__VA_ARGS__); \
156  } \
157  LogPrintStr(_log_msg_); \
158 } while(0)
159 
160 #define LogPrint(category, ...) do { \
161  if (LogAcceptCategory((category))) { \
162  LogPrintf(__VA_ARGS__); \
163  } \
164 } while(0)
165 #endif
166 
167 template<typename... Args>
168 bool error(const char *fmt, const Args &... args)
169 {
170  LogPrintStr("ERROR: " + tfm::format(fmt, args...) + "\n");
171  return false;
172 }
173 
174 void PrintExceptionContinue(const std::exception *pex, const char *pszThread);
175 
176 void FileCommit(FILE *file);
177 
178 bool TruncateFile(FILE *file, unsigned int length);
179 
180 int RaiseFileDescriptorLimit(int nMinFD);
181 
182 void AllocateFileRange(FILE *file, unsigned int offset, unsigned int length);
183 
184 bool RenameOver(fs::path src, fs::path dest);
185 
186 bool TryCreateDirectories(const fs::path &p);
187 
188 fs::path GetDefaultDataDir();
189 
190 const fs::path &GetDataDir(bool fNetSpecific = true);
191 
192 void ClearDatadirCache();
193 
194 fs::path GetConfigFile(const std::string &confPath);
195 
196 #ifndef WIN32
197 
198 fs::path GetPidFile();
199 
200 void CreatePidFile(const fs::path &path, pid_t pid);
201 
202 #endif
203 #ifdef WIN32
204 fs::path GetSpecialFolderPath(int nFolder, bool fCreate = true);
205 #endif
206 
207 void OpenDebugLog();
208 
209 void ShrinkDebugFile();
210 
211 void runCommand(const std::string &strCommand);
212 
213 inline bool IsSwitchChar(char c)
214 {
215 #ifdef WIN32
216  return c == '-' || c == '/';
217 #else
218  return c == '-';
219 #endif
220 }
221 
223 {
224 protected:
226  std::map<std::string, std::string> mapArgs;
227  std::map<std::string, std::vector<std::string>> mapMultiArgs;
228 public:
229  void ParseParameters(int argc, const char *const argv[]);
230 
231  void ReadConfigFile(const std::string &confPath);
232 
239  std::vector<std::string> GetArgs(const std::string &strArg) const;
240 
247  bool IsArgSet(const std::string &strArg) const;
248 
256  std::string GetArg(const std::string &strArg, const std::string &strDefault) const;
257 
265  int64_t GetArg(const std::string &strArg, int64_t nDefault) const;
266 
274  bool GetBoolArg(const std::string &strArg, bool fDefault) const;
275 
283  bool SoftSetArg(const std::string &strArg, const std::string &strValue);
284 
292  bool SoftSetBoolArg(const std::string &strArg, bool fValue);
293 
294  // Forces an arg setting. Called by SoftSetArg() if the arg hasn't already
295  // been set. Also called directly in testing.
296  void ForceSetArg(const std::string &strArg, const std::string &strValue);
297 };
298 
299 extern ArgsManager gArgs;
300 
307 std::string HelpMessageGroup(const std::string &message);
308 
316 std::string HelpMessageOpt(const std::string &option, const std::string &message);
317 
323 int GetNumCores();
324 
325 void RenameThread(const char *name);
326 
330 template<typename Callable>
331 void TraceThread(const char *name, Callable func)
332 {
333  std::string s = strprintf("raven-%s", name);
334  RenameThread(s.c_str());
335  try
336  {
337  LogPrintf("%s thread start\n", name);
338  func();
339  LogPrintf("%s thread exit\n", name);
340  }
341  catch (const boost::thread_interrupted &)
342  {
343  LogPrintf("%s thread interrupt\n", name);
344  throw;
345  }
346  catch (const std::exception &e)
347  {
348  PrintExceptionContinue(&e, name);
349  throw;
350  }
351  catch (...)
352  {
353  PrintExceptionContinue(nullptr, name);
354  throw;
355  }
356 }
357 
358 std::string CopyrightHolders(const std::string &strPrefix);
359 
360 void SetThreadPriority(int nPriority);
361 
362 #endif // RAVEN_UTIL_H
int64_t GetStartupTime()
Server/client environment: argument handling, config file parsing, logging, thread wrappers...
Definition: util.cpp:930
Definition: util.h:93
Definition: util.h:82
void ShrinkDebugFile()
Definition: util.cpp:799
#define strprintf
Definition: tinyformat.h:1054
bool fPrintToConsole
Definition: util.cpp:95
const QString REINDEX("-reindex")
std::vector< CLogCategoryActive > ListActiveLogCategories()
Returns a vector of the active log categories.
Definition: util.cpp:294
bool SetupNetworking()
Definition: util.cpp:896
void RenameThread(const char *name)
Definition: util.cpp:849
std::atomic< uint32_t > logCategories
std::string HelpMessageGroup(const std::string &message)
Format a string to be used as group of options in help messages.
Definition: util.cpp:506
void SetupEnvironment()
Definition: util.cpp:865
bool TryCreateDirectories(const fs::path &p)
Ignores exceptions thrown by Boost&#39;s create_directories if the requested directory exists...
Definition: util.cpp:684
bool GetLogCategory(uint32_t *f, const std::string *str)
Return true if str parses as a log category and set the flags in f.
Definition: util.cpp:256
fs::path GetDefaultDataDir()
Definition: util.cpp:542
#define LogPrintf(...)
Definition: util.h:149
void CreatePidFile(const fs::path &path, pid_t pid)
Definition: util.cpp:656
void OpenDebugLog()
Definition: util.cpp:198
std::string ListLogCategories()
Returns a string with the log categories.
Definition: util.cpp:277
void format(std::ostream &out, const char *fmt, const Args &... args)
Format list of arguments to the stream according to given format string.
Definition: tinyformat.h:955
void TraceThread(const char *name, Callable func)
Definition: util.h:331
boost::signals2::signal< std::string(const char *psz)> Translate
Translate a message to the native language of the user.
Definition: util.h:45
fs::path GetPidFile()
Definition: util.cpp:649
int GetNumCores()
Return the number of physical cores available on the current system.
Definition: util.cpp:908
CCriticalSection cs_args
Definition: util.h:225
bool fLogIPs
Definition: util.cpp:100
const fs::path & GetDataDir(bool fNetSpecific=true)
Definition: util.cpp:572
void runCommand(const std::string &strCommand)
Definition: util.cpp:841
void SetThreadPriority(int nPriority)
Definition: util.cpp:935
void ClearDatadirCache()
Definition: util.cpp:604
std::map< std::string, std::string > mapArgs
Definition: util.h:226
fs::path GetConfigFile(const std::string &confPath)
Definition: util.cpp:612
bool IsSwitchChar(char c)
Definition: util.h:213
std::atomic< bool > fReopenDebugLog
void PrintExceptionContinue(const std::exception *pex, const char *pszThread)
Definition: util.cpp:535
void FileCommit(FILE *file)
Definition: util.cpp:699
std::map< std::string, std::vector< std::string > > mapMultiArgs
Definition: util.h:227
std::string CopyrightHolders(const std::string &strPrefix)
Definition: util.cpp:917
LogFlags
Definition: util.h:84
Signals for translation.
Definition: util.h:41
std::string category
Definition: util.h:78
bool fLogTimeMicros
Definition: util.cpp:99
bool RenameOver(fs::path src, fs::path dest)
Definition: util.cpp:668
bool error(const char *fmt, const Args &... args)
Definition: util.h:168
int RaiseFileDescriptorLimit(int nMinFD)
this function tries to raise the file descriptor limit to the requested number.
Definition: util.cpp:729
ArgsManager gArgs
Definition: util.cpp:94
void AllocateFileRange(FILE *file, unsigned int offset, unsigned int length)
this function tries to make a particular range of a file allocated (corresponding to disk space) it i...
Definition: util.cpp:755
CTranslationInterface translationInterface
Definition: util.cpp:102
bool TruncateFile(FILE *file, unsigned int length)
Definition: util.cpp:716
int LogPrintStr(const std::string &str)
Send a string to the log output.
Definition: util.cpp:346
const char *const RAVEN_CONF_FILENAME
Definition: util.cpp:91
bool fLogTimestamps
Definition: util.cpp:98
const char *const RAVEN_PID_FILENAME
Definition: util.cpp:92
std::string HelpMessageOpt(const std::string &option, const std::string &message)
Format a string to be used as option description in help messages.
Definition: util.cpp:511
std::string FormatStringFromLogArgs(const char *fmt, const Args &... args)
Get format string from VA_ARGS for error reporting.
Definition: util.h:132
std::string _(const char *psz)
Translation function: Call Translate signal on UI interface, which returns a boost::optional result...
Definition: util.h:66
Wrapped boost mutex: supports recursive locking, but no waiting TODO: We should move away from using ...
Definition: sync.h:92
bool fPrintToDebugLog
Definition: util.cpp:96