Content settings: remove some plugin-related code/resources when... there are no...
[chromium-blink-merge.git] / components / metrics / serialization / serialization_utils.cc
blob6d6aa0b930788d60e9a0cd4d8ba6fe4a59fcd6aa
1 // Copyright 2014 The Chromium 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.
5 #include "components/metrics/serialization/serialization_utils.h"
7 #include <sys/file.h>
9 #include <string>
10 #include <vector>
12 #include "base/files/file_path.h"
13 #include "base/files/file_util.h"
14 #include "base/files/scoped_file.h"
15 #include "base/logging.h"
16 #include "base/memory/scoped_ptr.h"
17 #include "base/memory/scoped_vector.h"
18 #include "base/strings/string_split.h"
19 #include "base/strings/string_util.h"
20 #include "components/metrics/serialization/metric_sample.h"
22 #define READ_WRITE_ALL_FILE_FLAGS \
23 (S_IRUSR | S_IWUSR | S_IRGRP | S_IWGRP | S_IROTH | S_IWOTH)
25 namespace metrics {
26 namespace {
28 // Reads the next message from |file_descriptor| into |message|.
30 // |message| will be set to the empty string if no message could be read (EOF)
31 // or the message was badly constructed.
33 // Returns false if no message can be read from this file anymore (EOF or
34 // unrecoverable error).
35 bool ReadMessage(int fd, std::string* message) {
36 CHECK(message);
38 int result;
39 int32_t message_size;
40 const int32_t message_header_size = sizeof(message_size);
41 // The file containing the metrics does not leave the device so the writer and
42 // the reader will always have the same endianness.
43 result = HANDLE_EINTR(read(fd, &message_size, message_header_size));
44 if (result < 0) {
45 DPLOG(ERROR) << "reading metrics message header";
46 return false;
48 if (result == 0) {
49 // This indicates a normal EOF.
50 return false;
52 if (result < message_header_size) {
53 DLOG(ERROR) << "bad read size " << result << ", expecting "
54 << sizeof(message_size);
55 return false;
58 // kMessageMaxLength applies to the entire message: the 4-byte
59 // length field and the content.
60 if (message_size > SerializationUtils::kMessageMaxLength) {
61 DLOG(ERROR) << "message too long : " << message_size;
62 if (HANDLE_EINTR(lseek(fd, message_size - 4, SEEK_CUR)) == -1) {
63 DLOG(ERROR) << "error while skipping message. abort";
64 return false;
66 // Badly formatted message was skipped. Treat the badly formatted sample as
67 // an empty sample.
68 message->clear();
69 return true;
72 if (message_size < message_header_size) {
73 DLOG(ERROR) << "message too short : " << message_size;
74 return false;
77 message_size -= message_header_size; // The message size includes itself.
78 char buffer[SerializationUtils::kMessageMaxLength];
79 if (!base::ReadFromFD(fd, buffer, message_size)) {
80 DPLOG(ERROR) << "reading metrics message body";
81 return false;
83 *message = std::string(buffer, message_size);
84 return true;
87 } // namespace
89 scoped_ptr<MetricSample> SerializationUtils::ParseSample(
90 const std::string& sample) {
91 if (sample.empty())
92 return scoped_ptr<MetricSample>();
94 std::vector<std::string> parts = base::SplitString(
95 sample, std::string(1, '\0'),
96 base::TRIM_WHITESPACE, base::SPLIT_WANT_ALL);
97 // We should have two null terminated strings so split should produce
98 // three chunks.
99 if (parts.size() != 3) {
100 DLOG(ERROR) << "splitting message on \\0 produced " << parts.size()
101 << " parts (expected 3)";
102 return scoped_ptr<MetricSample>();
104 const std::string& name = parts[0];
105 const std::string& value = parts[1];
107 if (base::LowerCaseEqualsASCII(name, "crash")) {
108 return MetricSample::CrashSample(value);
109 } else if (base::LowerCaseEqualsASCII(name, "histogram")) {
110 return MetricSample::ParseHistogram(value);
111 } else if (base::LowerCaseEqualsASCII(name, "linearhistogram")) {
112 return MetricSample::ParseLinearHistogram(value);
113 } else if (base::LowerCaseEqualsASCII(name, "sparsehistogram")) {
114 return MetricSample::ParseSparseHistogram(value);
115 } else if (base::LowerCaseEqualsASCII(name, "useraction")) {
116 return MetricSample::UserActionSample(value);
117 } else {
118 DLOG(ERROR) << "invalid event type: " << name << ", value: " << value;
120 return scoped_ptr<MetricSample>();
123 void SerializationUtils::ReadAndTruncateMetricsFromFile(
124 const std::string& filename,
125 ScopedVector<MetricSample>* metrics) {
126 struct stat stat_buf;
127 int result;
129 result = stat(filename.c_str(), &stat_buf);
130 if (result < 0) {
131 if (errno != ENOENT)
132 DPLOG(ERROR) << "bad metrics file stat: " << filename;
134 // Nothing to collect---try later.
135 return;
137 if (stat_buf.st_size == 0) {
138 // Also nothing to collect.
139 return;
141 base::ScopedFD fd(open(filename.c_str(), O_RDWR));
142 if (fd.get() < 0) {
143 DPLOG(ERROR) << "cannot open: " << filename;
144 return;
146 result = flock(fd.get(), LOCK_EX);
147 if (result < 0) {
148 DPLOG(ERROR) << "cannot lock: " << filename;
149 return;
152 // This processes all messages in the log. When all messages are
153 // read and processed, or an error occurs, truncate the file to zero size.
154 for (;;) {
155 std::string message;
157 if (!ReadMessage(fd.get(), &message))
158 break;
160 scoped_ptr<MetricSample> sample = ParseSample(message);
161 if (sample)
162 metrics->push_back(sample.Pass());
165 result = ftruncate(fd.get(), 0);
166 if (result < 0)
167 DPLOG(ERROR) << "truncate metrics log: " << filename;
169 result = flock(fd.get(), LOCK_UN);
170 if (result < 0)
171 DPLOG(ERROR) << "unlock metrics log: " << filename;
174 bool SerializationUtils::WriteMetricToFile(const MetricSample& sample,
175 const std::string& filename) {
176 if (!sample.IsValid())
177 return false;
179 base::ScopedFD file_descriptor(open(filename.c_str(),
180 O_WRONLY | O_APPEND | O_CREAT,
181 READ_WRITE_ALL_FILE_FLAGS));
183 if (file_descriptor.get() < 0) {
184 DPLOG(ERROR) << "error openning the file: " << filename;
185 return false;
188 fchmod(file_descriptor.get(), READ_WRITE_ALL_FILE_FLAGS);
189 // Grab a lock to avoid chrome truncating the file
190 // underneath us. Keep the file locked as briefly as possible.
191 // Freeing file_descriptor will close the file and and remove the lock.
192 if (HANDLE_EINTR(flock(file_descriptor.get(), LOCK_EX)) < 0) {
193 DPLOG(ERROR) << "error locking: " << filename;
194 return false;
197 std::string msg = sample.ToString();
198 int32 size = msg.length() + sizeof(int32);
199 if (size > kMessageMaxLength) {
200 DPLOG(ERROR) << "cannot write message: too long: " << filename;
201 return false;
204 // The file containing the metrics samples will only be read by programs on
205 // the same device so we do not check endianness.
206 if (!base::WriteFileDescriptor(file_descriptor.get(),
207 reinterpret_cast<char*>(&size),
208 sizeof(size))) {
209 DPLOG(ERROR) << "error writing message length: " << filename;
210 return false;
213 if (!base::WriteFileDescriptor(
214 file_descriptor.get(), msg.c_str(), msg.size())) {
215 DPLOG(ERROR) << "error writing message: " << filename;
216 return false;
219 return true;
222 } // namespace metrics