blob: 826e6745f332af6d35f18efdb138f209109bcac7 [file] [log] [blame]
tkchin93411912015-07-22 12:12:17 -07001/*
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
Steve Anton10542f22019-01-11 09:11:00 -080011#include "rtc_base/file_rotating_stream.h"
tkchin93411912015-07-22 12:12:17 -070012
Jonas Olsson55378f42018-05-25 10:23:10 +020013#include <cstdio>
tkchin93411912015-07-22 12:12:17 -070014#include <string>
Yves Gerey988cc082018-10-23 12:03:01 +020015#include <utility>
tkchin93411912015-07-22 12:12:17 -070016
Niels Möller7b3c76b2018-11-07 09:54:28 +010017#if defined(WEBRTC_WIN)
18#include <windows.h>
Jonas Olssona4d87372019-07-05 19:08:33 +020019
Steve Anton10542f22019-01-11 09:11:00 -080020#include "rtc_base/string_utils.h"
Niels Möller7b3c76b2018-11-07 09:54:28 +010021#else
Niels Möller260770c2018-11-07 15:08:18 +010022#include <dirent.h>
Niels Möller7b3c76b2018-11-07 09:54:28 +010023#include <sys/stat.h>
Niels Möllerb7396662018-11-13 11:55:19 +010024#include <unistd.h>
Niels Möller7b3c76b2018-11-07 09:54:28 +010025#endif // WEBRTC_WIN
26
Steve Anton2acd1632019-03-25 13:48:30 -070027#include "absl/algorithm/container.h"
Niels Möller7b3c76b2018-11-07 09:54:28 +010028#include "absl/strings/match.h"
Yves Gerey3e707812018-11-28 16:47:49 +010029#include "absl/types/optional.h"
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020030#include "rtc_base/checks.h"
Yves Gerey2e00abc2018-10-05 15:39:24 +020031#include "rtc_base/logging.h"
tkchin93411912015-07-22 12:12:17 -070032
Jonas Olsson55378f42018-05-25 10:23:10 +020033// Note: We use fprintf for logging in the write paths of this stream to avoid
tkchin93411912015-07-22 12:12:17 -070034// infinite loops when logging.
35
36namespace rtc {
37
Niels Möller7b3c76b2018-11-07 09:54:28 +010038namespace {
39
Niels Möllerd9ac0582019-01-03 14:21:38 +010040const char kCallSessionLogPrefix[] = "webrtc_log";
41
Niels Möller7b3c76b2018-11-07 09:54:28 +010042std::string AddTrailingPathDelimiterIfNeeded(std::string directory);
Niels Möller260770c2018-11-07 15:08:18 +010043
44// |dir| must have a trailing delimiter. |prefix| must not include wild card
45// characters.
46std::vector<std::string> GetFilesWithPrefix(const std::string& directory,
47 const std::string& prefix);
48bool DeleteFile(const std::string& file);
49bool MoveFile(const std::string& old_file, const std::string& new_file);
50bool IsFile(const std::string& file);
Niels Möller7b3c76b2018-11-07 09:54:28 +010051bool IsFolder(const std::string& file);
Niels Möller260770c2018-11-07 15:08:18 +010052absl::optional<size_t> GetFileSize(const std::string& file);
Niels Möller7b3c76b2018-11-07 09:54:28 +010053
54#if defined(WEBRTC_WIN)
55
56std::string AddTrailingPathDelimiterIfNeeded(std::string directory) {
57 if (absl::EndsWith(directory, "\\")) {
58 return directory;
59 }
60 return directory + "\\";
61}
62
Niels Möller260770c2018-11-07 15:08:18 +010063std::vector<std::string> GetFilesWithPrefix(const std::string& directory,
64 const std::string& prefix) {
65 RTC_DCHECK(absl::EndsWith(directory, "\\"));
Mirko Bonadei673f7e52019-03-25 09:01:02 +010066 WIN32_FIND_DATAW data;
Niels Möller260770c2018-11-07 15:08:18 +010067 HANDLE handle;
Mirko Bonadei673f7e52019-03-25 09:01:02 +010068 handle = ::FindFirstFileW(ToUtf16(directory + prefix + '*').c_str(), &data);
Niels Möller260770c2018-11-07 15:08:18 +010069 if (handle == INVALID_HANDLE_VALUE)
70 return {};
71
72 std::vector<std::string> file_list;
73 do {
74 file_list.emplace_back(directory + ToUtf8(data.cFileName));
Mirko Bonadei673f7e52019-03-25 09:01:02 +010075 } while (::FindNextFileW(handle, &data) == TRUE);
Niels Möller260770c2018-11-07 15:08:18 +010076
77 ::FindClose(handle);
78 return file_list;
79}
80
81bool DeleteFile(const std::string& file) {
Mirko Bonadei673f7e52019-03-25 09:01:02 +010082 return ::DeleteFileW(ToUtf16(file).c_str()) != 0;
Niels Möller260770c2018-11-07 15:08:18 +010083}
84
85bool MoveFile(const std::string& old_file, const std::string& new_file) {
Mirko Bonadei673f7e52019-03-25 09:01:02 +010086 return ::MoveFileW(ToUtf16(old_file).c_str(), ToUtf16(new_file).c_str()) != 0;
Niels Möller260770c2018-11-07 15:08:18 +010087}
88
89bool IsFile(const std::string& file) {
90 WIN32_FILE_ATTRIBUTE_DATA data = {0};
Mirko Bonadei673f7e52019-03-25 09:01:02 +010091 if (0 == ::GetFileAttributesExW(ToUtf16(file).c_str(), GetFileExInfoStandard,
92 &data))
Niels Möller260770c2018-11-07 15:08:18 +010093 return false;
94 return (data.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) == 0;
95}
96
Niels Möller7b3c76b2018-11-07 09:54:28 +010097bool IsFolder(const std::string& file) {
98 WIN32_FILE_ATTRIBUTE_DATA data = {0};
Mirko Bonadei673f7e52019-03-25 09:01:02 +010099 if (0 == ::GetFileAttributesExW(ToUtf16(file).c_str(), GetFileExInfoStandard,
100 &data))
Niels Möller7b3c76b2018-11-07 09:54:28 +0100101 return false;
102 return (data.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) ==
103 FILE_ATTRIBUTE_DIRECTORY;
104}
105
Niels Möller260770c2018-11-07 15:08:18 +0100106absl::optional<size_t> GetFileSize(const std::string& file) {
107 WIN32_FILE_ATTRIBUTE_DATA data = {0};
Mirko Bonadei673f7e52019-03-25 09:01:02 +0100108 if (::GetFileAttributesExW(ToUtf16(file).c_str(), GetFileExInfoStandard,
109 &data) == 0)
Niels Möller260770c2018-11-07 15:08:18 +0100110 return absl::nullopt;
111 return data.nFileSizeLow;
112}
113
Niels Möller7b3c76b2018-11-07 09:54:28 +0100114#else // defined(WEBRTC_WIN)
115
116std::string AddTrailingPathDelimiterIfNeeded(std::string directory) {
117 if (absl::EndsWith(directory, "/")) {
118 return directory;
119 }
120 return directory + "/";
121}
122
Niels Möller260770c2018-11-07 15:08:18 +0100123std::vector<std::string> GetFilesWithPrefix(const std::string& directory,
124 const std::string& prefix) {
125 RTC_DCHECK(absl::EndsWith(directory, "/"));
126 DIR* dir = ::opendir(directory.c_str());
127 if (dir == nullptr)
128 return {};
129 std::vector<std::string> file_list;
130 for (struct dirent* dirent = ::readdir(dir); dirent;
131 dirent = ::readdir(dir)) {
132 std::string name = dirent->d_name;
133 if (name.compare(0, prefix.size(), prefix) == 0) {
134 file_list.emplace_back(directory + name);
135 }
136 }
137 ::closedir(dir);
138 return file_list;
139}
140
141bool DeleteFile(const std::string& file) {
142 return ::unlink(file.c_str()) == 0;
143}
144
145bool MoveFile(const std::string& old_file, const std::string& new_file) {
146 return ::rename(old_file.c_str(), new_file.c_str()) == 0;
147}
148
149bool IsFile(const std::string& file) {
150 struct stat st;
151 int res = ::stat(file.c_str(), &st);
152 // Treat symlinks, named pipes, etc. all as files.
153 return res == 0 && !S_ISDIR(st.st_mode);
154}
155
Niels Möller7b3c76b2018-11-07 09:54:28 +0100156bool IsFolder(const std::string& file) {
157 struct stat st;
158 int res = ::stat(file.c_str(), &st);
159 return res == 0 && S_ISDIR(st.st_mode);
160}
161
Niels Möller260770c2018-11-07 15:08:18 +0100162absl::optional<size_t> GetFileSize(const std::string& file) {
163 struct stat st;
164 if (::stat(file.c_str(), &st) != 0)
165 return absl::nullopt;
166 return st.st_size;
167}
168
Niels Möller7b3c76b2018-11-07 09:54:28 +0100169#endif
170
171} // namespace
172
tkchin93411912015-07-22 12:12:17 -0700173FileRotatingStream::FileRotatingStream(const std::string& dir_path,
tkchin93411912015-07-22 12:12:17 -0700174 const std::string& file_prefix,
175 size_t max_file_size,
176 size_t num_files)
Niels Möller7b3c76b2018-11-07 09:54:28 +0100177 : dir_path_(AddTrailingPathDelimiterIfNeeded(dir_path)),
tkchin93411912015-07-22 12:12:17 -0700178 file_prefix_(file_prefix),
tkchin93411912015-07-22 12:12:17 -0700179 max_file_size_(max_file_size),
180 current_file_index_(0),
181 rotation_index_(0),
182 current_bytes_written_(0),
183 disable_buffering_(false) {
Niels Möller6ffe62a2019-01-08 13:22:57 +0100184 RTC_DCHECK_GT(max_file_size, 0);
185 RTC_DCHECK_GT(num_files, 1);
Niels Möller7b3c76b2018-11-07 09:54:28 +0100186 RTC_DCHECK(IsFolder(dir_path));
Niels Möller6ffe62a2019-01-08 13:22:57 +0100187 file_names_.clear();
188 for (size_t i = 0; i < num_files; ++i) {
189 file_names_.push_back(GetFilePath(i, num_files));
tkchin93411912015-07-22 12:12:17 -0700190 }
Niels Möller6ffe62a2019-01-08 13:22:57 +0100191 rotation_index_ = num_files - 1;
tkchin93411912015-07-22 12:12:17 -0700192}
193
Yves Gerey665174f2018-06-19 15:03:05 +0200194FileRotatingStream::~FileRotatingStream() {}
tkchin93411912015-07-22 12:12:17 -0700195
196StreamState FileRotatingStream::GetState() const {
Niels Möller23213d92019-01-22 11:01:24 +0100197 return (file_.is_open() ? SS_OPEN : SS_CLOSED);
tkchin93411912015-07-22 12:12:17 -0700198}
199
200StreamResult FileRotatingStream::Read(void* buffer,
201 size_t buffer_len,
202 size_t* read,
203 int* error) {
henrikg91d6ede2015-09-17 00:24:34 -0700204 RTC_DCHECK(buffer);
Niels Möller6ffe62a2019-01-08 13:22:57 +0100205 RTC_NOTREACHED();
206 return SR_EOS;
tkchin93411912015-07-22 12:12:17 -0700207}
208
209StreamResult FileRotatingStream::Write(const void* data,
210 size_t data_len,
211 size_t* written,
212 int* error) {
Niels Möller23213d92019-01-22 11:01:24 +0100213 if (!file_.is_open()) {
Jonas Olsson55378f42018-05-25 10:23:10 +0200214 std::fprintf(stderr, "Open() must be called before Write.\n");
tkchin93411912015-07-22 12:12:17 -0700215 return SR_ERROR;
216 }
217 // Write as much as will fit in to the current file.
henrikg91d6ede2015-09-17 00:24:34 -0700218 RTC_DCHECK_LT(current_bytes_written_, max_file_size_);
tkchin93411912015-07-22 12:12:17 -0700219 size_t remaining_bytes = max_file_size_ - current_bytes_written_;
220 size_t write_length = std::min(data_len, remaining_bytes);
tkchin93411912015-07-22 12:12:17 -0700221
Niels Möller23213d92019-01-22 11:01:24 +0100222 if (!file_.Write(data, write_length)) {
223 return SR_ERROR;
224 }
225 if (disable_buffering_ && !file_.Flush()) {
226 return SR_ERROR;
227 }
228
229 current_bytes_written_ += write_length;
230 if (written) {
231 *written = write_length;
232 }
tkchin93411912015-07-22 12:12:17 -0700233 // If we're done with this file, rotate it out.
234 if (current_bytes_written_ >= max_file_size_) {
henrikg91d6ede2015-09-17 00:24:34 -0700235 RTC_DCHECK_EQ(current_bytes_written_, max_file_size_);
tkchin93411912015-07-22 12:12:17 -0700236 RotateFiles();
237 }
Niels Möller23213d92019-01-22 11:01:24 +0100238 return SR_SUCCESS;
tkchin93411912015-07-22 12:12:17 -0700239}
240
241bool FileRotatingStream::Flush() {
Niels Möller23213d92019-01-22 11:01:24 +0100242 if (!file_.is_open()) {
tkchin93411912015-07-22 12:12:17 -0700243 return false;
244 }
Niels Möller23213d92019-01-22 11:01:24 +0100245 return file_.Flush();
tkchin93411912015-07-22 12:12:17 -0700246}
247
tkchin93411912015-07-22 12:12:17 -0700248void FileRotatingStream::Close() {
249 CloseCurrentFile();
250}
251
252bool FileRotatingStream::Open() {
Niels Möller6ffe62a2019-01-08 13:22:57 +0100253 // Delete existing files when opening for write.
254 std::vector<std::string> matching_files =
255 GetFilesWithPrefix(dir_path_, file_prefix_);
256 for (const auto& matching_file : matching_files) {
257 if (!DeleteFile(matching_file)) {
258 std::fprintf(stderr, "Failed to delete: %s\n", matching_file.c_str());
tkchin93411912015-07-22 12:12:17 -0700259 }
260 }
Niels Möller6ffe62a2019-01-08 13:22:57 +0100261 return OpenCurrentFile();
tkchin93411912015-07-22 12:12:17 -0700262}
263
264bool FileRotatingStream::DisableBuffering() {
265 disable_buffering_ = true;
Niels Möller23213d92019-01-22 11:01:24 +0100266 return true;
tkchin93411912015-07-22 12:12:17 -0700267}
268
269std::string FileRotatingStream::GetFilePath(size_t index) const {
henrikg91d6ede2015-09-17 00:24:34 -0700270 RTC_DCHECK_LT(index, file_names_.size());
tkchin93411912015-07-22 12:12:17 -0700271 return file_names_[index];
272}
273
274bool FileRotatingStream::OpenCurrentFile() {
275 CloseCurrentFile();
276
277 // Opens the appropriate file in the appropriate mode.
henrikg91d6ede2015-09-17 00:24:34 -0700278 RTC_DCHECK_LT(current_file_index_, file_names_.size());
tkchin93411912015-07-22 12:12:17 -0700279 std::string file_path = file_names_[current_file_index_];
Niels Möller6ffe62a2019-01-08 13:22:57 +0100280
281 // We should always be writing to the zero-th file.
282 RTC_DCHECK_EQ(current_file_index_, 0);
Niels Möller23213d92019-01-22 11:01:24 +0100283 int error;
284 file_ = webrtc::FileWrapper::OpenWriteOnly(file_path, &error);
285 if (!file_.is_open()) {
286 std::fprintf(stderr, "Failed to open: %s Error: %d\n", file_path.c_str(),
Jonas Olsson55378f42018-05-25 10:23:10 +0200287 error);
tkchin93411912015-07-22 12:12:17 -0700288 return false;
289 }
tkchin93411912015-07-22 12:12:17 -0700290 return true;
291}
292
293void FileRotatingStream::CloseCurrentFile() {
Niels Möller23213d92019-01-22 11:01:24 +0100294 if (!file_.is_open()) {
tkchin93411912015-07-22 12:12:17 -0700295 return;
296 }
297 current_bytes_written_ = 0;
Niels Möller23213d92019-01-22 11:01:24 +0100298 file_.Close();
tkchin93411912015-07-22 12:12:17 -0700299}
300
301void FileRotatingStream::RotateFiles() {
tkchin93411912015-07-22 12:12:17 -0700302 CloseCurrentFile();
303 // Rotates the files by deleting the file at |rotation_index_|, which is the
304 // oldest file and then renaming the newer files to have an incremented index.
305 // See header file comments for example.
hayscd02b0fa2015-12-08 13:59:05 -0800306 RTC_DCHECK_LT(rotation_index_, file_names_.size());
tkchin93411912015-07-22 12:12:17 -0700307 std::string file_to_delete = file_names_[rotation_index_];
Niels Möller260770c2018-11-07 15:08:18 +0100308 if (IsFile(file_to_delete)) {
309 if (!DeleteFile(file_to_delete)) {
Jonas Olsson55378f42018-05-25 10:23:10 +0200310 std::fprintf(stderr, "Failed to delete: %s\n", file_to_delete.c_str());
tkchin93411912015-07-22 12:12:17 -0700311 }
312 }
313 for (auto i = rotation_index_; i > 0; --i) {
314 std::string rotated_name = file_names_[i];
315 std::string unrotated_name = file_names_[i - 1];
Niels Möller260770c2018-11-07 15:08:18 +0100316 if (IsFile(unrotated_name)) {
317 if (!MoveFile(unrotated_name, rotated_name)) {
Jonas Olsson55378f42018-05-25 10:23:10 +0200318 std::fprintf(stderr, "Failed to move: %s to %s\n",
319 unrotated_name.c_str(), rotated_name.c_str());
tkchin93411912015-07-22 12:12:17 -0700320 }
321 }
322 }
323 // Create a new file for 0th index.
324 OpenCurrentFile();
325 OnRotation();
326}
327
tkchin93411912015-07-22 12:12:17 -0700328std::string FileRotatingStream::GetFilePath(size_t index,
329 size_t num_files) const {
henrikg91d6ede2015-09-17 00:24:34 -0700330 RTC_DCHECK_LT(index, num_files);
tkchin93411912015-07-22 12:12:17 -0700331
Jonas Olsson671cae22018-06-14 09:57:39 +0200332 const size_t buffer_size = 32;
333 char file_postfix[buffer_size];
334 // We want to zero pad the index so that it will sort nicely.
335 const int max_digits = std::snprintf(nullptr, 0, "%zu", num_files - 1);
336 RTC_DCHECK_LT(1 + max_digits, buffer_size);
337 std::snprintf(file_postfix, buffer_size, "_%0*zu", max_digits, index);
tkchin93411912015-07-22 12:12:17 -0700338
Niels Möller7b3c76b2018-11-07 09:54:28 +0100339 return dir_path_ + file_prefix_ + file_postfix;
tkchin93411912015-07-22 12:12:17 -0700340}
341
342CallSessionFileRotatingStream::CallSessionFileRotatingStream(
tkchin93411912015-07-22 12:12:17 -0700343 const std::string& dir_path,
344 size_t max_total_log_size)
345 : FileRotatingStream(dir_path,
Niels Möllerd9ac0582019-01-03 14:21:38 +0100346 kCallSessionLogPrefix,
tkchin93411912015-07-22 12:12:17 -0700347 max_total_log_size / 2,
348 GetNumRotatingLogFiles(max_total_log_size) + 1),
349 max_total_log_size_(max_total_log_size),
350 num_rotations_(0) {
kwibergaf476c72016-11-28 15:21:39 -0800351 RTC_DCHECK_GE(max_total_log_size, 4);
tkchin93411912015-07-22 12:12:17 -0700352}
353
tkchin93411912015-07-22 12:12:17 -0700354const size_t CallSessionFileRotatingStream::kRotatingLogFileDefaultSize =
355 1024 * 1024;
356
357void CallSessionFileRotatingStream::OnRotation() {
358 ++num_rotations_;
359 if (num_rotations_ == 1) {
360 // On the first rotation adjust the max file size so subsequent files after
361 // the first are smaller.
362 SetMaxFileSize(GetRotatingLogSize(max_total_log_size_));
363 } else if (num_rotations_ == (GetNumFiles() - 1)) {
364 // On the next rotation the very first file is going to be deleted. Change
365 // the rotation index so this doesn't happen.
366 SetRotationIndex(GetRotationIndex() - 1);
367 }
368}
369
370size_t CallSessionFileRotatingStream::GetRotatingLogSize(
371 size_t max_total_log_size) {
372 size_t num_rotating_log_files = GetNumRotatingLogFiles(max_total_log_size);
373 size_t rotating_log_size = num_rotating_log_files > 2
374 ? kRotatingLogFileDefaultSize
375 : max_total_log_size / 4;
376 return rotating_log_size;
377}
378
379size_t CallSessionFileRotatingStream::GetNumRotatingLogFiles(
380 size_t max_total_log_size) {
381 // At minimum have two rotating files. Otherwise split the available log size
382 // evenly across 1MB files.
383 return std::max((size_t)2,
384 (max_total_log_size / 2) / kRotatingLogFileDefaultSize);
385}
386
Niels Möllerd9ac0582019-01-03 14:21:38 +0100387FileRotatingStreamReader::FileRotatingStreamReader(
388 const std::string& dir_path,
389 const std::string& file_prefix) {
390 file_names_ = GetFilesWithPrefix(AddTrailingPathDelimiterIfNeeded(dir_path),
391 file_prefix);
392
393 // Plain sort of the file names would sort by age, i.e., oldest last. Using
394 // std::greater gives us the desired chronological older, oldest first.
Steve Anton2acd1632019-03-25 13:48:30 -0700395 absl::c_sort(file_names_, std::greater<std::string>());
Niels Möllerd9ac0582019-01-03 14:21:38 +0100396}
397
398FileRotatingStreamReader::~FileRotatingStreamReader() = default;
399
400size_t FileRotatingStreamReader::GetSize() const {
401 size_t total_size = 0;
402 for (const auto& file_name : file_names_) {
403 total_size += GetFileSize(file_name).value_or(0);
404 }
405 return total_size;
406}
407
408size_t FileRotatingStreamReader::ReadAll(void* buffer, size_t size) const {
409 size_t done = 0;
410 for (const auto& file_name : file_names_) {
411 if (done < size) {
Niels Möller23213d92019-01-22 11:01:24 +0100412 webrtc::FileWrapper f = webrtc::FileWrapper::OpenReadOnly(file_name);
413 if (!f.is_open()) {
Niels Möllerd9ac0582019-01-03 14:21:38 +0100414 break;
415 }
Niels Möller23213d92019-01-22 11:01:24 +0100416 done += f.Read(static_cast<char*>(buffer) + done, size - done);
Niels Möllerd9ac0582019-01-03 14:21:38 +0100417 } else {
418 break;
419 }
420 }
421 return done;
422}
423
424CallSessionFileRotatingStreamReader::CallSessionFileRotatingStreamReader(
425 const std::string& dir_path)
426 : FileRotatingStreamReader(dir_path, kCallSessionLogPrefix) {}
427
tkchin93411912015-07-22 12:12:17 -0700428} // namespace rtc