You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

428 lines
13 KiB

​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
  1. /*
  2. * Copyright 2015 The WebRTC Project Authors. All rights reserved.
  3. *
  4. * Use of this source code is governed by a BSD-style license
  5. * that can be found in the LICENSE file in the root of the source
  6. * tree. An additional intellectual property rights grant can be found
  7. * in the file PATENTS. All contributing project authors may
  8. * be found in the AUTHORS file in the root of the source tree.
  9. */
  10. #include "rtc_base/file_rotating_stream.h"
  11. #include <cstdio>
  12. #include <string>
  13. #include <utility>
  14. #if defined(WEBRTC_WIN)
  15. #include <windows.h>
  16. #include "rtc_base/string_utils.h"
  17. #else
  18. #include <dirent.h>
  19. #include <sys/stat.h>
  20. #include <unistd.h>
  21. #endif // WEBRTC_WIN
  22. #include "absl/algorithm/container.h"
  23. #include "absl/strings/match.h"
  24. #include "absl/types/optional.h"
  25. #include "rtc_base/checks.h"
  26. #include "rtc_base/logging.h"
  27. // Note: We use fprintf for logging in the write paths of this stream to avoid
  28. // infinite loops when logging.
  29. namespace rtc {
  30. namespace {
  31. const char kCallSessionLogPrefix[] = "webrtc_log";
  32. std::string AddTrailingPathDelimiterIfNeeded(std::string directory);
  33. // |dir| must have a trailing delimiter. |prefix| must not include wild card
  34. // characters.
  35. std::vector<std::string> GetFilesWithPrefix(const std::string& directory,
  36. const std::string& prefix);
  37. bool DeleteFile(const std::string& file);
  38. bool MoveFile(const std::string& old_file, const std::string& new_file);
  39. bool IsFile(const std::string& file);
  40. bool IsFolder(const std::string& file);
  41. absl::optional<size_t> GetFileSize(const std::string& file);
  42. #if defined(WEBRTC_WIN)
  43. std::string AddTrailingPathDelimiterIfNeeded(std::string directory) {
  44. if (absl::EndsWith(directory, "\\")) {
  45. return directory;
  46. }
  47. return directory + "\\";
  48. }
  49. std::vector<std::string> GetFilesWithPrefix(const std::string& directory,
  50. const std::string& prefix) {
  51. RTC_DCHECK(absl::EndsWith(directory, "\\"));
  52. WIN32_FIND_DATAW data;
  53. HANDLE handle;
  54. handle = ::FindFirstFileW(ToUtf16(directory + prefix + '*').c_str(), &data);
  55. if (handle == INVALID_HANDLE_VALUE)
  56. return {};
  57. std::vector<std::string> file_list;
  58. do {
  59. file_list.emplace_back(directory + ToUtf8(data.cFileName));
  60. } while (::FindNextFileW(handle, &data) == TRUE);
  61. ::FindClose(handle);
  62. return file_list;
  63. }
  64. bool DeleteFile(const std::string& file) {
  65. return ::DeleteFileW(ToUtf16(file).c_str()) != 0;
  66. }
  67. bool MoveFile(const std::string& old_file, const std::string& new_file) {
  68. return ::MoveFileW(ToUtf16(old_file).c_str(), ToUtf16(new_file).c_str()) != 0;
  69. }
  70. bool IsFile(const std::string& file) {
  71. WIN32_FILE_ATTRIBUTE_DATA data = {0};
  72. if (0 == ::GetFileAttributesExW(ToUtf16(file).c_str(), GetFileExInfoStandard,
  73. &data))
  74. return false;
  75. return (data.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) == 0;
  76. }
  77. bool IsFolder(const std::string& file) {
  78. WIN32_FILE_ATTRIBUTE_DATA data = {0};
  79. if (0 == ::GetFileAttributesExW(ToUtf16(file).c_str(), GetFileExInfoStandard,
  80. &data))
  81. return false;
  82. return (data.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) ==
  83. FILE_ATTRIBUTE_DIRECTORY;
  84. }
  85. absl::optional<size_t> GetFileSize(const std::string& file) {
  86. WIN32_FILE_ATTRIBUTE_DATA data = {0};
  87. if (::GetFileAttributesExW(ToUtf16(file).c_str(), GetFileExInfoStandard,
  88. &data) == 0)
  89. return absl::nullopt;
  90. return data.nFileSizeLow;
  91. }
  92. #else // defined(WEBRTC_WIN)
  93. std::string AddTrailingPathDelimiterIfNeeded(std::string directory) {
  94. if (absl::EndsWith(directory, "/")) {
  95. return directory;
  96. }
  97. return directory + "/";
  98. }
  99. std::vector<std::string> GetFilesWithPrefix(const std::string& directory,
  100. const std::string& prefix) {
  101. RTC_DCHECK(absl::EndsWith(directory, "/"));
  102. DIR* dir = ::opendir(directory.c_str());
  103. if (dir == nullptr)
  104. return {};
  105. std::vector<std::string> file_list;
  106. for (struct dirent* dirent = ::readdir(dir); dirent;
  107. dirent = ::readdir(dir)) {
  108. std::string name = dirent->d_name;
  109. if (name.compare(0, prefix.size(), prefix) == 0) {
  110. file_list.emplace_back(directory + name);
  111. }
  112. }
  113. ::closedir(dir);
  114. return file_list;
  115. }
  116. bool DeleteFile(const std::string& file) {
  117. return ::unlink(file.c_str()) == 0;
  118. }
  119. bool MoveFile(const std::string& old_file, const std::string& new_file) {
  120. return ::rename(old_file.c_str(), new_file.c_str()) == 0;
  121. }
  122. bool IsFile(const std::string& file) {
  123. struct stat st;
  124. int res = ::stat(file.c_str(), &st);
  125. // Treat symlinks, named pipes, etc. all as files.
  126. return res == 0 && !S_ISDIR(st.st_mode);
  127. }
  128. bool IsFolder(const std::string& file) {
  129. struct stat st;
  130. int res = ::stat(file.c_str(), &st);
  131. return res == 0 && S_ISDIR(st.st_mode);
  132. }
  133. absl::optional<size_t> GetFileSize(const std::string& file) {
  134. struct stat st;
  135. if (::stat(file.c_str(), &st) != 0)
  136. return absl::nullopt;
  137. return st.st_size;
  138. }
  139. #endif
  140. } // namespace
  141. FileRotatingStream::FileRotatingStream(const std::string& dir_path,
  142. const std::string& file_prefix,
  143. size_t max_file_size,
  144. size_t num_files)
  145. : dir_path_(AddTrailingPathDelimiterIfNeeded(dir_path)),
  146. file_prefix_(file_prefix),
  147. max_file_size_(max_file_size),
  148. current_file_index_(0),
  149. rotation_index_(0),
  150. current_bytes_written_(0),
  151. disable_buffering_(false) {
  152. RTC_DCHECK_GT(max_file_size, 0);
  153. RTC_DCHECK_GT(num_files, 1);
  154. RTC_DCHECK(IsFolder(dir_path));
  155. file_names_.clear();
  156. for (size_t i = 0; i < num_files; ++i) {
  157. file_names_.push_back(GetFilePath(i, num_files));
  158. }
  159. rotation_index_ = num_files - 1;
  160. }
  161. FileRotatingStream::~FileRotatingStream() {}
  162. StreamState FileRotatingStream::GetState() const {
  163. return (file_.is_open() ? SS_OPEN : SS_CLOSED);
  164. }
  165. StreamResult FileRotatingStream::Read(void* buffer,
  166. size_t buffer_len,
  167. size_t* read,
  168. int* error) {
  169. RTC_DCHECK(buffer);
  170. RTC_NOTREACHED();
  171. return SR_EOS;
  172. }
  173. StreamResult FileRotatingStream::Write(const void* data,
  174. size_t data_len,
  175. size_t* written,
  176. int* error) {
  177. if (!file_.is_open()) {
  178. std::fprintf(stderr, "Open() must be called before Write.\n");
  179. return SR_ERROR;
  180. }
  181. // Write as much as will fit in to the current file.
  182. RTC_DCHECK_LT(current_bytes_written_, max_file_size_);
  183. size_t remaining_bytes = max_file_size_ - current_bytes_written_;
  184. size_t write_length = std::min(data_len, remaining_bytes);
  185. if (!file_.Write(data, write_length)) {
  186. return SR_ERROR;
  187. }
  188. if (disable_buffering_ && !file_.Flush()) {
  189. return SR_ERROR;
  190. }
  191. current_bytes_written_ += write_length;
  192. if (written) {
  193. *written = write_length;
  194. }
  195. // If we're done with this file, rotate it out.
  196. if (current_bytes_written_ >= max_file_size_) {
  197. RTC_DCHECK_EQ(current_bytes_written_, max_file_size_);
  198. RotateFiles();
  199. }
  200. return SR_SUCCESS;
  201. }
  202. bool FileRotatingStream::Flush() {
  203. if (!file_.is_open()) {
  204. return false;
  205. }
  206. return file_.Flush();
  207. }
  208. void FileRotatingStream::Close() {
  209. CloseCurrentFile();
  210. }
  211. bool FileRotatingStream::Open() {
  212. // Delete existing files when opening for write.
  213. std::vector<std::string> matching_files =
  214. GetFilesWithPrefix(dir_path_, file_prefix_);
  215. for (const auto& matching_file : matching_files) {
  216. if (!DeleteFile(matching_file)) {
  217. std::fprintf(stderr, "Failed to delete: %s\n", matching_file.c_str());
  218. }
  219. }
  220. return OpenCurrentFile();
  221. }
  222. bool FileRotatingStream::DisableBuffering() {
  223. disable_buffering_ = true;
  224. return true;
  225. }
  226. std::string FileRotatingStream::GetFilePath(size_t index) const {
  227. RTC_DCHECK_LT(index, file_names_.size());
  228. return file_names_[index];
  229. }
  230. bool FileRotatingStream::OpenCurrentFile() {
  231. CloseCurrentFile();
  232. // Opens the appropriate file in the appropriate mode.
  233. RTC_DCHECK_LT(current_file_index_, file_names_.size());
  234. std::string file_path = file_names_[current_file_index_];
  235. // We should always be writing to the zero-th file.
  236. RTC_DCHECK_EQ(current_file_index_, 0);
  237. int error;
  238. file_ = webrtc::FileWrapper::OpenWriteOnly(file_path, &error);
  239. if (!file_.is_open()) {
  240. std::fprintf(stderr, "Failed to open: %s Error: %d\n", file_path.c_str(),
  241. error);
  242. return false;
  243. }
  244. return true;
  245. }
  246. void FileRotatingStream::CloseCurrentFile() {
  247. if (!file_.is_open()) {
  248. return;
  249. }
  250. current_bytes_written_ = 0;
  251. file_.Close();
  252. }
  253. void FileRotatingStream::RotateFiles() {
  254. CloseCurrentFile();
  255. // Rotates the files by deleting the file at |rotation_index_|, which is the
  256. // oldest file and then renaming the newer files to have an incremented index.
  257. // See header file comments for example.
  258. RTC_DCHECK_LT(rotation_index_, file_names_.size());
  259. std::string file_to_delete = file_names_[rotation_index_];
  260. if (IsFile(file_to_delete)) {
  261. if (!DeleteFile(file_to_delete)) {
  262. std::fprintf(stderr, "Failed to delete: %s\n", file_to_delete.c_str());
  263. }
  264. }
  265. for (auto i = rotation_index_; i > 0; --i) {
  266. std::string rotated_name = file_names_[i];
  267. std::string unrotated_name = file_names_[i - 1];
  268. if (IsFile(unrotated_name)) {
  269. if (!MoveFile(unrotated_name, rotated_name)) {
  270. std::fprintf(stderr, "Failed to move: %s to %s\n",
  271. unrotated_name.c_str(), rotated_name.c_str());
  272. }
  273. }
  274. }
  275. // Create a new file for 0th index.
  276. OpenCurrentFile();
  277. OnRotation();
  278. }
  279. std::string FileRotatingStream::GetFilePath(size_t index,
  280. size_t num_files) const {
  281. RTC_DCHECK_LT(index, num_files);
  282. const size_t buffer_size = 32;
  283. char file_postfix[buffer_size];
  284. // We want to zero pad the index so that it will sort nicely.
  285. const int max_digits = std::snprintf(nullptr, 0, "%zu", num_files - 1);
  286. RTC_DCHECK_LT(1 + max_digits, buffer_size);
  287. std::snprintf(file_postfix, buffer_size, "_%0*zu", max_digits, index);
  288. return dir_path_ + file_prefix_ + file_postfix;
  289. }
  290. CallSessionFileRotatingStream::CallSessionFileRotatingStream(
  291. const std::string& dir_path,
  292. size_t max_total_log_size)
  293. : FileRotatingStream(dir_path,
  294. kCallSessionLogPrefix,
  295. max_total_log_size / 2,
  296. GetNumRotatingLogFiles(max_total_log_size) + 1),
  297. max_total_log_size_(max_total_log_size),
  298. num_rotations_(0) {
  299. RTC_DCHECK_GE(max_total_log_size, 4);
  300. }
  301. const size_t CallSessionFileRotatingStream::kRotatingLogFileDefaultSize =
  302. 1024 * 1024;
  303. void CallSessionFileRotatingStream::OnRotation() {
  304. ++num_rotations_;
  305. if (num_rotations_ == 1) {
  306. // On the first rotation adjust the max file size so subsequent files after
  307. // the first are smaller.
  308. SetMaxFileSize(GetRotatingLogSize(max_total_log_size_));
  309. } else if (num_rotations_ == (GetNumFiles() - 1)) {
  310. // On the next rotation the very first file is going to be deleted. Change
  311. // the rotation index so this doesn't happen.
  312. SetRotationIndex(GetRotationIndex() - 1);
  313. }
  314. }
  315. size_t CallSessionFileRotatingStream::GetRotatingLogSize(
  316. size_t max_total_log_size) {
  317. size_t num_rotating_log_files = GetNumRotatingLogFiles(max_total_log_size);
  318. size_t rotating_log_size = num_rotating_log_files > 2
  319. ? kRotatingLogFileDefaultSize
  320. : max_total_log_size / 4;
  321. return rotating_log_size;
  322. }
  323. size_t CallSessionFileRotatingStream::GetNumRotatingLogFiles(
  324. size_t max_total_log_size) {
  325. // At minimum have two rotating files. Otherwise split the available log size
  326. // evenly across 1MB files.
  327. return std::max((size_t)2,
  328. (max_total_log_size / 2) / kRotatingLogFileDefaultSize);
  329. }
  330. FileRotatingStreamReader::FileRotatingStreamReader(
  331. const std::string& dir_path,
  332. const std::string& file_prefix) {
  333. file_names_ = GetFilesWithPrefix(AddTrailingPathDelimiterIfNeeded(dir_path),
  334. file_prefix);
  335. // Plain sort of the file names would sort by age, i.e., oldest last. Using
  336. // std::greater gives us the desired chronological older, oldest first.
  337. absl::c_sort(file_names_, std::greater<std::string>());
  338. }
  339. FileRotatingStreamReader::~FileRotatingStreamReader() = default;
  340. size_t FileRotatingStreamReader::GetSize() const {
  341. size_t total_size = 0;
  342. for (const auto& file_name : file_names_) {
  343. total_size += GetFileSize(file_name).value_or(0);
  344. }
  345. return total_size;
  346. }
  347. size_t FileRotatingStreamReader::ReadAll(void* buffer, size_t size) const {
  348. size_t done = 0;
  349. for (const auto& file_name : file_names_) {
  350. if (done < size) {
  351. webrtc::FileWrapper f = webrtc::FileWrapper::OpenReadOnly(file_name);
  352. if (!f.is_open()) {
  353. break;
  354. }
  355. done += f.Read(static_cast<char*>(buffer) + done, size - done);
  356. } else {
  357. break;
  358. }
  359. }
  360. return done;
  361. }
  362. CallSessionFileRotatingStreamReader::CallSessionFileRotatingStreamReader(
  363. const std::string& dir_path)
  364. : FileRotatingStreamReader(dir_path, kCallSessionLogPrefix) {}
  365. } // namespace rtc