blob: 4e3aa732452010f998ad8e89fc513bf7ce1f62f9 [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>
14#include <iostream>
15#include <string>
16
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020017#include "rtc_base/checks.h"
18#include "rtc_base/fileutils.h"
19#include "rtc_base/pathutils.h"
tkchin93411912015-07-22 12:12:17 -070020
21// Note: We use std::cerr for logging in the write paths of this stream to avoid
22// infinite loops when logging.
23
24namespace rtc {
25
26FileRotatingStream::FileRotatingStream(const std::string& dir_path,
27 const std::string& file_prefix)
28 : FileRotatingStream(dir_path, file_prefix, 0, 0, kRead) {
29}
30
31FileRotatingStream::FileRotatingStream(const std::string& dir_path,
32 const std::string& file_prefix,
33 size_t max_file_size,
34 size_t num_files)
35 : FileRotatingStream(dir_path,
36 file_prefix,
37 max_file_size,
38 num_files,
39 kWrite) {
kwibergaf476c72016-11-28 15:21:39 -080040 RTC_DCHECK_GT(max_file_size, 0);
41 RTC_DCHECK_GT(num_files, 1);
tkchin93411912015-07-22 12:12:17 -070042}
43
44FileRotatingStream::FileRotatingStream(const std::string& dir_path,
45 const std::string& file_prefix,
46 size_t max_file_size,
47 size_t num_files,
48 Mode mode)
49 : dir_path_(dir_path),
50 file_prefix_(file_prefix),
51 mode_(mode),
52 file_stream_(nullptr),
53 max_file_size_(max_file_size),
54 current_file_index_(0),
55 rotation_index_(0),
56 current_bytes_written_(0),
57 disable_buffering_(false) {
henrikg91d6ede2015-09-17 00:24:34 -070058 RTC_DCHECK(Filesystem::IsFolder(dir_path));
tkchin93411912015-07-22 12:12:17 -070059 switch (mode) {
60 case kWrite: {
61 file_names_.clear();
62 for (size_t i = 0; i < num_files; ++i) {
63 file_names_.push_back(GetFilePath(i, num_files));
64 }
65 rotation_index_ = num_files - 1;
66 break;
67 }
68 case kRead: {
69 file_names_ = GetFilesWithPrefix();
70 std::sort(file_names_.begin(), file_names_.end());
71 if (file_names_.size() > 0) {
72 // |file_names_| is sorted newest first, so read from the end.
73 current_file_index_ = file_names_.size() - 1;
74 }
75 break;
76 }
77 }
78}
79
80FileRotatingStream::~FileRotatingStream() {
81}
82
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_) {
152 std::cerr << "Open() must be called before Write." << std::endl;
153 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)) {
216 std::cerr << "Failed to delete: " << matching_file << std::endl;
217 }
218 }
219 return OpenCurrentFile();
220 }
221 }
222 return false;
223}
224
225bool FileRotatingStream::DisableBuffering() {
226 disable_buffering_ = true;
227 if (!file_stream_) {
228 std::cerr << "Open() must be called before DisableBuffering()."
229 << std::endl;
230 return false;
231 }
232 return file_stream_->DisableBuffering();
233}
234
235std::string FileRotatingStream::GetFilePath(size_t index) const {
henrikg91d6ede2015-09-17 00:24:34 -0700236 RTC_DCHECK_LT(index, file_names_.size());
tkchin93411912015-07-22 12:12:17 -0700237 return file_names_[index];
238}
239
240bool FileRotatingStream::OpenCurrentFile() {
241 CloseCurrentFile();
242
243 // Opens the appropriate file in the appropriate mode.
henrikg91d6ede2015-09-17 00:24:34 -0700244 RTC_DCHECK_LT(current_file_index_, file_names_.size());
tkchin93411912015-07-22 12:12:17 -0700245 std::string file_path = file_names_[current_file_index_];
246 file_stream_.reset(new FileStream());
247 const char* mode = nullptr;
248 switch (mode_) {
249 case kWrite:
250 mode = "w+";
251 // We should always we writing to the zero-th file.
kwibergaf476c72016-11-28 15:21:39 -0800252 RTC_DCHECK_EQ(current_file_index_, 0);
tkchin93411912015-07-22 12:12:17 -0700253 break;
254 case kRead:
255 mode = "r";
256 break;
257 }
258 int error = 0;
259 if (!file_stream_->Open(file_path, mode, &error)) {
260 std::cerr << "Failed to open: " << file_path << "Error: " << error
261 << std::endl;
262 file_stream_.reset();
263 return false;
264 }
265 if (disable_buffering_) {
266 file_stream_->DisableBuffering();
267 }
268 return true;
269}
270
271void FileRotatingStream::CloseCurrentFile() {
272 if (!file_stream_) {
273 return;
274 }
275 current_bytes_written_ = 0;
276 file_stream_.reset();
277}
278
279void FileRotatingStream::RotateFiles() {
henrikg91d6ede2015-09-17 00:24:34 -0700280 RTC_DCHECK_EQ(mode_, kWrite);
tkchin93411912015-07-22 12:12:17 -0700281 CloseCurrentFile();
282 // Rotates the files by deleting the file at |rotation_index_|, which is the
283 // oldest file and then renaming the newer files to have an incremented index.
284 // See header file comments for example.
hayscd02b0fa2015-12-08 13:59:05 -0800285 RTC_DCHECK_LT(rotation_index_, file_names_.size());
tkchin93411912015-07-22 12:12:17 -0700286 std::string file_to_delete = file_names_[rotation_index_];
287 if (Filesystem::IsFile(file_to_delete)) {
288 if (!Filesystem::DeleteFile(file_to_delete)) {
289 std::cerr << "Failed to delete: " << file_to_delete << std::endl;
290 }
291 }
292 for (auto i = rotation_index_; i > 0; --i) {
293 std::string rotated_name = file_names_[i];
294 std::string unrotated_name = file_names_[i - 1];
295 if (Filesystem::IsFile(unrotated_name)) {
296 if (!Filesystem::MoveFile(unrotated_name, rotated_name)) {
297 std::cerr << "Failed to move: " << unrotated_name << " to "
298 << rotated_name << std::endl;
299 }
300 }
301 }
302 // Create a new file for 0th index.
303 OpenCurrentFile();
304 OnRotation();
305}
306
307std::vector<std::string> FileRotatingStream::GetFilesWithPrefix() const {
308 std::vector<std::string> files;
309 // Iterate over the files in the directory.
310 DirectoryIterator it;
311 Pathname dir_path;
312 dir_path.SetFolder(dir_path_);
313 if (!it.Iterate(dir_path)) {
314 return files;
315 }
316 do {
317 std::string current_name = it.Name();
318 if (current_name.size() && !it.IsDirectory() &&
319 current_name.compare(0, file_prefix_.size(), file_prefix_) == 0) {
320 Pathname path(dir_path_, current_name);
321 files.push_back(path.pathname());
322 }
323 } while (it.Next());
324 return files;
325}
326
327std::string FileRotatingStream::GetFilePath(size_t index,
328 size_t num_files) const {
henrikg91d6ede2015-09-17 00:24:34 -0700329 RTC_DCHECK_LT(index, num_files);
tkchin93411912015-07-22 12:12:17 -0700330 std::ostringstream file_name;
331 // The format will be "_%<num_digits>zu". We want to zero pad the index so
332 // that it will sort nicely.
333 size_t max_digits = ((num_files - 1) / 10) + 1;
334 size_t num_digits = (index / 10) + 1;
henrikg91d6ede2015-09-17 00:24:34 -0700335 RTC_DCHECK_LE(num_digits, max_digits);
tkchin93411912015-07-22 12:12:17 -0700336 size_t padding = max_digits - num_digits;
337
338 file_name << file_prefix_ << "_";
339 for (size_t i = 0; i < padding; ++i) {
340 file_name << "0";
341 }
342 file_name << index;
343
344 Pathname file_path(dir_path_, file_name.str());
345 return file_path.pathname();
346}
347
348CallSessionFileRotatingStream::CallSessionFileRotatingStream(
349 const std::string& dir_path)
350 : FileRotatingStream(dir_path, kLogPrefix),
351 max_total_log_size_(0),
352 num_rotations_(0) {
353}
354
355CallSessionFileRotatingStream::CallSessionFileRotatingStream(
356 const std::string& dir_path,
357 size_t max_total_log_size)
358 : FileRotatingStream(dir_path,
359 kLogPrefix,
360 max_total_log_size / 2,
361 GetNumRotatingLogFiles(max_total_log_size) + 1),
362 max_total_log_size_(max_total_log_size),
363 num_rotations_(0) {
kwibergaf476c72016-11-28 15:21:39 -0800364 RTC_DCHECK_GE(max_total_log_size, 4);
tkchin93411912015-07-22 12:12:17 -0700365}
366
367const char* CallSessionFileRotatingStream::kLogPrefix = "webrtc_log";
368const size_t CallSessionFileRotatingStream::kRotatingLogFileDefaultSize =
369 1024 * 1024;
370
371void CallSessionFileRotatingStream::OnRotation() {
372 ++num_rotations_;
373 if (num_rotations_ == 1) {
374 // On the first rotation adjust the max file size so subsequent files after
375 // the first are smaller.
376 SetMaxFileSize(GetRotatingLogSize(max_total_log_size_));
377 } else if (num_rotations_ == (GetNumFiles() - 1)) {
378 // On the next rotation the very first file is going to be deleted. Change
379 // the rotation index so this doesn't happen.
380 SetRotationIndex(GetRotationIndex() - 1);
381 }
382}
383
384size_t CallSessionFileRotatingStream::GetRotatingLogSize(
385 size_t max_total_log_size) {
386 size_t num_rotating_log_files = GetNumRotatingLogFiles(max_total_log_size);
387 size_t rotating_log_size = num_rotating_log_files > 2
388 ? kRotatingLogFileDefaultSize
389 : max_total_log_size / 4;
390 return rotating_log_size;
391}
392
393size_t CallSessionFileRotatingStream::GetNumRotatingLogFiles(
394 size_t max_total_log_size) {
395 // At minimum have two rotating files. Otherwise split the available log size
396 // evenly across 1MB files.
397 return std::max((size_t)2,
398 (max_total_log_size / 2) / kRotatingLogFileDefaultSize);
399}
400
401} // namespace rtc