blob: c28616d8f6dfb1db68fddd0896b2762742602ce0 [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
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020011#include "rtc_base/filerotatingstream.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
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020018#include "rtc_base/checks.h"
19#include "rtc_base/fileutils.h"
Yves Gerey2e00abc2018-10-05 15:39:24 +020020#include "rtc_base/logging.h"
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020021#include "rtc_base/pathutils.h"
tkchin93411912015-07-22 12:12:17 -070022
Jonas Olsson55378f42018-05-25 10:23:10 +020023// Note: We use fprintf for logging in the write paths of this stream to avoid
tkchin93411912015-07-22 12:12:17 -070024// infinite loops when logging.
25
26namespace rtc {
27
28FileRotatingStream::FileRotatingStream(const std::string& dir_path,
29 const std::string& file_prefix)
Yves Gerey665174f2018-06-19 15:03:05 +020030 : FileRotatingStream(dir_path, file_prefix, 0, 0, kRead) {}
tkchin93411912015-07-22 12:12:17 -070031
32FileRotatingStream::FileRotatingStream(const std::string& dir_path,
33 const std::string& file_prefix,
34 size_t max_file_size,
35 size_t num_files)
36 : FileRotatingStream(dir_path,
37 file_prefix,
38 max_file_size,
39 num_files,
40 kWrite) {
kwibergaf476c72016-11-28 15:21:39 -080041 RTC_DCHECK_GT(max_file_size, 0);
42 RTC_DCHECK_GT(num_files, 1);
tkchin93411912015-07-22 12:12:17 -070043}
44
45FileRotatingStream::FileRotatingStream(const std::string& dir_path,
46 const std::string& file_prefix,
47 size_t max_file_size,
48 size_t num_files,
49 Mode mode)
50 : dir_path_(dir_path),
51 file_prefix_(file_prefix),
52 mode_(mode),
53 file_stream_(nullptr),
54 max_file_size_(max_file_size),
55 current_file_index_(0),
56 rotation_index_(0),
57 current_bytes_written_(0),
58 disable_buffering_(false) {
henrikg91d6ede2015-09-17 00:24:34 -070059 RTC_DCHECK(Filesystem::IsFolder(dir_path));
tkchin93411912015-07-22 12:12:17 -070060 switch (mode) {
61 case kWrite: {
62 file_names_.clear();
63 for (size_t i = 0; i < num_files; ++i) {
64 file_names_.push_back(GetFilePath(i, num_files));
65 }
66 rotation_index_ = num_files - 1;
67 break;
68 }
69 case kRead: {
70 file_names_ = GetFilesWithPrefix();
71 std::sort(file_names_.begin(), file_names_.end());
72 if (file_names_.size() > 0) {
73 // |file_names_| is sorted newest first, so read from the end.
74 current_file_index_ = file_names_.size() - 1;
75 }
76 break;
77 }
78 }
79}
80
Yves Gerey665174f2018-06-19 15:03:05 +020081FileRotatingStream::~FileRotatingStream() {}
tkchin93411912015-07-22 12:12:17 -070082
83StreamState FileRotatingStream::GetState() const {
84 if (mode_ == kRead && current_file_index_ < file_names_.size()) {
85 return SS_OPEN;
86 }
87 if (!file_stream_) {
88 return SS_CLOSED;
89 }
90 return file_stream_->GetState();
91}
92
93StreamResult FileRotatingStream::Read(void* buffer,
94 size_t buffer_len,
95 size_t* read,
96 int* error) {
henrikg91d6ede2015-09-17 00:24:34 -070097 RTC_DCHECK(buffer);
tkchin93411912015-07-22 12:12:17 -070098 if (mode_ != kRead) {
99 return SR_EOS;
100 }
101 if (current_file_index_ >= file_names_.size()) {
102 return SR_EOS;
103 }
104 // We will have no file stream initially, and when we are finished with the
105 // previous file.
106 if (!file_stream_) {
107 if (!OpenCurrentFile()) {
108 return SR_ERROR;
109 }
110 }
111 int local_error = 0;
112 if (!error) {
113 error = &local_error;
114 }
115 StreamResult result = file_stream_->Read(buffer, buffer_len, read, error);
116 if (result == SR_EOS || result == SR_ERROR) {
117 if (result == SR_ERROR) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100118 RTC_LOG(LS_ERROR) << "Failed to read from: "
119 << file_names_[current_file_index_]
120 << "Error: " << error;
tkchin93411912015-07-22 12:12:17 -0700121 }
122 // Reached the end of the file, read next file. If there is an error return
123 // the error status but allow for a next read by reading next file.
124 CloseCurrentFile();
125 if (current_file_index_ == 0) {
126 // Just finished reading the last file, signal EOS by setting index.
127 current_file_index_ = file_names_.size();
128 } else {
129 --current_file_index_;
130 }
131 if (read) {
132 *read = 0;
133 }
134 return result == SR_EOS ? SR_SUCCESS : result;
135 } else if (result == SR_SUCCESS) {
136 // Succeeded, continue reading from this file.
137 return SR_SUCCESS;
138 } else {
139 RTC_NOTREACHED();
140 }
141 return result;
142}
143
144StreamResult FileRotatingStream::Write(const void* data,
145 size_t data_len,
146 size_t* written,
147 int* error) {
148 if (mode_ != kWrite) {
149 return SR_EOS;
150 }
151 if (!file_stream_) {
Jonas Olsson55378f42018-05-25 10:23:10 +0200152 std::fprintf(stderr, "Open() must be called before Write.\n");
tkchin93411912015-07-22 12:12:17 -0700153 return SR_ERROR;
154 }
155 // Write as much as will fit in to the current file.
henrikg91d6ede2015-09-17 00:24:34 -0700156 RTC_DCHECK_LT(current_bytes_written_, max_file_size_);
tkchin93411912015-07-22 12:12:17 -0700157 size_t remaining_bytes = max_file_size_ - current_bytes_written_;
158 size_t write_length = std::min(data_len, remaining_bytes);
159 size_t local_written = 0;
160 if (!written) {
161 written = &local_written;
162 }
163 StreamResult result = file_stream_->Write(data, write_length, written, error);
164 current_bytes_written_ += *written;
165
166 // If we're done with this file, rotate it out.
167 if (current_bytes_written_ >= max_file_size_) {
henrikg91d6ede2015-09-17 00:24:34 -0700168 RTC_DCHECK_EQ(current_bytes_written_, max_file_size_);
tkchin93411912015-07-22 12:12:17 -0700169 RotateFiles();
170 }
171 return result;
172}
173
174bool FileRotatingStream::Flush() {
175 if (!file_stream_) {
176 return false;
177 }
178 return file_stream_->Flush();
179}
180
tkchin28bae022015-07-23 12:27:02 -0700181bool FileRotatingStream::GetSize(size_t* size) const {
182 if (mode_ != kRead) {
183 // Not possible to get accurate size on disk when writing because of
184 // potential buffering.
185 return false;
186 }
henrikg91d6ede2015-09-17 00:24:34 -0700187 RTC_DCHECK(size);
tkchin28bae022015-07-23 12:27:02 -0700188 *size = 0;
189 size_t total_size = 0;
190 for (auto file_name : file_names_) {
191 Pathname pathname(file_name);
192 size_t file_size = 0;
193 if (Filesystem::GetFileSize(file_name, &file_size)) {
194 total_size += file_size;
195 }
196 }
197 *size = total_size;
198 return true;
199}
200
tkchin93411912015-07-22 12:12:17 -0700201void FileRotatingStream::Close() {
202 CloseCurrentFile();
203}
204
205bool FileRotatingStream::Open() {
206 switch (mode_) {
207 case kRead:
208 // Defer opening to when we first read since we want to return read error
209 // if we fail to open next file.
210 return true;
211 case kWrite: {
212 // Delete existing files when opening for write.
213 std::vector<std::string> matching_files = GetFilesWithPrefix();
214 for (auto matching_file : matching_files) {
215 if (!Filesystem::DeleteFile(matching_file)) {
Jonas Olsson55378f42018-05-25 10:23:10 +0200216 std::fprintf(stderr, "Failed to delete: %s\n", matching_file.c_str());
tkchin93411912015-07-22 12:12:17 -0700217 }
218 }
219 return OpenCurrentFile();
220 }
221 }
222 return false;
223}
224
225bool FileRotatingStream::DisableBuffering() {
226 disable_buffering_ = true;
227 if (!file_stream_) {
Jonas Olsson55378f42018-05-25 10:23:10 +0200228 std::fprintf(stderr, "Open() must be called before DisableBuffering().\n");
tkchin93411912015-07-22 12:12:17 -0700229 return false;
230 }
231 return file_stream_->DisableBuffering();
232}
233
234std::string FileRotatingStream::GetFilePath(size_t index) const {
henrikg91d6ede2015-09-17 00:24:34 -0700235 RTC_DCHECK_LT(index, file_names_.size());
tkchin93411912015-07-22 12:12:17 -0700236 return file_names_[index];
237}
238
239bool FileRotatingStream::OpenCurrentFile() {
240 CloseCurrentFile();
241
242 // Opens the appropriate file in the appropriate mode.
henrikg91d6ede2015-09-17 00:24:34 -0700243 RTC_DCHECK_LT(current_file_index_, file_names_.size());
tkchin93411912015-07-22 12:12:17 -0700244 std::string file_path = file_names_[current_file_index_];
245 file_stream_.reset(new FileStream());
246 const char* mode = nullptr;
247 switch (mode_) {
248 case kWrite:
249 mode = "w+";
250 // We should always we writing to the zero-th file.
kwibergaf476c72016-11-28 15:21:39 -0800251 RTC_DCHECK_EQ(current_file_index_, 0);
tkchin93411912015-07-22 12:12:17 -0700252 break;
253 case kRead:
254 mode = "r";
255 break;
256 }
257 int error = 0;
258 if (!file_stream_->Open(file_path, mode, &error)) {
Jonas Olsson55378f42018-05-25 10:23:10 +0200259 std::fprintf(stderr, "Failed to open: %s Error: %i\n", file_path.c_str(),
260 error);
tkchin93411912015-07-22 12:12:17 -0700261 file_stream_.reset();
262 return false;
263 }
264 if (disable_buffering_) {
265 file_stream_->DisableBuffering();
266 }
267 return true;
268}
269
270void FileRotatingStream::CloseCurrentFile() {
271 if (!file_stream_) {
272 return;
273 }
274 current_bytes_written_ = 0;
275 file_stream_.reset();
276}
277
278void FileRotatingStream::RotateFiles() {
henrikg91d6ede2015-09-17 00:24:34 -0700279 RTC_DCHECK_EQ(mode_, kWrite);
tkchin93411912015-07-22 12:12:17 -0700280 CloseCurrentFile();
281 // Rotates the files by deleting the file at |rotation_index_|, which is the
282 // oldest file and then renaming the newer files to have an incremented index.
283 // See header file comments for example.
hayscd02b0fa2015-12-08 13:59:05 -0800284 RTC_DCHECK_LT(rotation_index_, file_names_.size());
tkchin93411912015-07-22 12:12:17 -0700285 std::string file_to_delete = file_names_[rotation_index_];
286 if (Filesystem::IsFile(file_to_delete)) {
287 if (!Filesystem::DeleteFile(file_to_delete)) {
Jonas Olsson55378f42018-05-25 10:23:10 +0200288 std::fprintf(stderr, "Failed to delete: %s\n", file_to_delete.c_str());
tkchin93411912015-07-22 12:12:17 -0700289 }
290 }
291 for (auto i = rotation_index_; i > 0; --i) {
292 std::string rotated_name = file_names_[i];
293 std::string unrotated_name = file_names_[i - 1];
294 if (Filesystem::IsFile(unrotated_name)) {
295 if (!Filesystem::MoveFile(unrotated_name, rotated_name)) {
Jonas Olsson55378f42018-05-25 10:23:10 +0200296 std::fprintf(stderr, "Failed to move: %s to %s\n",
297 unrotated_name.c_str(), rotated_name.c_str());
tkchin93411912015-07-22 12:12:17 -0700298 }
299 }
300 }
301 // Create a new file for 0th index.
302 OpenCurrentFile();
303 OnRotation();
304}
305
306std::vector<std::string> FileRotatingStream::GetFilesWithPrefix() const {
307 std::vector<std::string> files;
308 // Iterate over the files in the directory.
309 DirectoryIterator it;
310 Pathname dir_path;
311 dir_path.SetFolder(dir_path_);
312 if (!it.Iterate(dir_path)) {
313 return files;
314 }
315 do {
316 std::string current_name = it.Name();
317 if (current_name.size() && !it.IsDirectory() &&
318 current_name.compare(0, file_prefix_.size(), file_prefix_) == 0) {
319 Pathname path(dir_path_, current_name);
320 files.push_back(path.pathname());
321 }
322 } while (it.Next());
323 return files;
324}
325
326std::string FileRotatingStream::GetFilePath(size_t index,
327 size_t num_files) const {
henrikg91d6ede2015-09-17 00:24:34 -0700328 RTC_DCHECK_LT(index, num_files);
tkchin93411912015-07-22 12:12:17 -0700329
Jonas Olsson671cae22018-06-14 09:57:39 +0200330 const size_t buffer_size = 32;
331 char file_postfix[buffer_size];
332 // We want to zero pad the index so that it will sort nicely.
333 const int max_digits = std::snprintf(nullptr, 0, "%zu", num_files - 1);
334 RTC_DCHECK_LT(1 + max_digits, buffer_size);
335 std::snprintf(file_postfix, buffer_size, "_%0*zu", max_digits, index);
tkchin93411912015-07-22 12:12:17 -0700336
Jonas Olsson671cae22018-06-14 09:57:39 +0200337 Pathname file_path(dir_path_, file_prefix_ + file_postfix);
tkchin93411912015-07-22 12:12:17 -0700338 return file_path.pathname();
339}
340
341CallSessionFileRotatingStream::CallSessionFileRotatingStream(
342 const std::string& dir_path)
343 : FileRotatingStream(dir_path, kLogPrefix),
344 max_total_log_size_(0),
Yves Gerey665174f2018-06-19 15:03:05 +0200345 num_rotations_(0) {}
tkchin93411912015-07-22 12:12:17 -0700346
347CallSessionFileRotatingStream::CallSessionFileRotatingStream(
348 const std::string& dir_path,
349 size_t max_total_log_size)
350 : FileRotatingStream(dir_path,
351 kLogPrefix,
352 max_total_log_size / 2,
353 GetNumRotatingLogFiles(max_total_log_size) + 1),
354 max_total_log_size_(max_total_log_size),
355 num_rotations_(0) {
kwibergaf476c72016-11-28 15:21:39 -0800356 RTC_DCHECK_GE(max_total_log_size, 4);
tkchin93411912015-07-22 12:12:17 -0700357}
358
359const char* CallSessionFileRotatingStream::kLogPrefix = "webrtc_log";
360const 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
393} // namespace rtc