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 // The file containing the metrics do not leave the device so the writer and
41 // the reader will always have the same endianness.
42 result
= HANDLE_EINTR(read(fd
, &message_size
, sizeof(message_size
)));
44 DPLOG(ERROR
) << "reading metrics message header";
48 // This indicates a normal EOF.
51 if (result
< static_cast<int>(sizeof(message_size
))) {
52 DLOG(ERROR
) << "bad read size " << result
<< ", expecting "
53 << sizeof(message_size
);
57 // kMessageMaxLength applies to the entire message: the 4-byte
58 // length field and the content.
59 if (message_size
> SerializationUtils::kMessageMaxLength
) {
60 DLOG(ERROR
) << "message too long : " << message_size
;
61 if (HANDLE_EINTR(lseek(fd
, message_size
- 4, SEEK_CUR
)) == -1) {
62 DLOG(ERROR
) << "error while skipping message. abort";
65 // Badly formatted message was skipped. Treat the badly formatted sample as
71 message_size
-= sizeof(message_size
); // The message size includes itself.
72 char buffer
[SerializationUtils::kMessageMaxLength
];
73 if (!base::ReadFromFD(fd
, buffer
, message_size
)) {
74 DPLOG(ERROR
) << "reading metrics message body";
77 *message
= std::string(buffer
, message_size
);
83 scoped_ptr
<MetricSample
> SerializationUtils::ParseSample(
84 const std::string
& sample
) {
86 return scoped_ptr
<MetricSample
>();
88 std::vector
<std::string
> parts
;
89 base::SplitString(sample
, '\0', &parts
);
90 // We should have two null terminated strings so split should produce
92 if (parts
.size() != 3) {
93 DLOG(ERROR
) << "splitting message on \\0 produced " << parts
.size()
94 << " parts (expected 3)";
95 return scoped_ptr
<MetricSample
>();
97 const std::string
& name
= parts
[0];
98 const std::string
& value
= parts
[1];
100 if (LowerCaseEqualsASCII(name
, "crash")) {
101 return MetricSample::CrashSample(value
);
102 } else if (LowerCaseEqualsASCII(name
, "histogram")) {
103 return MetricSample::ParseHistogram(value
);
104 } else if (LowerCaseEqualsASCII(name
, "linearhistogram")) {
105 return MetricSample::ParseLinearHistogram(value
);
106 } else if (LowerCaseEqualsASCII(name
, "sparsehistogram")) {
107 return MetricSample::ParseSparseHistogram(value
);
108 } else if (LowerCaseEqualsASCII(name
, "useraction")) {
109 return MetricSample::UserActionSample(value
);
111 DLOG(ERROR
) << "invalid event type: " << name
<< ", value: " << value
;
113 return scoped_ptr
<MetricSample
>();
116 void SerializationUtils::ReadAndTruncateMetricsFromFile(
117 const std::string
& filename
,
118 ScopedVector
<MetricSample
>* metrics
) {
119 struct stat stat_buf
;
122 result
= stat(filename
.c_str(), &stat_buf
);
125 DPLOG(ERROR
) << "bad metrics file stat: " << filename
;
127 // Nothing to collect---try later.
130 if (stat_buf
.st_size
== 0) {
131 // Also nothing to collect.
134 base::ScopedFD
fd(open(filename
.c_str(), O_RDWR
));
136 DPLOG(ERROR
) << "cannot open: " << filename
;
139 result
= flock(fd
.get(), LOCK_EX
);
141 DPLOG(ERROR
) << "cannot lock: " << filename
;
145 // This processes all messages in the log. When all messages are
146 // read and processed, or an error occurs, truncate the file to zero size.
150 if (!ReadMessage(fd
.get(), &message
))
153 scoped_ptr
<MetricSample
> sample
= ParseSample(message
);
155 metrics
->push_back(sample
.release());
158 result
= ftruncate(fd
.get(), 0);
160 DPLOG(ERROR
) << "truncate metrics log: " << filename
;
162 result
= flock(fd
.get(), LOCK_UN
);
164 DPLOG(ERROR
) << "unlock metrics log: " << filename
;
167 bool SerializationUtils::WriteMetricToFile(const MetricSample
& sample
,
168 const std::string
& filename
) {
169 if (!sample
.IsValid())
172 base::ScopedFD
file_descriptor(open(filename
.c_str(),
173 O_WRONLY
| O_APPEND
| O_CREAT
,
174 READ_WRITE_ALL_FILE_FLAGS
));
176 if (file_descriptor
.get() < 0) {
177 DPLOG(ERROR
) << "error openning the file: " << filename
;
181 fchmod(file_descriptor
.get(), READ_WRITE_ALL_FILE_FLAGS
);
182 // Grab a lock to avoid chrome truncating the file
183 // underneath us. Keep the file locked as briefly as possible.
184 // Freeing file_descriptor will close the file and and remove the lock.
185 if (HANDLE_EINTR(flock(file_descriptor
.get(), LOCK_EX
)) < 0) {
186 DPLOG(ERROR
) << "error locking: " << filename
;
190 std::string msg
= sample
.ToString();
191 int32 size
= msg
.length() + sizeof(int32
);
192 if (size
> kMessageMaxLength
) {
193 DPLOG(ERROR
) << "cannot write message: too long: " << filename
;
197 // The file containing the metrics samples will only be read by programs on
198 // the same device so we do not check endianness.
199 if (!base::WriteFileDescriptor(file_descriptor
.get(),
200 reinterpret_cast<char*>(&size
),
202 DPLOG(ERROR
) << "error writing message length: " << filename
;
206 if (!base::WriteFileDescriptor(
207 file_descriptor
.get(), msg
.c_str(), msg
.size())) {
208 DPLOG(ERROR
) << "error writing message: " << filename
;
215 } // namespace metrics