auto_roll_logger.cc 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366
  1. // Copyright (c) 2011-present, Facebook, Inc. All rights reserved.
  2. // This source code is licensed under both the GPLv2 (found in the
  3. // COPYING file in the root directory) and Apache 2.0 License
  4. // (found in the LICENSE.Apache file in the root directory).
  5. //
  6. #include "logging/auto_roll_logger.h"
  7. #include <algorithm>
  8. #include "file/filename.h"
  9. #include "logging/logging.h"
  10. #include "rocksdb/env.h"
  11. #include "rocksdb/file_system.h"
  12. #include "rocksdb/system_clock.h"
  13. #include "util/mutexlock.h"
  14. namespace ROCKSDB_NAMESPACE {
  15. // -- AutoRollLogger
  16. AutoRollLogger::AutoRollLogger(const std::shared_ptr<FileSystem>& fs,
  17. const std::shared_ptr<SystemClock>& clock,
  18. const std::string& dbname,
  19. const std::string& db_log_dir,
  20. size_t log_max_size,
  21. size_t log_file_time_to_roll,
  22. size_t keep_log_file_num,
  23. const InfoLogLevel log_level)
  24. : Logger(log_level),
  25. dbname_(dbname),
  26. db_log_dir_(db_log_dir),
  27. fs_(fs),
  28. clock_(clock),
  29. status_(Status::OK()),
  30. kMaxLogFileSize(log_max_size),
  31. kLogFileTimeToRoll(log_file_time_to_roll),
  32. kKeepLogFileNum(keep_log_file_num),
  33. cached_now(static_cast<uint64_t>(clock_->NowMicros() * 1e-6)),
  34. ctime_(cached_now),
  35. cached_now_access_count(0),
  36. call_NowMicros_every_N_records_(100),
  37. mutex_() {
  38. Status s = fs->GetAbsolutePath(dbname, io_options_, &db_absolute_path_,
  39. &io_context_);
  40. if (s.IsNotSupported()) {
  41. db_absolute_path_ = dbname;
  42. } else {
  43. status_ = s;
  44. }
  45. log_fname_ = InfoLogFileName(dbname_, db_absolute_path_, db_log_dir_);
  46. if (fs_->FileExists(log_fname_, io_options_, &io_context_).ok()) {
  47. RollLogFile();
  48. }
  49. GetExistingFiles();
  50. s = ResetLogger();
  51. if (s.ok() && status_.ok()) {
  52. status_ = TrimOldLogFiles();
  53. }
  54. }
  55. Status AutoRollLogger::ResetLogger() {
  56. TEST_SYNC_POINT("AutoRollLogger::ResetLogger:BeforeNewLogger");
  57. status_ = fs_->NewLogger(log_fname_, io_options_, &logger_, &io_context_);
  58. TEST_SYNC_POINT("AutoRollLogger::ResetLogger:AfterNewLogger");
  59. if (!status_.ok()) {
  60. return status_;
  61. }
  62. assert(logger_);
  63. logger_->SetInfoLogLevel(Logger::GetInfoLogLevel());
  64. if (logger_->GetLogFileSize() == Logger::kDoNotSupportGetLogFileSize) {
  65. status_ = Status::NotSupported(
  66. "The underlying logger doesn't support GetLogFileSize()");
  67. }
  68. if (status_.ok()) {
  69. cached_now = static_cast<uint64_t>(clock_->NowMicros() * 1e-6);
  70. ctime_ = cached_now;
  71. cached_now_access_count = 0;
  72. }
  73. return status_;
  74. }
  75. void AutoRollLogger::RollLogFile() {
  76. // This function is called when log is rotating. Two rotations
  77. // can happen quickly (NowMicro returns same value). To not overwrite
  78. // previous log file we increment by one micro second and try again.
  79. uint64_t now = clock_->NowMicros();
  80. std::string old_fname;
  81. do {
  82. old_fname =
  83. OldInfoLogFileName(dbname_, now, db_absolute_path_, db_log_dir_);
  84. now++;
  85. } while (fs_->FileExists(old_fname, io_options_, &io_context_).ok());
  86. // Wait for logger_ reference count to turn to 1 as it might be pinned by
  87. // Flush. Pinned Logger can't be closed till Flush is completed on that
  88. // Logger.
  89. while (logger_.use_count() > 1) {
  90. }
  91. // Close the existing logger first to release the existing handle
  92. // before renaming the file using the file system. If this call
  93. // fails there is nothing much we can do and we will continue with the
  94. // rename and hence ignoring the result status.
  95. if (logger_) {
  96. logger_->Close().PermitUncheckedError();
  97. }
  98. Status s = fs_->RenameFile(log_fname_, old_fname, io_options_, &io_context_);
  99. if (!s.ok()) {
  100. // What should we do on error?
  101. }
  102. old_log_files_.push(old_fname);
  103. }
  104. void AutoRollLogger::GetExistingFiles() {
  105. {
  106. // Empty the queue to avoid duplicated entries in the queue.
  107. std::queue<std::string> empty;
  108. std::swap(old_log_files_, empty);
  109. }
  110. std::string parent_dir;
  111. std::vector<std::string> info_log_files;
  112. Status s =
  113. GetInfoLogFiles(fs_, db_log_dir_, dbname_, &parent_dir, &info_log_files);
  114. if (status_.ok()) {
  115. status_ = s;
  116. }
  117. // We need to sort the file before enqueing it so that when we
  118. // delete file from the front, it is the oldest file.
  119. std::sort(info_log_files.begin(), info_log_files.end());
  120. for (const std::string& f : info_log_files) {
  121. old_log_files_.push(parent_dir + "/" + f);
  122. }
  123. }
  124. Status AutoRollLogger::TrimOldLogFiles() {
  125. // Here we directly list info files and delete them through FileSystem.
  126. // The deletion isn't going through DB, so there are shortcomes:
  127. // 1. the deletion is not rate limited by SstFileManager
  128. // 2. there is a chance that an I/O will be issued here
  129. // Since it's going to be complicated to pass DB object down to
  130. // here, we take a simple approach to keep the code easier to
  131. // maintain.
  132. // old_log_files_.empty() is helpful for the corner case that
  133. // kKeepLogFileNum == 0. We can instead check kKeepLogFileNum != 0 but
  134. // it's essentially the same thing, and checking empty before accessing
  135. // the queue feels safer.
  136. while (!old_log_files_.empty() && old_log_files_.size() >= kKeepLogFileNum) {
  137. Status s =
  138. fs_->DeleteFile(old_log_files_.front(), io_options_, &io_context_);
  139. // Remove the file from the tracking anyway. It's possible that
  140. // DB cleaned up the old log file, or people cleaned it up manually.
  141. old_log_files_.pop();
  142. // To make the file really go away, we should sync parent directory.
  143. // Since there isn't any consistency issue involved here, skipping
  144. // this part to avoid one I/O here.
  145. if (!s.ok()) {
  146. return s;
  147. }
  148. }
  149. return Status::OK();
  150. }
  151. std::string AutoRollLogger::ValistToString(const char* format,
  152. va_list args) const {
  153. // Any log messages longer than 1024 will get truncated.
  154. // The user is responsible for chopping longer messages into multi line log
  155. static const int MAXBUFFERSIZE = 1024;
  156. char buffer[MAXBUFFERSIZE];
  157. int count = vsnprintf(buffer, MAXBUFFERSIZE, format, args);
  158. (void)count;
  159. assert(count >= 0);
  160. return buffer;
  161. }
  162. void AutoRollLogger::LogInternal(const char* format, ...) {
  163. mutex_.AssertHeld();
  164. if (!logger_) {
  165. return;
  166. }
  167. va_list args;
  168. va_start(args, format);
  169. logger_->Logv(format, args);
  170. va_end(args);
  171. }
  172. void AutoRollLogger::Logv(const char* format, va_list ap) {
  173. std::shared_ptr<Logger> logger;
  174. {
  175. MutexLock l(&mutex_);
  176. assert(GetStatus().ok());
  177. if (!logger_) {
  178. return;
  179. }
  180. if ((kLogFileTimeToRoll > 0 && LogExpired()) ||
  181. (kMaxLogFileSize > 0 && logger_->GetLogFileSize() >= kMaxLogFileSize)) {
  182. RollLogFile();
  183. Status s = ResetLogger();
  184. Status s2 = TrimOldLogFiles();
  185. if (!s.ok()) {
  186. // can't really log the error if creating a new LOG file failed
  187. return;
  188. }
  189. WriteHeaderInfo();
  190. if (!s2.ok()) {
  191. ROCKS_LOG_WARN(logger.get(), "Fail to trim old info log file: %s",
  192. s2.ToString().c_str());
  193. }
  194. }
  195. // pin down the current logger_ instance before releasing the mutex.
  196. logger = logger_;
  197. }
  198. // Another thread could have put a new Logger instance into logger_ by now.
  199. // However, since logger is still hanging on to the previous instance
  200. // (reference count is not zero), we don't have to worry about it being
  201. // deleted while we are accessing it.
  202. // Note that logv itself is not mutex protected to allow maximum concurrency,
  203. // as thread safety should have been handled by the underlying logger.
  204. logger->Logv(format, ap);
  205. }
  206. void AutoRollLogger::WriteHeaderInfo() {
  207. mutex_.AssertHeld();
  208. for (auto& header : headers_) {
  209. LogInternal("%s", header.c_str());
  210. }
  211. }
  212. void AutoRollLogger::LogHeader(const char* format, va_list args) {
  213. // header message are to be retained in memory. Since we cannot make any
  214. // assumptions about the data contained in va_list, we will retain them as
  215. // strings
  216. va_list tmp;
  217. va_copy(tmp, args);
  218. std::string data = ValistToString(format, tmp);
  219. va_end(tmp);
  220. MutexLock l(&mutex_);
  221. if (!logger_) {
  222. return;
  223. }
  224. headers_.push_back(data);
  225. // Log the original message to the current log
  226. logger_->Logv(format, args);
  227. }
  228. bool AutoRollLogger::LogExpired() {
  229. if (cached_now_access_count >= call_NowMicros_every_N_records_) {
  230. cached_now = static_cast<uint64_t>(clock_->NowMicros() * 1e-6);
  231. cached_now_access_count = 0;
  232. }
  233. ++cached_now_access_count;
  234. return cached_now >= ctime_ + kLogFileTimeToRoll;
  235. }
  236. Status CreateLoggerFromOptions(const std::string& dbname,
  237. const DBOptions& options,
  238. std::shared_ptr<Logger>* logger) {
  239. if (options.info_log) {
  240. *logger = options.info_log;
  241. return Status::OK();
  242. }
  243. Env* env = options.env;
  244. std::string db_absolute_path;
  245. Status s = env->GetAbsolutePath(dbname, &db_absolute_path);
  246. TEST_SYNC_POINT_CALLBACK("rocksdb::CreateLoggerFromOptions:AfterGetPath", &s);
  247. if (!s.ok()) {
  248. return s;
  249. }
  250. std::string fname =
  251. InfoLogFileName(dbname, db_absolute_path, options.db_log_dir);
  252. const auto& clock = env->GetSystemClock();
  253. // In case it does not exist.
  254. s = env->CreateDirIfMissing(dbname);
  255. if (!s.ok()) {
  256. if (options.db_log_dir.empty()) {
  257. return s;
  258. } else {
  259. // Ignore the error returned during creation of dbname because dbname and
  260. // db_log_dir can be on different filesystems in which case dbname will
  261. // not exist and error should be ignored. db_log_dir creation will handle
  262. // the error in case there is any error in the creation of dbname on same
  263. // filesystem.
  264. s = Status::OK();
  265. }
  266. }
  267. assert(s.ok());
  268. if (!options.db_log_dir.empty()) {
  269. s = env->CreateDirIfMissing(options.db_log_dir);
  270. if (!s.ok()) {
  271. return s;
  272. }
  273. }
  274. // Currently we only support roll by time-to-roll and log size
  275. if (options.log_file_time_to_roll > 0 || options.max_log_file_size > 0) {
  276. AutoRollLogger* result = new AutoRollLogger(
  277. env->GetFileSystem(), clock, dbname, options.db_log_dir,
  278. options.max_log_file_size, options.log_file_time_to_roll,
  279. options.keep_log_file_num, options.info_log_level);
  280. s = result->GetStatus();
  281. if (!s.ok()) {
  282. delete result;
  283. } else {
  284. logger->reset(result);
  285. }
  286. return s;
  287. }
  288. // Open a log file in the same directory as the db
  289. s = env->FileExists(fname);
  290. if (s.ok()) {
  291. s = env->RenameFile(
  292. fname, OldInfoLogFileName(dbname, clock->NowMicros(), db_absolute_path,
  293. options.db_log_dir));
  294. // The operation sequence of "FileExists -> Rename" is not atomic. It's
  295. // possible that FileExists returns OK but file gets deleted before Rename.
  296. // This can cause Rename to return IOError with subcode PathNotFound.
  297. // Although it may be a rare case and applications should be discouraged
  298. // to not concurrently modifying the contents of the directories accessed
  299. // by the database instance, it is still helpful if we can perform some
  300. // simple handling of this case. Therefore, we do the following:
  301. // 1. if Rename() returns IOError with PathNotFound subcode, then we check
  302. // whether the source file, i.e. LOG, exists.
  303. // 2. if LOG exists, it means Rename() failed due to something else. Then
  304. // we report error.
  305. // 3. if LOG does not exist, it means it may have been removed/renamed by
  306. // someone else. Since it does not exist, we can reset Status to OK so
  307. // that this caller can try creating a new LOG file. If this succeeds,
  308. // we should still allow it.
  309. if (s.IsPathNotFound()) {
  310. s = env->FileExists(fname);
  311. if (s.IsNotFound()) {
  312. s = Status::OK();
  313. }
  314. }
  315. } else if (s.IsNotFound()) {
  316. // "LOG" is not required to exist since this could be a new DB.
  317. s = Status::OK();
  318. }
  319. if (s.ok()) {
  320. s = env->NewLogger(fname, logger);
  321. }
  322. if (s.ok() && logger->get() != nullptr) {
  323. (*logger)->SetInfoLogLevel(options.info_log_level);
  324. }
  325. return s;
  326. }
  327. } // namespace ROCKSDB_NAMESPACE