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"
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)
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
) {
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
));
45 DPLOG(ERROR
) << "reading metrics message header";
49 // This indicates a normal EOF.
52 if (result
< message_header_size
) {
53 DLOG(ERROR
) << "bad read size " << result
<< ", expecting "
54 << sizeof(message_size
);
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";
66 // Badly formatted message was skipped. Treat the badly formatted sample as
72 if (message_size
< message_header_size
) {
73 DLOG(ERROR
) << "message too short : " << message_size
;
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";
83 *message
= std::string(buffer
, message_size
);
89 scoped_ptr
<MetricSample
> SerializationUtils::ParseSample(
90 const std::string
& sample
) {
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
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
);
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
;
129 result
= stat(filename
.c_str(), &stat_buf
);
132 DPLOG(ERROR
) << "bad metrics file stat: " << filename
;
134 // Nothing to collect---try later.
137 if (stat_buf
.st_size
== 0) {
138 // Also nothing to collect.
141 base::ScopedFD
fd(open(filename
.c_str(), O_RDWR
));
143 DPLOG(ERROR
) << "cannot open: " << filename
;
146 result
= flock(fd
.get(), LOCK_EX
);
148 DPLOG(ERROR
) << "cannot lock: " << filename
;
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.
157 if (!ReadMessage(fd
.get(), &message
))
160 scoped_ptr
<MetricSample
> sample
= ParseSample(message
);
162 metrics
->push_back(sample
.Pass());
165 result
= ftruncate(fd
.get(), 0);
167 DPLOG(ERROR
) << "truncate metrics log: " << filename
;
169 result
= flock(fd
.get(), LOCK_UN
);
171 DPLOG(ERROR
) << "unlock metrics log: " << filename
;
174 bool SerializationUtils::WriteMetricToFile(const MetricSample
& sample
,
175 const std::string
& filename
) {
176 if (!sample
.IsValid())
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
;
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
;
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
;
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
),
209 DPLOG(ERROR
) << "error writing message length: " << filename
;
213 if (!base::WriteFileDescriptor(
214 file_descriptor
.get(), msg
.c_str(), msg
.size())) {
215 DPLOG(ERROR
) << "error writing message: " << filename
;
222 } // namespace metrics