blob: de2ff93a5b0a76826807d977dab9b1b26e4e0f0f [file] [log] [blame]
Darin Petkov65b01462010-04-14 13:32:20 -07001// Copyright (c) 2010 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
Darin Petkov65b01462010-04-14 13:32:20 -07005#include "metrics_library.h"
6
7#include <errno.h>
8#include <sys/file.h>
Ken Mixter4c5daa42010-08-26 18:35:06 -07009#include <sys/stat.h>
Darin Petkov4fcb2ac2010-04-15 16:40:23 -070010
11#include <cstdarg>
12#include <cstdio>
13#include <cstring>
Darin Petkov65b01462010-04-14 13:32:20 -070014
Chris Masonee10b5482013-02-14 12:15:35 -080015// HANDLE_EINTR macro, no libbase required.
16#include <base/posix/eintr_wrapper.h>
17
Ken Mixterb2f17092011-07-22 14:59:51 -070018#include "policy/device_policy.h"
Darin Petkov8842c8c2011-02-24 12:48:30 -080019
Darin Petkov65b01462010-04-14 13:32:20 -070020#define READ_WRITE_ALL_FILE_FLAGS \
21 (S_IRUSR | S_IWUSR | S_IRGRP | S_IWGRP | S_IROTH | S_IWOTH)
Chih-Chung Chang6844c062013-04-01 14:27:39 +080022#define ARRAY_SIZE(a) (sizeof(a) / sizeof((a)[0]))
Darin Petkov65b01462010-04-14 13:32:20 -070023
Ken Mixter4c5daa42010-08-26 18:35:06 -070024static const char kAutotestPath[] = "/var/log/metrics/autotest-events";
25static const char kUMAEventsPath[] = "/var/log/metrics/uma-events";
26static const char kConsentFile[] = "/home/chronos/Consent To Send Stats";
Darin Petkov4fcb2ac2010-04-15 16:40:23 -070027static const int32_t kBufferSize = 1024;
Luigi Semenzato32684222013-03-13 10:53:55 -070028static const char kCrosEventHistogramName[] = "Platform.CrOSEvent";
29static const int kCrosEventHistogramMax = 100;
Darin Petkov65b01462010-04-14 13:32:20 -070030
Chih-Chung Chang6844c062013-04-01 14:27:39 +080031/* Add new cros events here.
32 *
33 * The index of the event is sent in the message, so please do not
34 * reorder the names.
35 */
36static const char *kCrosEventNames[] = {
37 "ModemManagerCommandSendFailure", // 0
38 "HwWatchdogReboot", // 1
39 "Cras.NoCodecsFoundAtBoot", // 2
Darren Krahn6e55c1152013-07-19 14:09:50 -070040 "Chaps.DatabaseCorrupted", // 3
41 "Chaps.DatabaseRepairFailure", // 4
42 "Chaps.DatabaseCreateFailure", // 5
Darren Krahn86830ba2013-07-26 13:37:20 -070043 "Attestation.OriginSpecificExhausted", // 6
Chih-Chung Chang6844c062013-04-01 14:27:39 +080044};
45
Ken Mixter4c5daa42010-08-26 18:35:06 -070046time_t MetricsLibrary::cached_enabled_time_ = 0;
47bool MetricsLibrary::cached_enabled_ = false;
48
David James3b3add52010-06-04 15:01:19 -070049using std::string;
Darin Petkov65b01462010-04-14 13:32:20 -070050
51// TODO(sosa@chromium.org) - use Chromium logger instead of stderr
Darin Petkov11b8eb32010-05-18 11:00:59 -070052static void PrintError(const char* message, const char* file,
Darin Petkov4fcb2ac2010-04-15 16:40:23 -070053 int code) {
David James3b3add52010-06-04 15:01:19 -070054 static const char kProgramName[] = "libmetrics";
Darin Petkov65b01462010-04-14 13:32:20 -070055 if (code == 0) {
56 fprintf(stderr, "%s: %s\n", kProgramName, message);
57 } else if (file == NULL) {
58 fprintf(stderr, "%s: ", kProgramName);
59 perror(message);
60 } else {
61 fprintf(stderr, "%s: %s: ", kProgramName, file);
62 perror(message);
63 }
64}
65
Darin Petkov8d3305e2011-02-25 14:19:30 -080066// Copied from libbase to avoid pulling in all of libbase just for libmetrics.
67static int WriteFileDescriptor(const int fd, const char* data, int size) {
68 // Allow for partial writes.
69 ssize_t bytes_written_total = 0;
70 for (ssize_t bytes_written_partial = 0; bytes_written_total < size;
71 bytes_written_total += bytes_written_partial) {
72 bytes_written_partial =
73 HANDLE_EINTR(write(fd, data + bytes_written_total,
74 size - bytes_written_total));
75 if (bytes_written_partial < 0)
76 return -1;
77 }
78
79 return bytes_written_total;
80}
81
Darin Petkov11b8eb32010-05-18 11:00:59 -070082MetricsLibrary::MetricsLibrary()
Ken Mixter4c5daa42010-08-26 18:35:06 -070083 : uma_events_file_(NULL),
Ken Mixterb2f17092011-07-22 14:59:51 -070084 consent_file_(kConsentFile),
85 policy_provider_(NULL) {}
Ken Mixter4c5daa42010-08-26 18:35:06 -070086
Ken Mixtereafbbdf2010-10-01 15:38:42 -070087// We take buffer and buffer_size as parameters in order to simplify testing
88// of various alignments of the |device_name| with |buffer_size|.
89bool MetricsLibrary::IsDeviceMounted(const char* device_name,
90 const char* mounts_file,
91 char* buffer,
92 int buffer_size,
93 bool* result) {
94 if (buffer == NULL || buffer_size < 1)
95 return false;
96 int mounts_fd = open(mounts_file, O_RDONLY);
97 if (mounts_fd < 0)
98 return false;
99 // match_offset describes:
100 // -1 -- not beginning of line
101 // 0..strlen(device_name)-1 -- this offset in device_name is next to match
102 // strlen(device_name) -- matched full name, just need a space.
103 int match_offset = 0;
104 bool match = false;
105 while (!match) {
106 int read_size = read(mounts_fd, buffer, buffer_size);
107 if (read_size <= 0) {
108 if (errno == -EINTR)
109 continue;
110 break;
111 }
112 for (int i = 0; i < read_size; ++i) {
113 if (buffer[i] == '\n') {
114 match_offset = 0;
115 continue;
116 }
117 if (match_offset < 0) {
118 continue;
119 }
120 if (device_name[match_offset] == '\0') {
121 if (buffer[i] == ' ') {
122 match = true;
123 break;
124 }
125 match_offset = -1;
126 continue;
127 }
128
129 if (buffer[i] == device_name[match_offset]) {
130 ++match_offset;
131 } else {
132 match_offset = -1;
133 }
134 }
135 }
136 close(mounts_fd);
137 *result = match;
138 return true;
139}
140
141bool MetricsLibrary::IsGuestMode() {
142 char buffer[256];
143 bool result = false;
144 if (!IsDeviceMounted("guestfs",
145 "/proc/mounts",
146 buffer,
147 sizeof(buffer),
148 &result)) {
149 return false;
150 }
Arkaitz Ruiz Alvarez9f1a7742011-05-26 12:22:22 -0700151 return result && (access("/var/run/state/logged-in", F_OK) == 0);
Ken Mixtereafbbdf2010-10-01 15:38:42 -0700152}
153
Ken Mixter4c5daa42010-08-26 18:35:06 -0700154bool MetricsLibrary::AreMetricsEnabled() {
Julian Pastarmov70b7abd2011-08-02 16:10:49 +0200155 static struct stat stat_buffer;
Ken Mixter4c5daa42010-08-26 18:35:06 -0700156 time_t this_check_time = time(NULL);
Ken Mixter4c5daa42010-08-26 18:35:06 -0700157 if (this_check_time != cached_enabled_time_) {
158 cached_enabled_time_ = this_check_time;
Julian Pastarmov70b7abd2011-08-02 16:10:49 +0200159
160 if (!policy_provider_.get())
161 policy_provider_.reset(new policy::PolicyProvider());
Julian Pastarmovd605a002013-02-04 17:58:14 +0100162 policy_provider_->Reload();
Julian Pastarmov70b7abd2011-08-02 16:10:49 +0200163 // We initialize with the default value which is false and will be preserved
164 // if the policy is not set.
165 bool enabled = false;
166 bool has_policy = false;
167 if (policy_provider_->device_policy_is_loaded()) {
168 has_policy =
169 policy_provider_->GetDevicePolicy().GetMetricsEnabled(&enabled);
170 }
171 // If policy couldn't be loaded or the metrics policy is not set we should
172 // still respect the consent file if it is present for migration purposes.
173 // TODO(pastarmovj)
174 if (!has_policy) {
175 enabled = stat(consent_file_, &stat_buffer) >= 0;
176 }
177
Ken Mixterb2f17092011-07-22 14:59:51 -0700178 if (enabled && !IsGuestMode())
Ken Mixtereafbbdf2010-10-01 15:38:42 -0700179 cached_enabled_ = true;
180 else
181 cached_enabled_ = false;
Ken Mixter4c5daa42010-08-26 18:35:06 -0700182 }
183 return cached_enabled_;
184}
Darin Petkov11b8eb32010-05-18 11:00:59 -0700185
186bool MetricsLibrary::SendMessageToChrome(int32_t length, const char* message) {
Ken Mixter4c5daa42010-08-26 18:35:06 -0700187
Darin Petkov8842c8c2011-02-24 12:48:30 -0800188 int chrome_fd = HANDLE_EINTR(open(uma_events_file_,
189 O_WRONLY | O_APPEND | O_CREAT,
190 READ_WRITE_ALL_FILE_FLAGS));
Darin Petkov4fcb2ac2010-04-15 16:40:23 -0700191 // If we failed to open it, return.
Darin Petkov65b01462010-04-14 13:32:20 -0700192 if (chrome_fd < 0) {
Darin Petkov11b8eb32010-05-18 11:00:59 -0700193 PrintError("open", uma_events_file_, errno);
Darin Petkov4fcb2ac2010-04-15 16:40:23 -0700194 return false;
Darin Petkov65b01462010-04-14 13:32:20 -0700195 }
196
Darin Petkov4fcb2ac2010-04-15 16:40:23 -0700197 // Need to chmod because open flags are anded with umask. Ignore the
198 // exit code -- a chronos process may fail chmoding because the file
199 // has been created by a root process but that should be OK.
200 fchmod(chrome_fd, READ_WRITE_ALL_FILE_FLAGS);
Darin Petkov65b01462010-04-14 13:32:20 -0700201
Darin Petkov4fcb2ac2010-04-15 16:40:23 -0700202 // Grab an exclusive lock to protect Chrome from truncating
203 // underneath us. Keep the file locked as briefly as possible.
Darin Petkov8842c8c2011-02-24 12:48:30 -0800204 if (HANDLE_EINTR(flock(chrome_fd, LOCK_EX)) < 0) {
Darin Petkov11b8eb32010-05-18 11:00:59 -0700205 PrintError("flock", uma_events_file_, errno);
Darin Petkov8842c8c2011-02-24 12:48:30 -0800206 HANDLE_EINTR(close(chrome_fd));
Darin Petkov4fcb2ac2010-04-15 16:40:23 -0700207 return false;
Darin Petkov65b01462010-04-14 13:32:20 -0700208 }
209
Darin Petkov4fcb2ac2010-04-15 16:40:23 -0700210 bool success = true;
Darin Petkov8d3305e2011-02-25 14:19:30 -0800211 if (WriteFileDescriptor(chrome_fd, message, length) != length) {
Darin Petkov11b8eb32010-05-18 11:00:59 -0700212 PrintError("write", uma_events_file_, errno);
Darin Petkov4fcb2ac2010-04-15 16:40:23 -0700213 success = false;
214 }
Darin Petkov65b01462010-04-14 13:32:20 -0700215
Darin Petkov8842c8c2011-02-24 12:48:30 -0800216 // Close the file and release the lock.
217 HANDLE_EINTR(close(chrome_fd));
Darin Petkov4fcb2ac2010-04-15 16:40:23 -0700218 return success;
219}
220
Darin Petkov11b8eb32010-05-18 11:00:59 -0700221int32_t MetricsLibrary::FormatChromeMessage(int32_t buffer_size, char* buffer,
222 const char* format, ...) {
Darin Petkov4fcb2ac2010-04-15 16:40:23 -0700223 int32_t message_length;
224 size_t len_size = sizeof(message_length);
225
226 // Format the non-LENGTH contents in the buffer by leaving space for
227 // LENGTH at the start of the buffer.
228 va_list args;
229 va_start(args, format);
230 message_length = vsnprintf(&buffer[len_size], buffer_size - len_size,
231 format, args);
232 va_end(args);
233
234 if (message_length < 0) {
235 PrintError("chrome message format error", NULL, 0);
236 return -1;
237 }
238
239 // +1 to account for the trailing \0.
240 message_length += len_size + 1;
241 if (message_length > buffer_size) {
242 PrintError("chrome message too long", NULL, 0);
243 return -1;
244 }
245
246 // Prepend LENGTH to the message.
247 memcpy(buffer, &message_length, len_size);
248 return message_length;
249}
250
Darin Petkovfc91b422010-05-12 13:05:45 -0700251void MetricsLibrary::Init() {
Darin Petkov11b8eb32010-05-18 11:00:59 -0700252 uma_events_file_ = kUMAEventsPath;
Darin Petkovfc91b422010-05-12 13:05:45 -0700253}
254
Darin Petkovc2526a12010-04-21 14:24:04 -0700255bool MetricsLibrary::SendToAutotest(const string& name, int value) {
David James3b3add52010-06-04 15:01:19 -0700256 FILE* autotest_file = fopen(kAutotestPath, "a+");
Darin Petkov4fcb2ac2010-04-15 16:40:23 -0700257 if (autotest_file == NULL) {
258 PrintError("fopen", kAutotestPath, errno);
259 return false;
260 }
261
262 fprintf(autotest_file, "%s=%d\n", name.c_str(), value);
263 fclose(autotest_file);
264 return true;
265}
266
Darin Petkov21cd2c52010-05-12 15:26:16 -0700267bool MetricsLibrary::SendToUMA(const string& name, int sample,
268 int min, int max, int nbuckets) {
Darin Petkov4fcb2ac2010-04-15 16:40:23 -0700269 // Format the message.
270 char message[kBufferSize];
271 int32_t message_length =
272 FormatChromeMessage(kBufferSize, message,
Darin Petkovc2526a12010-04-21 14:24:04 -0700273 "histogram%c%s %d %d %d %d", '\0',
274 name.c_str(), sample, min, max, nbuckets);
Darin Petkov4fcb2ac2010-04-15 16:40:23 -0700275 if (message_length < 0)
276 return false;
277
278 // Send the message.
279 return SendMessageToChrome(message_length, message);
Darin Petkov65b01462010-04-14 13:32:20 -0700280}
Darin Petkov5b7dce12010-04-21 15:45:10 -0700281
Darin Petkov21cd2c52010-05-12 15:26:16 -0700282bool MetricsLibrary::SendEnumToUMA(const std::string& name, int sample,
283 int max) {
Darin Petkov5b7dce12010-04-21 15:45:10 -0700284 // Format the message.
285 char message[kBufferSize];
286 int32_t message_length =
287 FormatChromeMessage(kBufferSize, message,
288 "linearhistogram%c%s %d %d", '\0',
289 name.c_str(), sample, max);
Darin Petkoved824852011-01-06 10:51:47 -0800290 if (message_length < 0)
291 return false;
Darin Petkov5b7dce12010-04-21 15:45:10 -0700292
Darin Petkoved824852011-01-06 10:51:47 -0800293 // Send the message.
294 return SendMessageToChrome(message_length, message);
295}
296
Luigi Semenzatoa7ebeb32013-03-19 15:02:42 -0700297bool MetricsLibrary::SendSparseToUMA(const std::string& name, int sample) {
298 // Format the message.
299 char message[kBufferSize];
300 int32_t message_length =
301 FormatChromeMessage(kBufferSize, message, "sparsehistogram%c%s %d",
302 '\0', name.c_str(), sample);
303 if (message_length < 0)
304 return false;
305
306 // Send the message.
307 return SendMessageToChrome(message_length, message);
308}
309
Darin Petkoved824852011-01-06 10:51:47 -0800310bool MetricsLibrary::SendUserActionToUMA(const std::string& action) {
311 // Format the message.
312 char message[kBufferSize];
313 int32_t message_length =
314 FormatChromeMessage(kBufferSize, message,
315 "useraction%c%s", '\0', action.c_str());
Darin Petkov5b7dce12010-04-21 15:45:10 -0700316 if (message_length < 0)
317 return false;
318
319 // Send the message.
320 return SendMessageToChrome(message_length, message);
321}
Ken Mixterbe2e13b2011-01-22 06:15:56 -0800322
323bool MetricsLibrary::SendCrashToUMA(const char *crash_kind) {
324 // Format the message.
325 char message[kBufferSize];
326 int32_t message_length =
327 FormatChromeMessage(kBufferSize, message,
328 "crash%c%s", '\0', crash_kind);
329
330 if (message_length < 0)
331 return false;
332
333 // Send the message.
334 return SendMessageToChrome(message_length, message);
335}
Ken Mixterb2f17092011-07-22 14:59:51 -0700336
337void MetricsLibrary::SetPolicyProvider(policy::PolicyProvider* provider) {
338 policy_provider_.reset(provider);
339}
Luigi Semenzato32684222013-03-13 10:53:55 -0700340
341bool MetricsLibrary::SendCrosEventToUMA(const std::string& event) {
Chih-Chung Chang6844c062013-04-01 14:27:39 +0800342 for (size_t i = 0; i < ARRAY_SIZE(kCrosEventNames); i++) {
343 if (strcmp(event.c_str(), kCrosEventNames[i]) == 0) {
344 return SendEnumToUMA(kCrosEventHistogramName, i, kCrosEventHistogramMax);
345 }
Luigi Semenzato32684222013-03-13 10:53:55 -0700346 }
Chih-Chung Chang6844c062013-04-01 14:27:39 +0800347 return false;
Luigi Semenzato32684222013-03-13 10:53:55 -0700348}