blob: 12b0c712229ba1e2987755401709ea41fcd6bef2 [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
Darren Krahn09a15fa2014-02-07 16:51:15 -080048 "TPM.NonZeroDictionaryAttackCounter", // 11
Chih-Chung Chang6844c062013-04-01 14:27:39 +080049};
50
Ken Mixter4c5daa42010-08-26 18:35:06 -070051time_t MetricsLibrary::cached_enabled_time_ = 0;
52bool MetricsLibrary::cached_enabled_ = false;
53
David James3b3add52010-06-04 15:01:19 -070054using std::string;
Darin Petkov65b01462010-04-14 13:32:20 -070055
56// TODO(sosa@chromium.org) - use Chromium logger instead of stderr
Darin Petkov11b8eb32010-05-18 11:00:59 -070057static void PrintError(const char* message, const char* file,
Darin Petkov4fcb2ac2010-04-15 16:40:23 -070058 int code) {
David James3b3add52010-06-04 15:01:19 -070059 static const char kProgramName[] = "libmetrics";
Darin Petkov65b01462010-04-14 13:32:20 -070060 if (code == 0) {
61 fprintf(stderr, "%s: %s\n", kProgramName, message);
62 } else if (file == NULL) {
63 fprintf(stderr, "%s: ", kProgramName);
64 perror(message);
65 } else {
66 fprintf(stderr, "%s: %s: ", kProgramName, file);
67 perror(message);
68 }
69}
70
Darin Petkov8d3305e2011-02-25 14:19:30 -080071// Copied from libbase to avoid pulling in all of libbase just for libmetrics.
72static int WriteFileDescriptor(const int fd, const char* data, int size) {
73 // Allow for partial writes.
74 ssize_t bytes_written_total = 0;
75 for (ssize_t bytes_written_partial = 0; bytes_written_total < size;
76 bytes_written_total += bytes_written_partial) {
77 bytes_written_partial =
78 HANDLE_EINTR(write(fd, data + bytes_written_total,
79 size - bytes_written_total));
80 if (bytes_written_partial < 0)
81 return -1;
82 }
83
84 return bytes_written_total;
85}
86
Darin Petkov11b8eb32010-05-18 11:00:59 -070087MetricsLibrary::MetricsLibrary()
Ken Mixter4c5daa42010-08-26 18:35:06 -070088 : uma_events_file_(NULL),
Ken Mixterb2f17092011-07-22 14:59:51 -070089 consent_file_(kConsentFile),
90 policy_provider_(NULL) {}
Ken Mixter4c5daa42010-08-26 18:35:06 -070091
Ken Mixtereafbbdf2010-10-01 15:38:42 -070092// We take buffer and buffer_size as parameters in order to simplify testing
93// of various alignments of the |device_name| with |buffer_size|.
94bool MetricsLibrary::IsDeviceMounted(const char* device_name,
95 const char* mounts_file,
96 char* buffer,
97 int buffer_size,
98 bool* result) {
99 if (buffer == NULL || buffer_size < 1)
100 return false;
101 int mounts_fd = open(mounts_file, O_RDONLY);
102 if (mounts_fd < 0)
103 return false;
104 // match_offset describes:
105 // -1 -- not beginning of line
106 // 0..strlen(device_name)-1 -- this offset in device_name is next to match
107 // strlen(device_name) -- matched full name, just need a space.
108 int match_offset = 0;
109 bool match = false;
110 while (!match) {
111 int read_size = read(mounts_fd, buffer, buffer_size);
112 if (read_size <= 0) {
113 if (errno == -EINTR)
114 continue;
115 break;
116 }
117 for (int i = 0; i < read_size; ++i) {
118 if (buffer[i] == '\n') {
119 match_offset = 0;
120 continue;
121 }
122 if (match_offset < 0) {
123 continue;
124 }
125 if (device_name[match_offset] == '\0') {
126 if (buffer[i] == ' ') {
127 match = true;
128 break;
129 }
130 match_offset = -1;
131 continue;
132 }
133
134 if (buffer[i] == device_name[match_offset]) {
135 ++match_offset;
136 } else {
137 match_offset = -1;
138 }
139 }
140 }
141 close(mounts_fd);
142 *result = match;
143 return true;
144}
145
146bool MetricsLibrary::IsGuestMode() {
147 char buffer[256];
148 bool result = false;
149 if (!IsDeviceMounted("guestfs",
150 "/proc/mounts",
151 buffer,
152 sizeof(buffer),
153 &result)) {
154 return false;
155 }
Arkaitz Ruiz Alvarez9f1a7742011-05-26 12:22:22 -0700156 return result && (access("/var/run/state/logged-in", F_OK) == 0);
Ken Mixtereafbbdf2010-10-01 15:38:42 -0700157}
158
Ken Mixter4c5daa42010-08-26 18:35:06 -0700159bool MetricsLibrary::AreMetricsEnabled() {
Julian Pastarmov70b7abd2011-08-02 16:10:49 +0200160 static struct stat stat_buffer;
Ken Mixter4c5daa42010-08-26 18:35:06 -0700161 time_t this_check_time = time(NULL);
Ken Mixter4c5daa42010-08-26 18:35:06 -0700162 if (this_check_time != cached_enabled_time_) {
163 cached_enabled_time_ = this_check_time;
Julian Pastarmov70b7abd2011-08-02 16:10:49 +0200164
165 if (!policy_provider_.get())
166 policy_provider_.reset(new policy::PolicyProvider());
Julian Pastarmovd605a002013-02-04 17:58:14 +0100167 policy_provider_->Reload();
Julian Pastarmov70b7abd2011-08-02 16:10:49 +0200168 // We initialize with the default value which is false and will be preserved
169 // if the policy is not set.
170 bool enabled = false;
171 bool has_policy = false;
172 if (policy_provider_->device_policy_is_loaded()) {
173 has_policy =
174 policy_provider_->GetDevicePolicy().GetMetricsEnabled(&enabled);
175 }
176 // If policy couldn't be loaded or the metrics policy is not set we should
177 // still respect the consent file if it is present for migration purposes.
178 // TODO(pastarmovj)
179 if (!has_policy) {
180 enabled = stat(consent_file_, &stat_buffer) >= 0;
181 }
182
Ken Mixterb2f17092011-07-22 14:59:51 -0700183 if (enabled && !IsGuestMode())
Ken Mixtereafbbdf2010-10-01 15:38:42 -0700184 cached_enabled_ = true;
185 else
186 cached_enabled_ = false;
Ken Mixter4c5daa42010-08-26 18:35:06 -0700187 }
188 return cached_enabled_;
189}
Darin Petkov11b8eb32010-05-18 11:00:59 -0700190
191bool MetricsLibrary::SendMessageToChrome(int32_t length, const char* message) {
Ken Mixter4c5daa42010-08-26 18:35:06 -0700192
Darin Petkov8842c8c2011-02-24 12:48:30 -0800193 int chrome_fd = HANDLE_EINTR(open(uma_events_file_,
194 O_WRONLY | O_APPEND | O_CREAT,
195 READ_WRITE_ALL_FILE_FLAGS));
Darin Petkov4fcb2ac2010-04-15 16:40:23 -0700196 // If we failed to open it, return.
Darin Petkov65b01462010-04-14 13:32:20 -0700197 if (chrome_fd < 0) {
Darin Petkov11b8eb32010-05-18 11:00:59 -0700198 PrintError("open", uma_events_file_, errno);
Darin Petkov4fcb2ac2010-04-15 16:40:23 -0700199 return false;
Darin Petkov65b01462010-04-14 13:32:20 -0700200 }
201
Darin Petkov4fcb2ac2010-04-15 16:40:23 -0700202 // Need to chmod because open flags are anded with umask. Ignore the
203 // exit code -- a chronos process may fail chmoding because the file
204 // has been created by a root process but that should be OK.
205 fchmod(chrome_fd, READ_WRITE_ALL_FILE_FLAGS);
Darin Petkov65b01462010-04-14 13:32:20 -0700206
Darin Petkov4fcb2ac2010-04-15 16:40:23 -0700207 // Grab an exclusive lock to protect Chrome from truncating
208 // underneath us. Keep the file locked as briefly as possible.
Darin Petkov8842c8c2011-02-24 12:48:30 -0800209 if (HANDLE_EINTR(flock(chrome_fd, LOCK_EX)) < 0) {
Darin Petkov11b8eb32010-05-18 11:00:59 -0700210 PrintError("flock", uma_events_file_, errno);
Darin Petkov8842c8c2011-02-24 12:48:30 -0800211 HANDLE_EINTR(close(chrome_fd));
Darin Petkov4fcb2ac2010-04-15 16:40:23 -0700212 return false;
Darin Petkov65b01462010-04-14 13:32:20 -0700213 }
214
Darin Petkov4fcb2ac2010-04-15 16:40:23 -0700215 bool success = true;
Darin Petkov8d3305e2011-02-25 14:19:30 -0800216 if (WriteFileDescriptor(chrome_fd, message, length) != length) {
Darin Petkov11b8eb32010-05-18 11:00:59 -0700217 PrintError("write", uma_events_file_, errno);
Darin Petkov4fcb2ac2010-04-15 16:40:23 -0700218 success = false;
219 }
Darin Petkov65b01462010-04-14 13:32:20 -0700220
Darin Petkov8842c8c2011-02-24 12:48:30 -0800221 // Close the file and release the lock.
222 HANDLE_EINTR(close(chrome_fd));
Darin Petkov4fcb2ac2010-04-15 16:40:23 -0700223 return success;
224}
225
Darin Petkov11b8eb32010-05-18 11:00:59 -0700226int32_t MetricsLibrary::FormatChromeMessage(int32_t buffer_size, char* buffer,
227 const char* format, ...) {
Darin Petkov4fcb2ac2010-04-15 16:40:23 -0700228 int32_t message_length;
229 size_t len_size = sizeof(message_length);
230
231 // Format the non-LENGTH contents in the buffer by leaving space for
232 // LENGTH at the start of the buffer.
233 va_list args;
234 va_start(args, format);
235 message_length = vsnprintf(&buffer[len_size], buffer_size - len_size,
236 format, args);
237 va_end(args);
238
239 if (message_length < 0) {
240 PrintError("chrome message format error", NULL, 0);
241 return -1;
242 }
243
244 // +1 to account for the trailing \0.
245 message_length += len_size + 1;
246 if (message_length > buffer_size) {
247 PrintError("chrome message too long", NULL, 0);
248 return -1;
249 }
250
251 // Prepend LENGTH to the message.
252 memcpy(buffer, &message_length, len_size);
253 return message_length;
254}
255
Darin Petkovfc91b422010-05-12 13:05:45 -0700256void MetricsLibrary::Init() {
Darin Petkov11b8eb32010-05-18 11:00:59 -0700257 uma_events_file_ = kUMAEventsPath;
Darin Petkovfc91b422010-05-12 13:05:45 -0700258}
259
Darin Petkovc2526a12010-04-21 14:24:04 -0700260bool MetricsLibrary::SendToAutotest(const string& name, int value) {
David James3b3add52010-06-04 15:01:19 -0700261 FILE* autotest_file = fopen(kAutotestPath, "a+");
Darin Petkov4fcb2ac2010-04-15 16:40:23 -0700262 if (autotest_file == NULL) {
263 PrintError("fopen", kAutotestPath, errno);
264 return false;
265 }
266
267 fprintf(autotest_file, "%s=%d\n", name.c_str(), value);
268 fclose(autotest_file);
269 return true;
270}
271
Darin Petkov21cd2c52010-05-12 15:26:16 -0700272bool MetricsLibrary::SendToUMA(const string& name, int sample,
273 int min, int max, int nbuckets) {
Darin Petkov4fcb2ac2010-04-15 16:40:23 -0700274 // Format the message.
275 char message[kBufferSize];
276 int32_t message_length =
277 FormatChromeMessage(kBufferSize, message,
Darin Petkovc2526a12010-04-21 14:24:04 -0700278 "histogram%c%s %d %d %d %d", '\0',
279 name.c_str(), sample, min, max, nbuckets);
Darin Petkov4fcb2ac2010-04-15 16:40:23 -0700280 if (message_length < 0)
281 return false;
282
283 // Send the message.
284 return SendMessageToChrome(message_length, message);
Darin Petkov65b01462010-04-14 13:32:20 -0700285}
Darin Petkov5b7dce12010-04-21 15:45:10 -0700286
Darin Petkov21cd2c52010-05-12 15:26:16 -0700287bool MetricsLibrary::SendEnumToUMA(const std::string& name, int sample,
288 int max) {
Darin Petkov5b7dce12010-04-21 15:45:10 -0700289 // Format the message.
290 char message[kBufferSize];
291 int32_t message_length =
292 FormatChromeMessage(kBufferSize, message,
293 "linearhistogram%c%s %d %d", '\0',
294 name.c_str(), sample, max);
Darin Petkoved824852011-01-06 10:51:47 -0800295 if (message_length < 0)
296 return false;
Darin Petkov5b7dce12010-04-21 15:45:10 -0700297
Darin Petkoved824852011-01-06 10:51:47 -0800298 // Send the message.
299 return SendMessageToChrome(message_length, message);
300}
301
Luigi Semenzatoa7ebeb32013-03-19 15:02:42 -0700302bool MetricsLibrary::SendSparseToUMA(const std::string& name, int sample) {
303 // Format the message.
304 char message[kBufferSize];
305 int32_t message_length =
306 FormatChromeMessage(kBufferSize, message, "sparsehistogram%c%s %d",
307 '\0', name.c_str(), sample);
308 if (message_length < 0)
309 return false;
310
311 // Send the message.
312 return SendMessageToChrome(message_length, message);
313}
314
Darin Petkoved824852011-01-06 10:51:47 -0800315bool MetricsLibrary::SendUserActionToUMA(const std::string& action) {
316 // Format the message.
317 char message[kBufferSize];
318 int32_t message_length =
319 FormatChromeMessage(kBufferSize, message,
320 "useraction%c%s", '\0', action.c_str());
Darin Petkov5b7dce12010-04-21 15:45:10 -0700321 if (message_length < 0)
322 return false;
323
324 // Send the message.
325 return SendMessageToChrome(message_length, message);
326}
Ken Mixterbe2e13b2011-01-22 06:15:56 -0800327
328bool MetricsLibrary::SendCrashToUMA(const char *crash_kind) {
329 // Format the message.
330 char message[kBufferSize];
331 int32_t message_length =
332 FormatChromeMessage(kBufferSize, message,
333 "crash%c%s", '\0', crash_kind);
334
335 if (message_length < 0)
336 return false;
337
338 // Send the message.
339 return SendMessageToChrome(message_length, message);
340}
Ken Mixterb2f17092011-07-22 14:59:51 -0700341
342void MetricsLibrary::SetPolicyProvider(policy::PolicyProvider* provider) {
343 policy_provider_.reset(provider);
344}
Luigi Semenzato32684222013-03-13 10:53:55 -0700345
346bool MetricsLibrary::SendCrosEventToUMA(const std::string& event) {
Chih-Chung Chang6844c062013-04-01 14:27:39 +0800347 for (size_t i = 0; i < ARRAY_SIZE(kCrosEventNames); i++) {
348 if (strcmp(event.c_str(), kCrosEventNames[i]) == 0) {
349 return SendEnumToUMA(kCrosEventHistogramName, i, kCrosEventHistogramMax);
350 }
Luigi Semenzato32684222013-03-13 10:53:55 -0700351 }
Chih-Chung Chang6844c062013-04-01 14:27:39 +0800352 return false;
Luigi Semenzato32684222013-03-13 10:53:55 -0700353}