blob: 12ad226f2db8236bbd41f233538f098effbea7f3 [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
Chih-Chung Chang6844c062013-04-01 14:27:39 +080043};
44
Ken Mixter4c5daa42010-08-26 18:35:06 -070045time_t MetricsLibrary::cached_enabled_time_ = 0;
46bool MetricsLibrary::cached_enabled_ = false;
47
David James3b3add52010-06-04 15:01:19 -070048using std::string;
Darin Petkov65b01462010-04-14 13:32:20 -070049
50// TODO(sosa@chromium.org) - use Chromium logger instead of stderr
Darin Petkov11b8eb32010-05-18 11:00:59 -070051static void PrintError(const char* message, const char* file,
Darin Petkov4fcb2ac2010-04-15 16:40:23 -070052 int code) {
David James3b3add52010-06-04 15:01:19 -070053 static const char kProgramName[] = "libmetrics";
Darin Petkov65b01462010-04-14 13:32:20 -070054 if (code == 0) {
55 fprintf(stderr, "%s: %s\n", kProgramName, message);
56 } else if (file == NULL) {
57 fprintf(stderr, "%s: ", kProgramName);
58 perror(message);
59 } else {
60 fprintf(stderr, "%s: %s: ", kProgramName, file);
61 perror(message);
62 }
63}
64
Darin Petkov8d3305e2011-02-25 14:19:30 -080065// Copied from libbase to avoid pulling in all of libbase just for libmetrics.
66static int WriteFileDescriptor(const int fd, const char* data, int size) {
67 // Allow for partial writes.
68 ssize_t bytes_written_total = 0;
69 for (ssize_t bytes_written_partial = 0; bytes_written_total < size;
70 bytes_written_total += bytes_written_partial) {
71 bytes_written_partial =
72 HANDLE_EINTR(write(fd, data + bytes_written_total,
73 size - bytes_written_total));
74 if (bytes_written_partial < 0)
75 return -1;
76 }
77
78 return bytes_written_total;
79}
80
Darin Petkov11b8eb32010-05-18 11:00:59 -070081MetricsLibrary::MetricsLibrary()
Ken Mixter4c5daa42010-08-26 18:35:06 -070082 : uma_events_file_(NULL),
Ken Mixterb2f17092011-07-22 14:59:51 -070083 consent_file_(kConsentFile),
84 policy_provider_(NULL) {}
Ken Mixter4c5daa42010-08-26 18:35:06 -070085
Ken Mixtereafbbdf2010-10-01 15:38:42 -070086// We take buffer and buffer_size as parameters in order to simplify testing
87// of various alignments of the |device_name| with |buffer_size|.
88bool MetricsLibrary::IsDeviceMounted(const char* device_name,
89 const char* mounts_file,
90 char* buffer,
91 int buffer_size,
92 bool* result) {
93 if (buffer == NULL || buffer_size < 1)
94 return false;
95 int mounts_fd = open(mounts_file, O_RDONLY);
96 if (mounts_fd < 0)
97 return false;
98 // match_offset describes:
99 // -1 -- not beginning of line
100 // 0..strlen(device_name)-1 -- this offset in device_name is next to match
101 // strlen(device_name) -- matched full name, just need a space.
102 int match_offset = 0;
103 bool match = false;
104 while (!match) {
105 int read_size = read(mounts_fd, buffer, buffer_size);
106 if (read_size <= 0) {
107 if (errno == -EINTR)
108 continue;
109 break;
110 }
111 for (int i = 0; i < read_size; ++i) {
112 if (buffer[i] == '\n') {
113 match_offset = 0;
114 continue;
115 }
116 if (match_offset < 0) {
117 continue;
118 }
119 if (device_name[match_offset] == '\0') {
120 if (buffer[i] == ' ') {
121 match = true;
122 break;
123 }
124 match_offset = -1;
125 continue;
126 }
127
128 if (buffer[i] == device_name[match_offset]) {
129 ++match_offset;
130 } else {
131 match_offset = -1;
132 }
133 }
134 }
135 close(mounts_fd);
136 *result = match;
137 return true;
138}
139
140bool MetricsLibrary::IsGuestMode() {
141 char buffer[256];
142 bool result = false;
143 if (!IsDeviceMounted("guestfs",
144 "/proc/mounts",
145 buffer,
146 sizeof(buffer),
147 &result)) {
148 return false;
149 }
Arkaitz Ruiz Alvarez9f1a7742011-05-26 12:22:22 -0700150 return result && (access("/var/run/state/logged-in", F_OK) == 0);
Ken Mixtereafbbdf2010-10-01 15:38:42 -0700151}
152
Ken Mixter4c5daa42010-08-26 18:35:06 -0700153bool MetricsLibrary::AreMetricsEnabled() {
Julian Pastarmov70b7abd2011-08-02 16:10:49 +0200154 static struct stat stat_buffer;
Ken Mixter4c5daa42010-08-26 18:35:06 -0700155 time_t this_check_time = time(NULL);
Ken Mixter4c5daa42010-08-26 18:35:06 -0700156 if (this_check_time != cached_enabled_time_) {
157 cached_enabled_time_ = this_check_time;
Julian Pastarmov70b7abd2011-08-02 16:10:49 +0200158
159 if (!policy_provider_.get())
160 policy_provider_.reset(new policy::PolicyProvider());
Julian Pastarmovd605a002013-02-04 17:58:14 +0100161 policy_provider_->Reload();
Julian Pastarmov70b7abd2011-08-02 16:10:49 +0200162 // We initialize with the default value which is false and will be preserved
163 // if the policy is not set.
164 bool enabled = false;
165 bool has_policy = false;
166 if (policy_provider_->device_policy_is_loaded()) {
167 has_policy =
168 policy_provider_->GetDevicePolicy().GetMetricsEnabled(&enabled);
169 }
170 // If policy couldn't be loaded or the metrics policy is not set we should
171 // still respect the consent file if it is present for migration purposes.
172 // TODO(pastarmovj)
173 if (!has_policy) {
174 enabled = stat(consent_file_, &stat_buffer) >= 0;
175 }
176
Ken Mixterb2f17092011-07-22 14:59:51 -0700177 if (enabled && !IsGuestMode())
Ken Mixtereafbbdf2010-10-01 15:38:42 -0700178 cached_enabled_ = true;
179 else
180 cached_enabled_ = false;
Ken Mixter4c5daa42010-08-26 18:35:06 -0700181 }
182 return cached_enabled_;
183}
Darin Petkov11b8eb32010-05-18 11:00:59 -0700184
185bool MetricsLibrary::SendMessageToChrome(int32_t length, const char* message) {
Ken Mixter4c5daa42010-08-26 18:35:06 -0700186
Darin Petkov8842c8c2011-02-24 12:48:30 -0800187 int chrome_fd = HANDLE_EINTR(open(uma_events_file_,
188 O_WRONLY | O_APPEND | O_CREAT,
189 READ_WRITE_ALL_FILE_FLAGS));
Darin Petkov4fcb2ac2010-04-15 16:40:23 -0700190 // If we failed to open it, return.
Darin Petkov65b01462010-04-14 13:32:20 -0700191 if (chrome_fd < 0) {
Darin Petkov11b8eb32010-05-18 11:00:59 -0700192 PrintError("open", uma_events_file_, errno);
Darin Petkov4fcb2ac2010-04-15 16:40:23 -0700193 return false;
Darin Petkov65b01462010-04-14 13:32:20 -0700194 }
195
Darin Petkov4fcb2ac2010-04-15 16:40:23 -0700196 // Need to chmod because open flags are anded with umask. Ignore the
197 // exit code -- a chronos process may fail chmoding because the file
198 // has been created by a root process but that should be OK.
199 fchmod(chrome_fd, READ_WRITE_ALL_FILE_FLAGS);
Darin Petkov65b01462010-04-14 13:32:20 -0700200
Darin Petkov4fcb2ac2010-04-15 16:40:23 -0700201 // Grab an exclusive lock to protect Chrome from truncating
202 // underneath us. Keep the file locked as briefly as possible.
Darin Petkov8842c8c2011-02-24 12:48:30 -0800203 if (HANDLE_EINTR(flock(chrome_fd, LOCK_EX)) < 0) {
Darin Petkov11b8eb32010-05-18 11:00:59 -0700204 PrintError("flock", uma_events_file_, errno);
Darin Petkov8842c8c2011-02-24 12:48:30 -0800205 HANDLE_EINTR(close(chrome_fd));
Darin Petkov4fcb2ac2010-04-15 16:40:23 -0700206 return false;
Darin Petkov65b01462010-04-14 13:32:20 -0700207 }
208
Darin Petkov4fcb2ac2010-04-15 16:40:23 -0700209 bool success = true;
Darin Petkov8d3305e2011-02-25 14:19:30 -0800210 if (WriteFileDescriptor(chrome_fd, message, length) != length) {
Darin Petkov11b8eb32010-05-18 11:00:59 -0700211 PrintError("write", uma_events_file_, errno);
Darin Petkov4fcb2ac2010-04-15 16:40:23 -0700212 success = false;
213 }
Darin Petkov65b01462010-04-14 13:32:20 -0700214
Darin Petkov8842c8c2011-02-24 12:48:30 -0800215 // Close the file and release the lock.
216 HANDLE_EINTR(close(chrome_fd));
Darin Petkov4fcb2ac2010-04-15 16:40:23 -0700217 return success;
218}
219
Darin Petkov11b8eb32010-05-18 11:00:59 -0700220int32_t MetricsLibrary::FormatChromeMessage(int32_t buffer_size, char* buffer,
221 const char* format, ...) {
Darin Petkov4fcb2ac2010-04-15 16:40:23 -0700222 int32_t message_length;
223 size_t len_size = sizeof(message_length);
224
225 // Format the non-LENGTH contents in the buffer by leaving space for
226 // LENGTH at the start of the buffer.
227 va_list args;
228 va_start(args, format);
229 message_length = vsnprintf(&buffer[len_size], buffer_size - len_size,
230 format, args);
231 va_end(args);
232
233 if (message_length < 0) {
234 PrintError("chrome message format error", NULL, 0);
235 return -1;
236 }
237
238 // +1 to account for the trailing \0.
239 message_length += len_size + 1;
240 if (message_length > buffer_size) {
241 PrintError("chrome message too long", NULL, 0);
242 return -1;
243 }
244
245 // Prepend LENGTH to the message.
246 memcpy(buffer, &message_length, len_size);
247 return message_length;
248}
249
Darin Petkovfc91b422010-05-12 13:05:45 -0700250void MetricsLibrary::Init() {
Darin Petkov11b8eb32010-05-18 11:00:59 -0700251 uma_events_file_ = kUMAEventsPath;
Darin Petkovfc91b422010-05-12 13:05:45 -0700252}
253
Darin Petkovc2526a12010-04-21 14:24:04 -0700254bool MetricsLibrary::SendToAutotest(const string& name, int value) {
David James3b3add52010-06-04 15:01:19 -0700255 FILE* autotest_file = fopen(kAutotestPath, "a+");
Darin Petkov4fcb2ac2010-04-15 16:40:23 -0700256 if (autotest_file == NULL) {
257 PrintError("fopen", kAutotestPath, errno);
258 return false;
259 }
260
261 fprintf(autotest_file, "%s=%d\n", name.c_str(), value);
262 fclose(autotest_file);
263 return true;
264}
265
Darin Petkov21cd2c52010-05-12 15:26:16 -0700266bool MetricsLibrary::SendToUMA(const string& name, int sample,
267 int min, int max, int nbuckets) {
Darin Petkov4fcb2ac2010-04-15 16:40:23 -0700268 // Format the message.
269 char message[kBufferSize];
270 int32_t message_length =
271 FormatChromeMessage(kBufferSize, message,
Darin Petkovc2526a12010-04-21 14:24:04 -0700272 "histogram%c%s %d %d %d %d", '\0',
273 name.c_str(), sample, min, max, nbuckets);
Darin Petkov4fcb2ac2010-04-15 16:40:23 -0700274 if (message_length < 0)
275 return false;
276
277 // Send the message.
278 return SendMessageToChrome(message_length, message);
Darin Petkov65b01462010-04-14 13:32:20 -0700279}
Darin Petkov5b7dce12010-04-21 15:45:10 -0700280
Darin Petkov21cd2c52010-05-12 15:26:16 -0700281bool MetricsLibrary::SendEnumToUMA(const std::string& name, int sample,
282 int max) {
Darin Petkov5b7dce12010-04-21 15:45:10 -0700283 // Format the message.
284 char message[kBufferSize];
285 int32_t message_length =
286 FormatChromeMessage(kBufferSize, message,
287 "linearhistogram%c%s %d %d", '\0',
288 name.c_str(), sample, max);
Darin Petkoved824852011-01-06 10:51:47 -0800289 if (message_length < 0)
290 return false;
Darin Petkov5b7dce12010-04-21 15:45:10 -0700291
Darin Petkoved824852011-01-06 10:51:47 -0800292 // Send the message.
293 return SendMessageToChrome(message_length, message);
294}
295
Luigi Semenzatoa7ebeb32013-03-19 15:02:42 -0700296bool MetricsLibrary::SendSparseToUMA(const std::string& name, int sample) {
297 // Format the message.
298 char message[kBufferSize];
299 int32_t message_length =
300 FormatChromeMessage(kBufferSize, message, "sparsehistogram%c%s %d",
301 '\0', name.c_str(), sample);
302 if (message_length < 0)
303 return false;
304
305 // Send the message.
306 return SendMessageToChrome(message_length, message);
307}
308
Darin Petkoved824852011-01-06 10:51:47 -0800309bool MetricsLibrary::SendUserActionToUMA(const std::string& action) {
310 // Format the message.
311 char message[kBufferSize];
312 int32_t message_length =
313 FormatChromeMessage(kBufferSize, message,
314 "useraction%c%s", '\0', action.c_str());
Darin Petkov5b7dce12010-04-21 15:45:10 -0700315 if (message_length < 0)
316 return false;
317
318 // Send the message.
319 return SendMessageToChrome(message_length, message);
320}
Ken Mixterbe2e13b2011-01-22 06:15:56 -0800321
322bool MetricsLibrary::SendCrashToUMA(const char *crash_kind) {
323 // Format the message.
324 char message[kBufferSize];
325 int32_t message_length =
326 FormatChromeMessage(kBufferSize, message,
327 "crash%c%s", '\0', crash_kind);
328
329 if (message_length < 0)
330 return false;
331
332 // Send the message.
333 return SendMessageToChrome(message_length, message);
334}
Ken Mixterb2f17092011-07-22 14:59:51 -0700335
336void MetricsLibrary::SetPolicyProvider(policy::PolicyProvider* provider) {
337 policy_provider_.reset(provider);
338}
Luigi Semenzato32684222013-03-13 10:53:55 -0700339
340bool MetricsLibrary::SendCrosEventToUMA(const std::string& event) {
Chih-Chung Chang6844c062013-04-01 14:27:39 +0800341 for (size_t i = 0; i < ARRAY_SIZE(kCrosEventNames); i++) {
342 if (strcmp(event.c_str(), kCrosEventNames[i]) == 0) {
343 return SendEnumToUMA(kCrosEventHistogramName, i, kCrosEventHistogramMax);
344 }
Luigi Semenzato32684222013-03-13 10:53:55 -0700345 }
Chih-Chung Chang6844c062013-04-01 14:27:39 +0800346 return false;
Luigi Semenzato32684222013-03-13 10:53:55 -0700347}