blob: 01429b66291976ec0a35f75439adbbe166ae1bf9 [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
13#include <algorithm>
Jonas Olsson55378f42018-05-25 10:23:10 +020014#include <cstdio>
tkchin93411912015-07-22 12:12:17 -070015#include <string>
Yves Gerey988cc082018-10-23 12:03:01 +020016#include <utility>
tkchin93411912015-07-22 12:12:17 -070017
Niels Möller7b3c76b2018-11-07 09:54:28 +010018#if defined(WEBRTC_WIN)
19#include <windows.h>
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
27#include "absl/strings/match.h"
Yves Gerey3e707812018-11-28 16:47:49 +010028#include "absl/types/optional.h"
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020029#include "rtc_base/checks.h"
Yves Gerey2e00abc2018-10-05 15:39:24 +020030#include "rtc_base/logging.h"
tkchin93411912015-07-22 12:12:17 -070031
Jonas Olsson55378f42018-05-25 10:23:10 +020032// Note: We use fprintf for logging in the write paths of this stream to avoid
tkchin93411912015-07-22 12:12:17 -070033// infinite loops when logging.
34
35namespace rtc {
36
Niels Möller7b3c76b2018-11-07 09:54:28 +010037namespace {
38
Niels Möllerd9ac0582019-01-03 14:21:38 +010039const char kCallSessionLogPrefix[] = "webrtc_log";
40
Niels Möller7b3c76b2018-11-07 09:54:28 +010041std::string AddTrailingPathDelimiterIfNeeded(std::string directory);
Niels Möller260770c2018-11-07 15:08:18 +010042
43// |dir| must have a trailing delimiter. |prefix| must not include wild card
44// characters.
45std::vector<std::string> GetFilesWithPrefix(const std::string& directory,
46 const std::string& prefix);
47bool DeleteFile(const std::string& file);
48bool MoveFile(const std::string& old_file, const std::string& new_file);
49bool IsFile(const std::string& file);
Niels Möller7b3c76b2018-11-07 09:54:28 +010050bool IsFolder(const std::string& file);
Niels Möller260770c2018-11-07 15:08:18 +010051absl::optional<size_t> GetFileSize(const std::string& file);
Niels Möller7b3c76b2018-11-07 09:54:28 +010052
53#if defined(WEBRTC_WIN)
54
55std::string AddTrailingPathDelimiterIfNeeded(std::string directory) {
56 if (absl::EndsWith(directory, "\\")) {
57 return directory;
58 }
59 return directory + "\\";
60}
61
Niels Möller260770c2018-11-07 15:08:18 +010062std::vector<std::string> GetFilesWithPrefix(const std::string& directory,
63 const std::string& prefix) {
64 RTC_DCHECK(absl::EndsWith(directory, "\\"));
65 WIN32_FIND_DATA data;
66 HANDLE handle;
67 handle = ::FindFirstFile(ToUtf16(directory + prefix + '*').c_str(), &data);
68 if (handle == INVALID_HANDLE_VALUE)
69 return {};
70
71 std::vector<std::string> file_list;
72 do {
73 file_list.emplace_back(directory + ToUtf8(data.cFileName));
74 } while (::FindNextFile(handle, &data) == TRUE);
75
76 ::FindClose(handle);
77 return file_list;
78}
79
80bool DeleteFile(const std::string& file) {
81 return ::DeleteFile(ToUtf16(file).c_str()) != 0;
82}
83
84bool MoveFile(const std::string& old_file, const std::string& new_file) {
85 return ::MoveFile(ToUtf16(old_file).c_str(), ToUtf16(new_file).c_str()) != 0;
86}
87
88bool IsFile(const std::string& file) {
89 WIN32_FILE_ATTRIBUTE_DATA data = {0};
90 if (0 == ::GetFileAttributesEx(ToUtf16(file).c_str(), GetFileExInfoStandard,
91 &data))
92 return false;
93 return (data.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) == 0;
94}
95
Niels Möller7b3c76b2018-11-07 09:54:28 +010096bool IsFolder(const std::string& file) {
97 WIN32_FILE_ATTRIBUTE_DATA data = {0};
98 if (0 == ::GetFileAttributesEx(ToUtf16(file).c_str(), GetFileExInfoStandard,
99 &data))
100 return false;
101 return (data.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) ==
102 FILE_ATTRIBUTE_DIRECTORY;
103}
104
Niels Möller260770c2018-11-07 15:08:18 +0100105absl::optional<size_t> GetFileSize(const std::string& file) {
106 WIN32_FILE_ATTRIBUTE_DATA data = {0};
107 if (::GetFileAttributesEx(ToUtf16(file).c_str(), GetFileExInfoStandard,
108 &data) == 0)
109 return absl::nullopt;
110 return data.nFileSizeLow;
111}
112
Niels Möller7b3c76b2018-11-07 09:54:28 +0100113#else // defined(WEBRTC_WIN)
114
115std::string AddTrailingPathDelimiterIfNeeded(std::string directory) {
116 if (absl::EndsWith(directory, "/")) {
117 return directory;
118 }
119 return directory + "/";
120}
121
Niels Möller260770c2018-11-07 15:08:18 +0100122std::vector<std::string> GetFilesWithPrefix(const std::string& directory,
123 const std::string& prefix) {
124 RTC_DCHECK(absl::EndsWith(directory, "/"));
125 DIR* dir = ::opendir(directory.c_str());
126 if (dir == nullptr)
127 return {};
128 std::vector<std::string> file_list;
129 for (struct dirent* dirent = ::readdir(dir); dirent;
130 dirent = ::readdir(dir)) {
131 std::string name = dirent->d_name;
132 if (name.compare(0, prefix.size(), prefix) == 0) {
133 file_list.emplace_back(directory + name);
134 }
135 }
136 ::closedir(dir);
137 return file_list;
138}
139
140bool DeleteFile(const std::string& file) {
141 return ::unlink(file.c_str()) == 0;
142}
143
144bool MoveFile(const std::string& old_file, const std::string& new_file) {
145 return ::rename(old_file.c_str(), new_file.c_str()) == 0;
146}
147
148bool IsFile(const std::string& file) {
149 struct stat st;
150 int res = ::stat(file.c_str(), &st);
151 // Treat symlinks, named pipes, etc. all as files.
152 return res == 0 && !S_ISDIR(st.st_mode);
153}
154
Niels Möller7b3c76b2018-11-07 09:54:28 +0100155bool IsFolder(const std::string& file) {
156 struct stat st;
157 int res = ::stat(file.c_str(), &st);
158 return res == 0 && S_ISDIR(st.st_mode);
159}
160
Niels Möller260770c2018-11-07 15:08:18 +0100161absl::optional<size_t> GetFileSize(const std::string& file) {
162 struct stat st;
163 if (::stat(file.c_str(), &st) != 0)
164 return absl::nullopt;
165 return st.st_size;
166}
167
Niels Möller7b3c76b2018-11-07 09:54:28 +0100168#endif
169
170} // namespace
171
tkchin93411912015-07-22 12:12:17 -0700172FileRotatingStream::FileRotatingStream(const std::string& dir_path,
tkchin93411912015-07-22 12:12:17 -0700173 const std::string& file_prefix,
174 size_t max_file_size,
175 size_t num_files)
Niels Möller7b3c76b2018-11-07 09:54:28 +0100176 : dir_path_(AddTrailingPathDelimiterIfNeeded(dir_path)),
tkchin93411912015-07-22 12:12:17 -0700177 file_prefix_(file_prefix),
tkchin93411912015-07-22 12:12:17 -0700178 file_stream_(nullptr),
179 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 {
tkchin93411912015-07-22 12:12:17 -0700197 if (!file_stream_) {
198 return SS_CLOSED;
199 }
200 return file_stream_->GetState();
201}
202
203StreamResult FileRotatingStream::Read(void* buffer,
204 size_t buffer_len,
205 size_t* read,
206 int* error) {
henrikg91d6ede2015-09-17 00:24:34 -0700207 RTC_DCHECK(buffer);
Niels Möller6ffe62a2019-01-08 13:22:57 +0100208 RTC_NOTREACHED();
209 return SR_EOS;
tkchin93411912015-07-22 12:12:17 -0700210}
211
212StreamResult FileRotatingStream::Write(const void* data,
213 size_t data_len,
214 size_t* written,
215 int* error) {
tkchin93411912015-07-22 12:12:17 -0700216 if (!file_stream_) {
Jonas Olsson55378f42018-05-25 10:23:10 +0200217 std::fprintf(stderr, "Open() must be called before Write.\n");
tkchin93411912015-07-22 12:12:17 -0700218 return SR_ERROR;
219 }
220 // Write as much as will fit in to the current file.
henrikg91d6ede2015-09-17 00:24:34 -0700221 RTC_DCHECK_LT(current_bytes_written_, max_file_size_);
tkchin93411912015-07-22 12:12:17 -0700222 size_t remaining_bytes = max_file_size_ - current_bytes_written_;
223 size_t write_length = std::min(data_len, remaining_bytes);
224 size_t local_written = 0;
225 if (!written) {
226 written = &local_written;
227 }
228 StreamResult result = file_stream_->Write(data, write_length, written, error);
229 current_bytes_written_ += *written;
230
231 // If we're done with this file, rotate it out.
232 if (current_bytes_written_ >= max_file_size_) {
henrikg91d6ede2015-09-17 00:24:34 -0700233 RTC_DCHECK_EQ(current_bytes_written_, max_file_size_);
tkchin93411912015-07-22 12:12:17 -0700234 RotateFiles();
235 }
236 return result;
237}
238
239bool FileRotatingStream::Flush() {
240 if (!file_stream_) {
241 return false;
242 }
243 return file_stream_->Flush();
244}
245
tkchin93411912015-07-22 12:12:17 -0700246void FileRotatingStream::Close() {
247 CloseCurrentFile();
248}
249
250bool FileRotatingStream::Open() {
Niels Möller6ffe62a2019-01-08 13:22:57 +0100251 // Delete existing files when opening for write.
252 std::vector<std::string> matching_files =
253 GetFilesWithPrefix(dir_path_, file_prefix_);
254 for (const auto& matching_file : matching_files) {
255 if (!DeleteFile(matching_file)) {
256 std::fprintf(stderr, "Failed to delete: %s\n", matching_file.c_str());
tkchin93411912015-07-22 12:12:17 -0700257 }
258 }
Niels Möller6ffe62a2019-01-08 13:22:57 +0100259 return OpenCurrentFile();
tkchin93411912015-07-22 12:12:17 -0700260}
261
262bool FileRotatingStream::DisableBuffering() {
263 disable_buffering_ = true;
264 if (!file_stream_) {
Jonas Olsson55378f42018-05-25 10:23:10 +0200265 std::fprintf(stderr, "Open() must be called before DisableBuffering().\n");
tkchin93411912015-07-22 12:12:17 -0700266 return false;
267 }
268 return file_stream_->DisableBuffering();
269}
270
271std::string FileRotatingStream::GetFilePath(size_t index) const {
henrikg91d6ede2015-09-17 00:24:34 -0700272 RTC_DCHECK_LT(index, file_names_.size());
tkchin93411912015-07-22 12:12:17 -0700273 return file_names_[index];
274}
275
276bool FileRotatingStream::OpenCurrentFile() {
277 CloseCurrentFile();
278
279 // Opens the appropriate file in the appropriate mode.
henrikg91d6ede2015-09-17 00:24:34 -0700280 RTC_DCHECK_LT(current_file_index_, file_names_.size());
tkchin93411912015-07-22 12:12:17 -0700281 std::string file_path = file_names_[current_file_index_];
282 file_stream_.reset(new FileStream());
Niels Möller6ffe62a2019-01-08 13:22:57 +0100283
284 // We should always be writing to the zero-th file.
285 RTC_DCHECK_EQ(current_file_index_, 0);
tkchin93411912015-07-22 12:12:17 -0700286 int error = 0;
Niels Möller6ffe62a2019-01-08 13:22:57 +0100287 if (!file_stream_->Open(file_path, "w+", &error)) {
Jonas Olsson55378f42018-05-25 10:23:10 +0200288 std::fprintf(stderr, "Failed to open: %s Error: %i\n", file_path.c_str(),
289 error);
tkchin93411912015-07-22 12:12:17 -0700290 file_stream_.reset();
291 return false;
292 }
293 if (disable_buffering_) {
294 file_stream_->DisableBuffering();
295 }
296 return true;
297}
298
299void FileRotatingStream::CloseCurrentFile() {
300 if (!file_stream_) {
301 return;
302 }
303 current_bytes_written_ = 0;
304 file_stream_.reset();
305}
306
307void FileRotatingStream::RotateFiles() {
tkchin93411912015-07-22 12:12:17 -0700308 CloseCurrentFile();
309 // Rotates the files by deleting the file at |rotation_index_|, which is the
310 // oldest file and then renaming the newer files to have an incremented index.
311 // See header file comments for example.
hayscd02b0fa2015-12-08 13:59:05 -0800312 RTC_DCHECK_LT(rotation_index_, file_names_.size());
tkchin93411912015-07-22 12:12:17 -0700313 std::string file_to_delete = file_names_[rotation_index_];
Niels Möller260770c2018-11-07 15:08:18 +0100314 if (IsFile(file_to_delete)) {
315 if (!DeleteFile(file_to_delete)) {
Jonas Olsson55378f42018-05-25 10:23:10 +0200316 std::fprintf(stderr, "Failed to delete: %s\n", file_to_delete.c_str());
tkchin93411912015-07-22 12:12:17 -0700317 }
318 }
319 for (auto i = rotation_index_; i > 0; --i) {
320 std::string rotated_name = file_names_[i];
321 std::string unrotated_name = file_names_[i - 1];
Niels Möller260770c2018-11-07 15:08:18 +0100322 if (IsFile(unrotated_name)) {
323 if (!MoveFile(unrotated_name, rotated_name)) {
Jonas Olsson55378f42018-05-25 10:23:10 +0200324 std::fprintf(stderr, "Failed to move: %s to %s\n",
325 unrotated_name.c_str(), rotated_name.c_str());
tkchin93411912015-07-22 12:12:17 -0700326 }
327 }
328 }
329 // Create a new file for 0th index.
330 OpenCurrentFile();
331 OnRotation();
332}
333
tkchin93411912015-07-22 12:12:17 -0700334std::string FileRotatingStream::GetFilePath(size_t index,
335 size_t num_files) const {
henrikg91d6ede2015-09-17 00:24:34 -0700336 RTC_DCHECK_LT(index, num_files);
tkchin93411912015-07-22 12:12:17 -0700337
Jonas Olsson671cae22018-06-14 09:57:39 +0200338 const size_t buffer_size = 32;
339 char file_postfix[buffer_size];
340 // We want to zero pad the index so that it will sort nicely.
341 const int max_digits = std::snprintf(nullptr, 0, "%zu", num_files - 1);
342 RTC_DCHECK_LT(1 + max_digits, buffer_size);
343 std::snprintf(file_postfix, buffer_size, "_%0*zu", max_digits, index);
tkchin93411912015-07-22 12:12:17 -0700344
Niels Möller7b3c76b2018-11-07 09:54:28 +0100345 return dir_path_ + file_prefix_ + file_postfix;
tkchin93411912015-07-22 12:12:17 -0700346}
347
348CallSessionFileRotatingStream::CallSessionFileRotatingStream(
tkchin93411912015-07-22 12:12:17 -0700349 const std::string& dir_path,
350 size_t max_total_log_size)
351 : FileRotatingStream(dir_path,
Niels Möllerd9ac0582019-01-03 14:21:38 +0100352 kCallSessionLogPrefix,
tkchin93411912015-07-22 12:12:17 -0700353 max_total_log_size / 2,
354 GetNumRotatingLogFiles(max_total_log_size) + 1),
355 max_total_log_size_(max_total_log_size),
356 num_rotations_(0) {
kwibergaf476c72016-11-28 15:21:39 -0800357 RTC_DCHECK_GE(max_total_log_size, 4);
tkchin93411912015-07-22 12:12:17 -0700358}
359
tkchin93411912015-07-22 12:12:17 -0700360const size_t CallSessionFileRotatingStream::kRotatingLogFileDefaultSize =
361 1024 * 1024;
362
363void CallSessionFileRotatingStream::OnRotation() {
364 ++num_rotations_;
365 if (num_rotations_ == 1) {
366 // On the first rotation adjust the max file size so subsequent files after
367 // the first are smaller.
368 SetMaxFileSize(GetRotatingLogSize(max_total_log_size_));
369 } else if (num_rotations_ == (GetNumFiles() - 1)) {
370 // On the next rotation the very first file is going to be deleted. Change
371 // the rotation index so this doesn't happen.
372 SetRotationIndex(GetRotationIndex() - 1);
373 }
374}
375
376size_t CallSessionFileRotatingStream::GetRotatingLogSize(
377 size_t max_total_log_size) {
378 size_t num_rotating_log_files = GetNumRotatingLogFiles(max_total_log_size);
379 size_t rotating_log_size = num_rotating_log_files > 2
380 ? kRotatingLogFileDefaultSize
381 : max_total_log_size / 4;
382 return rotating_log_size;
383}
384
385size_t CallSessionFileRotatingStream::GetNumRotatingLogFiles(
386 size_t max_total_log_size) {
387 // At minimum have two rotating files. Otherwise split the available log size
388 // evenly across 1MB files.
389 return std::max((size_t)2,
390 (max_total_log_size / 2) / kRotatingLogFileDefaultSize);
391}
392
Niels Möllerd9ac0582019-01-03 14:21:38 +0100393FileRotatingStreamReader::FileRotatingStreamReader(
394 const std::string& dir_path,
395 const std::string& file_prefix) {
396 file_names_ = GetFilesWithPrefix(AddTrailingPathDelimiterIfNeeded(dir_path),
397 file_prefix);
398
399 // Plain sort of the file names would sort by age, i.e., oldest last. Using
400 // std::greater gives us the desired chronological older, oldest first.
401 std::sort(file_names_.begin(), file_names_.end(),
402 std::greater<std::string>());
403}
404
405FileRotatingStreamReader::~FileRotatingStreamReader() = default;
406
407size_t FileRotatingStreamReader::GetSize() const {
408 size_t total_size = 0;
409 for (const auto& file_name : file_names_) {
410 total_size += GetFileSize(file_name).value_or(0);
411 }
412 return total_size;
413}
414
415size_t FileRotatingStreamReader::ReadAll(void* buffer, size_t size) const {
416 size_t done = 0;
417 for (const auto& file_name : file_names_) {
418 if (done < size) {
419 FILE* f = fopen(file_name.c_str(), "rb");
420 if (!f) {
421 break;
422 }
423 done += fread(static_cast<char*>(buffer) + done, 1, size - done, f);
424 fclose(f);
425 } else {
426 break;
427 }
428 }
429 return done;
430}
431
432CallSessionFileRotatingStreamReader::CallSessionFileRotatingStreamReader(
433 const std::string& dir_path)
434 : FileRotatingStreamReader(dir_path, kCallSessionLogPrefix) {}
435
tkchin93411912015-07-22 12:12:17 -0700436} // namespace rtc