blob: fbf0b453aef99bee413aa65a6c3c79c1e98562f3 [file] [log] [blame]
Christopher Wiley5781aa42012-07-30 14:42:23 -07001// Copyright (c) 2012 The Chromium OS Authors. All rights reserved.
2// Use of this source code is governed by a BSD-style license that can be
3// found in the LICENSE file.
4
Christopher Wileyb691efd2012-08-09 13:51:51 -07005#include "shill/memory_log.h"
6
Christopher Wiley3e7635e2012-08-15 09:46:17 -07007#include <errno.h>
8#include <pwd.h>
Christopher Wiley5781aa42012-07-30 14:42:23 -07009#include <stdio.h>
Christopher Wiley3e7635e2012-08-15 09:46:17 -070010#include <string.h>
11#include <sys/stat.h>
12#include <unistd.h>
Christopher Wiley5781aa42012-07-30 14:42:23 -070013
14#include <ctime>
15#include <iomanip>
Christopher Wileyf11cebb2012-08-08 12:22:20 -070016#include <string>
Christopher Wiley5781aa42012-07-30 14:42:23 -070017
18#include <base/file_path.h>
19#include <base/file_util.h>
20
Christopher Wileyb691efd2012-08-09 13:51:51 -070021#include "shill/logging.h"
Christopher Wiley5781aa42012-07-30 14:42:23 -070022#include "shill/shill_time.h"
23
Albert Chaulk0e1cdea2013-02-27 15:32:55 -080024using base::FilePath;
25
Christopher Wiley5781aa42012-07-30 14:42:23 -070026namespace shill {
27
28namespace {
29
30// MemoryLog needs to be a 'leaky' singleton as it needs to survive to
31// handle logging till the very end of the shill process. Making MemoryLog
32// leaky is fine as it does not need to clean up or release any resource at
33// destruction.
34base::LazyInstance<MemoryLog>::Leaky g_memory_log = LAZY_INSTANCE_INITIALIZER;
35
36// Can't get to these in base/logging.c.
37const char *const kLogSeverityNames[logging::LOG_NUM_SEVERITIES] = {
38 "INFO", "WARNING", "ERROR", "ERROR_REPORT", "FATAL"
39};
40
Christopher Wiley3e7635e2012-08-15 09:46:17 -070041const char kLoggedInUserName[] = "chronos";
Christopher Wiley5781aa42012-07-30 14:42:23 -070042} // namespace
43
Christopher Wiley3e7635e2012-08-15 09:46:17 -070044const char MemoryLog::kDefaultLoggedInDumpPath[] =
Christopher Wiley03f8e482013-04-12 14:59:15 -070045 "/var/run/shill/log/connectivity.log";
Christopher Wiley3e7635e2012-08-15 09:46:17 -070046
47const char MemoryLog::kDefaultLoggedOutDumpPath[] =
48 "/var/log/connectivity.log";
49
50const char MemoryLog::kLoggedInTokenPath[] =
51 "/var/run/state/logged-in";
52
Christopher Wiley5781aa42012-07-30 14:42:23 -070053// static
54MemoryLog *MemoryLog::GetInstance() {
55 return g_memory_log.Pointer();
56}
57
58MemoryLog::MemoryLog()
59 : maximum_size_bytes_(kDefaultMaximumMemoryLogSizeInBytes),
Christopher Wiley3e7635e2012-08-15 09:46:17 -070060 current_size_bytes_(0),
61 maximum_disk_log_size_bytes_(kDefaultMaxDiskLogSizeInBytes) { }
Christopher Wiley5781aa42012-07-30 14:42:23 -070062
63void MemoryLog::Append(const std::string &msg) {
64 current_size_bytes_ += msg.size();
65 log_.push_back(msg);
66 ShrinkToTargetSize(maximum_size_bytes_);
67}
68
69void MemoryLog::Clear() {
70 current_size_bytes_ = 0;
71 log_.clear();
72}
73
Christopher Wiley3e7635e2012-08-15 09:46:17 -070074void MemoryLog::FlushToDisk() {
75 if (file_util::PathExists(FilePath(kLoggedInTokenPath))) {
76 FlushToDiskImpl(FilePath(kDefaultLoggedInDumpPath));
77 } else {
78 FlushToDiskImpl(FilePath(kDefaultLoggedOutDumpPath));
79 }
80}
81
82void MemoryLog::FlushToDiskImpl(const FilePath &file_path) {
mukesh agrawal910d0d62012-12-06 14:35:40 -080083 LOG(INFO) << "Saving memory log to " << file_path.AsUTF8Unsafe();
Christopher Wiley3e7635e2012-08-15 09:46:17 -070084 do {
85 // If the file exists, lets make sure it is of reasonable size before
86 // writing to it, and roll it over if it's too big.
87 if (!file_util::PathExists(file_path)) {
88 // No existing file means we can write without worry to a new file.
89 continue;
90 }
91 int64_t file_size = -1;
92 if (!file_util::GetFileSize(file_path, &file_size) || (file_size < 0)) {
93 LOG(ERROR) << "Failed to get size of existing memory log dump.";
94 return;
95 }
96 FilePath backup_path = file_path.ReplaceExtension(".bak");
97 if (static_cast<uint64_t>(file_size) < maximum_disk_log_size_bytes_) {
98 // File existed, but was below our threshold.
99 continue;
100 }
101 if (!file_util::Move(file_path, backup_path)) {
102 LOG(ERROR) << "Failed to move overly large memory log on disk from "
103 << file_path.value() << " to " << backup_path.value();
104 return;
105 }
106 } while (false);
107
108 if (FlushToFile(file_path) < 0) {
109 LOG(ERROR) << "Failed to flush memory log to disk";
110 }
111 // We don't want to see messages twice.
112 Clear();
113}
114
115ssize_t MemoryLog::FlushToFile(const FilePath &file_path) {
116 FILE *f = file_util::OpenFile(file_path, "a");
Christopher Wiley5781aa42012-07-30 14:42:23 -0700117 if (!f) {
Christopher Wiley3e7635e2012-08-15 09:46:17 -0700118 LOG(ERROR) << "Failed to open file for dumping memory log to disk.";
Christopher Wiley5781aa42012-07-30 14:42:23 -0700119 return -1;
120 }
Christopher Wiley5781aa42012-07-30 14:42:23 -0700121 file_util::ScopedFILE file_closer(f);
Christopher Wiley3e7635e2012-08-15 09:46:17 -0700122 long maximum_pw_string_size = sysconf(_SC_GETPW_R_SIZE_MAX);
123 if (maximum_pw_string_size < 0) {
124 LOG(ERROR) << "Setup for changing ownership of memory log file failed";
125 return -1;
126 }
127 struct passwd chronos;
128 struct passwd *pwresult = NULL;
129 scoped_array<char> buf(new char[maximum_pw_string_size]);
130 if (getpwnam_r(kLoggedInUserName,
131 &chronos,
132 buf.get(),
133 maximum_pw_string_size,
134 &pwresult) || pwresult == NULL) {
135 PLOG(ERROR) << "Failed to find user " << kLoggedInUserName
136 << " for memory log dump.";
137 return -1;
138 }
139 if (chown(file_path.value().c_str(), chronos.pw_uid, chronos.pw_gid)) {
140 PLOG(WARNING) << "Failed to change ownership of memory log file.";
141 }
142 if (chmod(file_path.value().c_str(), S_IRUSR | S_IWUSR | S_IRGRP | S_IROTH)) {
143 PLOG(WARNING) << "Failed to change permissions of memory log file. Error: "
144 << strerror(errno);
145 }
Christopher Wiley5781aa42012-07-30 14:42:23 -0700146 ssize_t bytes_written = 0;
147 std::deque<std::string>::iterator it;
148 for (it = log_.begin(); it != log_.end(); it++) {
149 bytes_written += fwrite(it->c_str(), 1, it->size(), f);
150 if (ferror(f)) {
Christopher Wiley3e7635e2012-08-15 09:46:17 -0700151 LOG(ERROR) << "Write to memory log dump file failed.";
Christopher Wiley5781aa42012-07-30 14:42:23 -0700152 return -1;
153 }
154 }
155
156 return bytes_written;
157}
158
159void MemoryLog::SetMaximumSize(size_t size_in_bytes) {
160 ShrinkToTargetSize(size_in_bytes);
161 maximum_size_bytes_ = size_in_bytes;
162}
163
164void MemoryLog::ShrinkToTargetSize(size_t number_bytes) {
165 while (current_size_bytes_ > number_bytes) {
166 const std::string &front = log_.front();
167 current_size_bytes_ -= front.size();
168 log_.pop_front();
169 }
170}
171
Christopher Wiley3e7635e2012-08-15 09:46:17 -0700172bool MemoryLog::TestContainsMessageWithText(const char *msg) {
173 std::deque<std::string>::const_iterator it;
174 for (it = log_.begin(); it != log_.end(); ++it) {
175 if (it->find(msg) != std::string::npos) {
176 return true;
177 }
178 }
179 return false;
180}
181
Christopher Wiley5781aa42012-07-30 14:42:23 -0700182MemoryLogMessage::MemoryLogMessage(const char *file,
183 int line,
184 logging::LogSeverity severity,
185 bool propagate_down)
186 : file_(file),
187 line_(line),
188 severity_(severity),
189 propagate_down_(propagate_down),
190 message_start_(0) {
191 Init();
192}
193
194MemoryLogMessage::~MemoryLogMessage() {
195 if (propagate_down_) {
196 ::logging::LogMessage(file_, line_, severity_).stream()
197 << &(stream_.str()[message_start_]);
198 }
199 stream_ << std::endl;
200 MemoryLog::GetInstance()->Append(stream_.str());
201}
202
203// This owes heavily to the base/logging.cc:LogMessage implementation, but
204// without as much customization. Unfortunately, there isn't a good way to
205// get into that code without drastically changing how base/logging works. It
206// isn't exactly rocket science in any case.
207void MemoryLogMessage::Init() {
208 const char *filename = strrchr(file_, '/');
209 if (!filename) {
210 filename = file_;
211 }
212
213 // Just log a timestamp, number of ticks, severity, and a file name.
214 struct timeval tv = {0};
215 struct tm local_time = {0};
216 Time::GetInstance()->GetTimeOfDay(&tv, NULL);
217 localtime_r(&tv.tv_sec, &local_time);
218 stream_ << std::setfill('0')
219 << local_time.tm_year + 1900
220 << '-' << std::setw(2) << local_time.tm_mon + 1
221 << '-' << std::setw(2) << local_time.tm_mday
222 << 'T' << std::setw(2) << local_time.tm_hour
223 << ':' << std::setw(2) << local_time.tm_min
224 << ':' << std::setw(2) << local_time.tm_sec
225 << '.' << tv.tv_usec << ' ';
226
Christopher Wiley5781aa42012-07-30 14:42:23 -0700227 if (severity_ >= 0)
228 stream_ << kLogSeverityNames[severity_];
229 else
230 stream_ << "VERBOSE" << -severity_;
231 stream_ << ":" << filename << "(" << line_ << ") ";
Christopher Wileyf11cebb2012-08-08 12:22:20 -0700232
Christopher Wiley5781aa42012-07-30 14:42:23 -0700233 message_start_ = stream_.tellp();
Christopher Wiley5781aa42012-07-30 14:42:23 -0700234}
235
236} // namespace shill