auto_roll_logger.cc 9.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292
  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 "util/mutexlock.h"
  11. namespace ROCKSDB_NAMESPACE {
  12. #ifndef ROCKSDB_LITE
  13. // -- AutoRollLogger
  14. AutoRollLogger::AutoRollLogger(Env* env, const std::string& dbname,
  15. const std::string& db_log_dir,
  16. size_t log_max_size,
  17. size_t log_file_time_to_roll,
  18. size_t keep_log_file_num,
  19. const InfoLogLevel log_level)
  20. : Logger(log_level),
  21. dbname_(dbname),
  22. db_log_dir_(db_log_dir),
  23. env_(env),
  24. status_(Status::OK()),
  25. kMaxLogFileSize(log_max_size),
  26. kLogFileTimeToRoll(log_file_time_to_roll),
  27. kKeepLogFileNum(keep_log_file_num),
  28. cached_now(static_cast<uint64_t>(env_->NowMicros() * 1e-6)),
  29. ctime_(cached_now),
  30. cached_now_access_count(0),
  31. call_NowMicros_every_N_records_(100),
  32. mutex_() {
  33. Status s = env->GetAbsolutePath(dbname, &db_absolute_path_);
  34. if (s.IsNotSupported()) {
  35. db_absolute_path_ = dbname;
  36. } else {
  37. status_ = s;
  38. }
  39. log_fname_ = InfoLogFileName(dbname_, db_absolute_path_, db_log_dir_);
  40. if (env_->FileExists(log_fname_).ok()) {
  41. RollLogFile();
  42. }
  43. GetExistingFiles();
  44. ResetLogger();
  45. if (status_.ok()) {
  46. status_ = TrimOldLogFiles();
  47. }
  48. }
  49. Status AutoRollLogger::ResetLogger() {
  50. TEST_SYNC_POINT("AutoRollLogger::ResetLogger:BeforeNewLogger");
  51. status_ = env_->NewLogger(log_fname_, &logger_);
  52. TEST_SYNC_POINT("AutoRollLogger::ResetLogger:AfterNewLogger");
  53. if (!status_.ok()) {
  54. return status_;
  55. }
  56. assert(logger_);
  57. logger_->SetInfoLogLevel(Logger::GetInfoLogLevel());
  58. if (logger_->GetLogFileSize() == Logger::kDoNotSupportGetLogFileSize) {
  59. status_ = Status::NotSupported(
  60. "The underlying logger doesn't support GetLogFileSize()");
  61. }
  62. if (status_.ok()) {
  63. cached_now = static_cast<uint64_t>(env_->NowMicros() * 1e-6);
  64. ctime_ = cached_now;
  65. cached_now_access_count = 0;
  66. }
  67. return status_;
  68. }
  69. void AutoRollLogger::RollLogFile() {
  70. // This function is called when log is rotating. Two rotations
  71. // can happen quickly (NowMicro returns same value). To not overwrite
  72. // previous log file we increment by one micro second and try again.
  73. uint64_t now = env_->NowMicros();
  74. std::string old_fname;
  75. do {
  76. old_fname = OldInfoLogFileName(
  77. dbname_, now, db_absolute_path_, db_log_dir_);
  78. now++;
  79. } while (env_->FileExists(old_fname).ok());
  80. env_->RenameFile(log_fname_, old_fname);
  81. old_log_files_.push(old_fname);
  82. }
  83. void AutoRollLogger::GetExistingFiles() {
  84. {
  85. // Empty the queue to avoid duplicated entries in the queue.
  86. std::queue<std::string> empty;
  87. std::swap(old_log_files_, empty);
  88. }
  89. std::string parent_dir;
  90. std::vector<std::string> info_log_files;
  91. Status s =
  92. GetInfoLogFiles(env_, db_log_dir_, dbname_, &parent_dir, &info_log_files);
  93. if (status_.ok()) {
  94. status_ = s;
  95. }
  96. // We need to sort the file before enqueing it so that when we
  97. // delete file from the front, it is the oldest file.
  98. std::sort(info_log_files.begin(), info_log_files.end());
  99. for (const std::string& f : info_log_files) {
  100. old_log_files_.push(parent_dir + "/" + f);
  101. }
  102. }
  103. Status AutoRollLogger::TrimOldLogFiles() {
  104. // Here we directly list info files and delete them through Env.
  105. // The deletion isn't going through DB, so there are shortcomes:
  106. // 1. the deletion is not rate limited by SstFileManager
  107. // 2. there is a chance that an I/O will be issued here
  108. // Since it's going to be complicated to pass DB object down to
  109. // here, we take a simple approach to keep the code easier to
  110. // maintain.
  111. // old_log_files_.empty() is helpful for the corner case that
  112. // kKeepLogFileNum == 0. We can instead check kKeepLogFileNum != 0 but
  113. // it's essentially the same thing, and checking empty before accessing
  114. // the queue feels safer.
  115. while (!old_log_files_.empty() && old_log_files_.size() >= kKeepLogFileNum) {
  116. Status s = env_->DeleteFile(old_log_files_.front());
  117. // Remove the file from the tracking anyway. It's possible that
  118. // DB cleaned up the old log file, or people cleaned it up manually.
  119. old_log_files_.pop();
  120. // To make the file really go away, we should sync parent directory.
  121. // Since there isn't any consistency issue involved here, skipping
  122. // this part to avoid one I/O here.
  123. if (!s.ok()) {
  124. return s;
  125. }
  126. }
  127. return Status::OK();
  128. }
  129. std::string AutoRollLogger::ValistToString(const char* format,
  130. va_list args) const {
  131. // Any log messages longer than 1024 will get truncated.
  132. // The user is responsible for chopping longer messages into multi line log
  133. static const int MAXBUFFERSIZE = 1024;
  134. char buffer[MAXBUFFERSIZE];
  135. int count = vsnprintf(buffer, MAXBUFFERSIZE, format, args);
  136. (void) count;
  137. assert(count >= 0);
  138. return buffer;
  139. }
  140. void AutoRollLogger::LogInternal(const char* format, ...) {
  141. mutex_.AssertHeld();
  142. if (!logger_) {
  143. return;
  144. }
  145. va_list args;
  146. va_start(args, format);
  147. logger_->Logv(format, args);
  148. va_end(args);
  149. }
  150. void AutoRollLogger::Logv(const char* format, va_list ap) {
  151. assert(GetStatus().ok());
  152. if (!logger_) {
  153. return;
  154. }
  155. std::shared_ptr<Logger> logger;
  156. {
  157. MutexLock l(&mutex_);
  158. if ((kLogFileTimeToRoll > 0 && LogExpired()) ||
  159. (kMaxLogFileSize > 0 && logger_->GetLogFileSize() >= kMaxLogFileSize)) {
  160. RollLogFile();
  161. Status s = ResetLogger();
  162. Status s2 = TrimOldLogFiles();
  163. if (!s.ok()) {
  164. // can't really log the error if creating a new LOG file failed
  165. return;
  166. }
  167. WriteHeaderInfo();
  168. if (!s2.ok()) {
  169. ROCKS_LOG_WARN(logger.get(), "Fail to trim old info log file: %s",
  170. s2.ToString().c_str());
  171. }
  172. }
  173. // pin down the current logger_ instance before releasing the mutex.
  174. logger = logger_;
  175. }
  176. // Another thread could have put a new Logger instance into logger_ by now.
  177. // However, since logger is still hanging on to the previous instance
  178. // (reference count is not zero), we don't have to worry about it being
  179. // deleted while we are accessing it.
  180. // Note that logv itself is not mutex protected to allow maximum concurrency,
  181. // as thread safety should have been handled by the underlying logger.
  182. logger->Logv(format, ap);
  183. }
  184. void AutoRollLogger::WriteHeaderInfo() {
  185. mutex_.AssertHeld();
  186. for (auto& header : headers_) {
  187. LogInternal("%s", header.c_str());
  188. }
  189. }
  190. void AutoRollLogger::LogHeader(const char* format, va_list args) {
  191. if (!logger_) {
  192. return;
  193. }
  194. // header message are to be retained in memory. Since we cannot make any
  195. // assumptions about the data contained in va_list, we will retain them as
  196. // strings
  197. va_list tmp;
  198. va_copy(tmp, args);
  199. std::string data = ValistToString(format, tmp);
  200. va_end(tmp);
  201. MutexLock l(&mutex_);
  202. headers_.push_back(data);
  203. // Log the original message to the current log
  204. logger_->Logv(format, args);
  205. }
  206. bool AutoRollLogger::LogExpired() {
  207. if (cached_now_access_count >= call_NowMicros_every_N_records_) {
  208. cached_now = static_cast<uint64_t>(env_->NowMicros() * 1e-6);
  209. cached_now_access_count = 0;
  210. }
  211. ++cached_now_access_count;
  212. return cached_now >= ctime_ + kLogFileTimeToRoll;
  213. }
  214. #endif // !ROCKSDB_LITE
  215. Status CreateLoggerFromOptions(const std::string& dbname,
  216. const DBOptions& options,
  217. std::shared_ptr<Logger>* logger) {
  218. if (options.info_log) {
  219. *logger = options.info_log;
  220. return Status::OK();
  221. }
  222. Env* env = options.env;
  223. std::string db_absolute_path;
  224. env->GetAbsolutePath(dbname, &db_absolute_path);
  225. std::string fname =
  226. InfoLogFileName(dbname, db_absolute_path, options.db_log_dir);
  227. env->CreateDirIfMissing(dbname); // In case it does not exist
  228. // Currently we only support roll by time-to-roll and log size
  229. #ifndef ROCKSDB_LITE
  230. if (options.log_file_time_to_roll > 0 || options.max_log_file_size > 0) {
  231. AutoRollLogger* result = new AutoRollLogger(
  232. env, dbname, options.db_log_dir, options.max_log_file_size,
  233. options.log_file_time_to_roll, options.keep_log_file_num,
  234. options.info_log_level);
  235. Status s = result->GetStatus();
  236. if (!s.ok()) {
  237. delete result;
  238. } else {
  239. logger->reset(result);
  240. }
  241. return s;
  242. }
  243. #endif // !ROCKSDB_LITE
  244. // Open a log file in the same directory as the db
  245. env->RenameFile(fname,
  246. OldInfoLogFileName(dbname, env->NowMicros(), db_absolute_path,
  247. options.db_log_dir));
  248. auto s = env->NewLogger(fname, logger);
  249. if (logger->get() != nullptr) {
  250. (*logger)->SetInfoLogLevel(options.info_log_level);
  251. }
  252. return s;
  253. }
  254. } // namespace ROCKSDB_NAMESPACE