blob: 3165561ce679fb56cc723fae885068ded26c8910 [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
Luigi Semenzatoe57398a2013-11-11 14:24:44 -080044 "SpringPowerSupply.Original.High", // 7
45 "SpringPowerSupply.Other.High", // 8
Luigi Semenzatoe8fd9682013-11-13 16:28:43 -080046 "SpringPowerSupply.Original.Low", // 9
47 "SpringPowerSupply.ChargerIdle", // 10
Chih-Chung Chang6844c062013-04-01 14:27:39 +080048};
49
Ken Mixter4c5daa42010-08-26 18:35:06 -070050time_t MetricsLibrary::cached_enabled_time_ = 0;
51bool MetricsLibrary::cached_enabled_ = false;
52
David James3b3add52010-06-04 15:01:19 -070053using std::string;
Darin Petkov65b01462010-04-14 13:32:20 -070054
55// TODO(sosa@chromium.org) - use Chromium logger instead of stderr
Darin Petkov11b8eb32010-05-18 11:00:59 -070056static void PrintError(const char* message, const char* file,
Darin Petkov4fcb2ac2010-04-15 16:40:23 -070057 int code) {
David James3b3add52010-06-04 15:01:19 -070058 static const char kProgramName[] = "libmetrics";
Darin Petkov65b01462010-04-14 13:32:20 -070059 if (code == 0) {
60 fprintf(stderr, "%s: %s\n", kProgramName, message);
61 } else if (file == NULL) {
62 fprintf(stderr, "%s: ", kProgramName);
63 perror(message);
64 } else {
65 fprintf(stderr, "%s: %s: ", kProgramName, file);
66 perror(message);
67 }
68}
69
Darin Petkov8d3305e2011-02-25 14:19:30 -080070// Copied from libbase to avoid pulling in all of libbase just for libmetrics.
71static int WriteFileDescriptor(const int fd, const char* data, int size) {
72 // Allow for partial writes.
73 ssize_t bytes_written_total = 0;
74 for (ssize_t bytes_written_partial = 0; bytes_written_total < size;
75 bytes_written_total += bytes_written_partial) {
76 bytes_written_partial =
77 HANDLE_EINTR(write(fd, data + bytes_written_total,
78 size - bytes_written_total));
79 if (bytes_written_partial < 0)
80 return -1;
81 }
82
83 return bytes_written_total;
84}
85
Darin Petkov11b8eb32010-05-18 11:00:59 -070086MetricsLibrary::MetricsLibrary()
Ken Mixter4c5daa42010-08-26 18:35:06 -070087 : uma_events_file_(NULL),
Ken Mixterb2f17092011-07-22 14:59:51 -070088 consent_file_(kConsentFile),
89 policy_provider_(NULL) {}
Ken Mixter4c5daa42010-08-26 18:35:06 -070090
Ken Mixtereafbbdf2010-10-01 15:38:42 -070091// We take buffer and buffer_size as parameters in order to simplify testing
92// of various alignments of the |device_name| with |buffer_size|.
93bool MetricsLibrary::IsDeviceMounted(const char* device_name,
94 const char* mounts_file,
95 char* buffer,
96 int buffer_size,
97 bool* result) {
98 if (buffer == NULL || buffer_size < 1)
99 return false;
100 int mounts_fd = open(mounts_file, O_RDONLY);
101 if (mounts_fd < 0)
102 return false;
103 // match_offset describes:
104 // -1 -- not beginning of line
105 // 0..strlen(device_name)-1 -- this offset in device_name is next to match
106 // strlen(device_name) -- matched full name, just need a space.
107 int match_offset = 0;
108 bool match = false;
109 while (!match) {
110 int read_size = read(mounts_fd, buffer, buffer_size);
111 if (read_size <= 0) {
112 if (errno == -EINTR)
113 continue;
114 break;
115 }
116 for (int i = 0; i < read_size; ++i) {
117 if (buffer[i] == '\n') {
118 match_offset = 0;
119 continue;
120 }
121 if (match_offset < 0) {
122 continue;
123 }
124 if (device_name[match_offset] == '\0') {
125 if (buffer[i] == ' ') {
126 match = true;
127 break;
128 }
129 match_offset = -1;
130 continue;
131 }
132
133 if (buffer[i] == device_name[match_offset]) {
134 ++match_offset;
135 } else {
136 match_offset = -1;
137 }
138 }
139 }
140 close(mounts_fd);
141 *result = match;
142 return true;
143}
144
145bool MetricsLibrary::IsGuestMode() {
146 char buffer[256];
147 bool result = false;
148 if (!IsDeviceMounted("guestfs",
149 "/proc/mounts",
150 buffer,
151 sizeof(buffer),
152 &result)) {
153 return false;
154 }
Arkaitz Ruiz Alvarez9f1a7742011-05-26 12:22:22 -0700155 return result && (access("/var/run/state/logged-in", F_OK) == 0);
Ken Mixtereafbbdf2010-10-01 15:38:42 -0700156}
157
Ken Mixter4c5daa42010-08-26 18:35:06 -0700158bool MetricsLibrary::AreMetricsEnabled() {
Julian Pastarmov70b7abd2011-08-02 16:10:49 +0200159 static struct stat stat_buffer;
Ken Mixter4c5daa42010-08-26 18:35:06 -0700160 time_t this_check_time = time(NULL);
Ken Mixter4c5daa42010-08-26 18:35:06 -0700161 if (this_check_time != cached_enabled_time_) {
162 cached_enabled_time_ = this_check_time;
Julian Pastarmov70b7abd2011-08-02 16:10:49 +0200163
164 if (!policy_provider_.get())
165 policy_provider_.reset(new policy::PolicyProvider());
Julian Pastarmovd605a002013-02-04 17:58:14 +0100166 policy_provider_->Reload();
Julian Pastarmov70b7abd2011-08-02 16:10:49 +0200167 // We initialize with the default value which is false and will be preserved
168 // if the policy is not set.
169 bool enabled = false;
170 bool has_policy = false;
171 if (policy_provider_->device_policy_is_loaded()) {
172 has_policy =
173 policy_provider_->GetDevicePolicy().GetMetricsEnabled(&enabled);
174 }
175 // If policy couldn't be loaded or the metrics policy is not set we should
176 // still respect the consent file if it is present for migration purposes.
177 // TODO(pastarmovj)
178 if (!has_policy) {
179 enabled = stat(consent_file_, &stat_buffer) >= 0;
180 }
181
Ken Mixterb2f17092011-07-22 14:59:51 -0700182 if (enabled && !IsGuestMode())
Ken Mixtereafbbdf2010-10-01 15:38:42 -0700183 cached_enabled_ = true;
184 else
185 cached_enabled_ = false;
Ken Mixter4c5daa42010-08-26 18:35:06 -0700186 }
187 return cached_enabled_;
188}
Darin Petkov11b8eb32010-05-18 11:00:59 -0700189
190bool MetricsLibrary::SendMessageToChrome(int32_t length, const char* message) {
Ken Mixter4c5daa42010-08-26 18:35:06 -0700191
Darin Petkov8842c8c2011-02-24 12:48:30 -0800192 int chrome_fd = HANDLE_EINTR(open(uma_events_file_,
193 O_WRONLY | O_APPEND | O_CREAT,
194 READ_WRITE_ALL_FILE_FLAGS));
Darin Petkov4fcb2ac2010-04-15 16:40:23 -0700195 // If we failed to open it, return.
Darin Petkov65b01462010-04-14 13:32:20 -0700196 if (chrome_fd < 0) {
Darin Petkov11b8eb32010-05-18 11:00:59 -0700197 PrintError("open", uma_events_file_, errno);
Darin Petkov4fcb2ac2010-04-15 16:40:23 -0700198 return false;
Darin Petkov65b01462010-04-14 13:32:20 -0700199 }
200
Darin Petkov4fcb2ac2010-04-15 16:40:23 -0700201 // Need to chmod because open flags are anded with umask. Ignore the
202 // exit code -- a chronos process may fail chmoding because the file
203 // has been created by a root process but that should be OK.
204 fchmod(chrome_fd, READ_WRITE_ALL_FILE_FLAGS);
Darin Petkov65b01462010-04-14 13:32:20 -0700205
Darin Petkov4fcb2ac2010-04-15 16:40:23 -0700206 // Grab an exclusive lock to protect Chrome from truncating
207 // underneath us. Keep the file locked as briefly as possible.
Darin Petkov8842c8c2011-02-24 12:48:30 -0800208 if (HANDLE_EINTR(flock(chrome_fd, LOCK_EX)) < 0) {
Darin Petkov11b8eb32010-05-18 11:00:59 -0700209 PrintError("flock", uma_events_file_, errno);
Darin Petkov8842c8c2011-02-24 12:48:30 -0800210 HANDLE_EINTR(close(chrome_fd));
Darin Petkov4fcb2ac2010-04-15 16:40:23 -0700211 return false;
Darin Petkov65b01462010-04-14 13:32:20 -0700212 }
213
Darin Petkov4fcb2ac2010-04-15 16:40:23 -0700214 bool success = true;
Darin Petkov8d3305e2011-02-25 14:19:30 -0800215 if (WriteFileDescriptor(chrome_fd, message, length) != length) {
Darin Petkov11b8eb32010-05-18 11:00:59 -0700216 PrintError("write", uma_events_file_, errno);
Darin Petkov4fcb2ac2010-04-15 16:40:23 -0700217 success = false;
218 }
Darin Petkov65b01462010-04-14 13:32:20 -0700219
Darin Petkov8842c8c2011-02-24 12:48:30 -0800220 // Close the file and release the lock.
221 HANDLE_EINTR(close(chrome_fd));
Darin Petkov4fcb2ac2010-04-15 16:40:23 -0700222 return success;
223}
224
Darin Petkov11b8eb32010-05-18 11:00:59 -0700225int32_t MetricsLibrary::FormatChromeMessage(int32_t buffer_size, char* buffer,
226 const char* format, ...) {
Darin Petkov4fcb2ac2010-04-15 16:40:23 -0700227 int32_t message_length;
228 size_t len_size = sizeof(message_length);
229
230 // Format the non-LENGTH contents in the buffer by leaving space for
231 // LENGTH at the start of the buffer.
232 va_list args;
233 va_start(args, format);
234 message_length = vsnprintf(&buffer[len_size], buffer_size - len_size,
235 format, args);
236 va_end(args);
237
238 if (message_length < 0) {
239 PrintError("chrome message format error", NULL, 0);
240 return -1;
241 }
242
243 // +1 to account for the trailing \0.
244 message_length += len_size + 1;
245 if (message_length > buffer_size) {
246 PrintError("chrome message too long", NULL, 0);
247 return -1;
248 }
249
250 // Prepend LENGTH to the message.
251 memcpy(buffer, &message_length, len_size);
252 return message_length;
253}
254
Darin Petkovfc91b422010-05-12 13:05:45 -0700255void MetricsLibrary::Init() {
Darin Petkov11b8eb32010-05-18 11:00:59 -0700256 uma_events_file_ = kUMAEventsPath;
Darin Petkovfc91b422010-05-12 13:05:45 -0700257}
258
Darin Petkovc2526a12010-04-21 14:24:04 -0700259bool MetricsLibrary::SendToAutotest(const string& name, int value) {
David James3b3add52010-06-04 15:01:19 -0700260 FILE* autotest_file = fopen(kAutotestPath, "a+");
Darin Petkov4fcb2ac2010-04-15 16:40:23 -0700261 if (autotest_file == NULL) {
262 PrintError("fopen", kAutotestPath, errno);
263 return false;
264 }
265
266 fprintf(autotest_file, "%s=%d\n", name.c_str(), value);
267 fclose(autotest_file);
268 return true;
269}
270
Darin Petkov21cd2c52010-05-12 15:26:16 -0700271bool MetricsLibrary::SendToUMA(const string& name, int sample,
272 int min, int max, int nbuckets) {
Darin Petkov4fcb2ac2010-04-15 16:40:23 -0700273 // Format the message.
274 char message[kBufferSize];
275 int32_t message_length =
276 FormatChromeMessage(kBufferSize, message,
Darin Petkovc2526a12010-04-21 14:24:04 -0700277 "histogram%c%s %d %d %d %d", '\0',
278 name.c_str(), sample, min, max, nbuckets);
Darin Petkov4fcb2ac2010-04-15 16:40:23 -0700279 if (message_length < 0)
280 return false;
281
282 // Send the message.
283 return SendMessageToChrome(message_length, message);
Darin Petkov65b01462010-04-14 13:32:20 -0700284}
Darin Petkov5b7dce12010-04-21 15:45:10 -0700285
Darin Petkov21cd2c52010-05-12 15:26:16 -0700286bool MetricsLibrary::SendEnumToUMA(const std::string& name, int sample,
287 int max) {
Darin Petkov5b7dce12010-04-21 15:45:10 -0700288 // Format the message.
289 char message[kBufferSize];
290 int32_t message_length =
291 FormatChromeMessage(kBufferSize, message,
292 "linearhistogram%c%s %d %d", '\0',
293 name.c_str(), sample, max);
Darin Petkoved824852011-01-06 10:51:47 -0800294 if (message_length < 0)
295 return false;
Darin Petkov5b7dce12010-04-21 15:45:10 -0700296
Darin Petkoved824852011-01-06 10:51:47 -0800297 // Send the message.
298 return SendMessageToChrome(message_length, message);
299}
300
Luigi Semenzatoa7ebeb32013-03-19 15:02:42 -0700301bool MetricsLibrary::SendSparseToUMA(const std::string& name, int sample) {
302 // Format the message.
303 char message[kBufferSize];
304 int32_t message_length =
305 FormatChromeMessage(kBufferSize, message, "sparsehistogram%c%s %d",
306 '\0', name.c_str(), sample);
307 if (message_length < 0)
308 return false;
309
310 // Send the message.
311 return SendMessageToChrome(message_length, message);
312}
313
Darin Petkoved824852011-01-06 10:51:47 -0800314bool MetricsLibrary::SendUserActionToUMA(const std::string& action) {
315 // Format the message.
316 char message[kBufferSize];
317 int32_t message_length =
318 FormatChromeMessage(kBufferSize, message,
319 "useraction%c%s", '\0', action.c_str());
Darin Petkov5b7dce12010-04-21 15:45:10 -0700320 if (message_length < 0)
321 return false;
322
323 // Send the message.
324 return SendMessageToChrome(message_length, message);
325}
Ken Mixterbe2e13b2011-01-22 06:15:56 -0800326
327bool MetricsLibrary::SendCrashToUMA(const char *crash_kind) {
328 // Format the message.
329 char message[kBufferSize];
330 int32_t message_length =
331 FormatChromeMessage(kBufferSize, message,
332 "crash%c%s", '\0', crash_kind);
333
334 if (message_length < 0)
335 return false;
336
337 // Send the message.
338 return SendMessageToChrome(message_length, message);
339}
Ken Mixterb2f17092011-07-22 14:59:51 -0700340
341void MetricsLibrary::SetPolicyProvider(policy::PolicyProvider* provider) {
342 policy_provider_.reset(provider);
343}
Luigi Semenzato32684222013-03-13 10:53:55 -0700344
345bool MetricsLibrary::SendCrosEventToUMA(const std::string& event) {
Chih-Chung Chang6844c062013-04-01 14:27:39 +0800346 for (size_t i = 0; i < ARRAY_SIZE(kCrosEventNames); i++) {
347 if (strcmp(event.c_str(), kCrosEventNames[i]) == 0) {
348 return SendEnumToUMA(kCrosEventHistogramName, i, kCrosEventHistogramMax);
349 }
Luigi Semenzato32684222013-03-13 10:53:55 -0700350 }
Chih-Chung Chang6844c062013-04-01 14:27:39 +0800351 return false;
Luigi Semenzato32684222013-03-13 10:53:55 -0700352}