blob: e5aaae6db851ffdbe7057e121832ce7c5292e9f9 [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
40};
41
Ken Mixter4c5daa42010-08-26 18:35:06 -070042time_t MetricsLibrary::cached_enabled_time_ = 0;
43bool MetricsLibrary::cached_enabled_ = false;
44
David James3b3add52010-06-04 15:01:19 -070045using std::string;
Darin Petkov65b01462010-04-14 13:32:20 -070046
47// TODO(sosa@chromium.org) - use Chromium logger instead of stderr
Darin Petkov11b8eb32010-05-18 11:00:59 -070048static void PrintError(const char* message, const char* file,
Darin Petkov4fcb2ac2010-04-15 16:40:23 -070049 int code) {
David James3b3add52010-06-04 15:01:19 -070050 static const char kProgramName[] = "libmetrics";
Darin Petkov65b01462010-04-14 13:32:20 -070051 if (code == 0) {
52 fprintf(stderr, "%s: %s\n", kProgramName, message);
53 } else if (file == NULL) {
54 fprintf(stderr, "%s: ", kProgramName);
55 perror(message);
56 } else {
57 fprintf(stderr, "%s: %s: ", kProgramName, file);
58 perror(message);
59 }
60}
61
Darin Petkov8d3305e2011-02-25 14:19:30 -080062// Copied from libbase to avoid pulling in all of libbase just for libmetrics.
63static int WriteFileDescriptor(const int fd, const char* data, int size) {
64 // Allow for partial writes.
65 ssize_t bytes_written_total = 0;
66 for (ssize_t bytes_written_partial = 0; bytes_written_total < size;
67 bytes_written_total += bytes_written_partial) {
68 bytes_written_partial =
69 HANDLE_EINTR(write(fd, data + bytes_written_total,
70 size - bytes_written_total));
71 if (bytes_written_partial < 0)
72 return -1;
73 }
74
75 return bytes_written_total;
76}
77
Darin Petkov11b8eb32010-05-18 11:00:59 -070078MetricsLibrary::MetricsLibrary()
Ken Mixter4c5daa42010-08-26 18:35:06 -070079 : uma_events_file_(NULL),
Ken Mixterb2f17092011-07-22 14:59:51 -070080 consent_file_(kConsentFile),
81 policy_provider_(NULL) {}
Ken Mixter4c5daa42010-08-26 18:35:06 -070082
Ken Mixtereafbbdf2010-10-01 15:38:42 -070083// We take buffer and buffer_size as parameters in order to simplify testing
84// of various alignments of the |device_name| with |buffer_size|.
85bool MetricsLibrary::IsDeviceMounted(const char* device_name,
86 const char* mounts_file,
87 char* buffer,
88 int buffer_size,
89 bool* result) {
90 if (buffer == NULL || buffer_size < 1)
91 return false;
92 int mounts_fd = open(mounts_file, O_RDONLY);
93 if (mounts_fd < 0)
94 return false;
95 // match_offset describes:
96 // -1 -- not beginning of line
97 // 0..strlen(device_name)-1 -- this offset in device_name is next to match
98 // strlen(device_name) -- matched full name, just need a space.
99 int match_offset = 0;
100 bool match = false;
101 while (!match) {
102 int read_size = read(mounts_fd, buffer, buffer_size);
103 if (read_size <= 0) {
104 if (errno == -EINTR)
105 continue;
106 break;
107 }
108 for (int i = 0; i < read_size; ++i) {
109 if (buffer[i] == '\n') {
110 match_offset = 0;
111 continue;
112 }
113 if (match_offset < 0) {
114 continue;
115 }
116 if (device_name[match_offset] == '\0') {
117 if (buffer[i] == ' ') {
118 match = true;
119 break;
120 }
121 match_offset = -1;
122 continue;
123 }
124
125 if (buffer[i] == device_name[match_offset]) {
126 ++match_offset;
127 } else {
128 match_offset = -1;
129 }
130 }
131 }
132 close(mounts_fd);
133 *result = match;
134 return true;
135}
136
137bool MetricsLibrary::IsGuestMode() {
138 char buffer[256];
139 bool result = false;
140 if (!IsDeviceMounted("guestfs",
141 "/proc/mounts",
142 buffer,
143 sizeof(buffer),
144 &result)) {
145 return false;
146 }
Arkaitz Ruiz Alvarez9f1a7742011-05-26 12:22:22 -0700147 return result && (access("/var/run/state/logged-in", F_OK) == 0);
Ken Mixtereafbbdf2010-10-01 15:38:42 -0700148}
149
Ken Mixter4c5daa42010-08-26 18:35:06 -0700150bool MetricsLibrary::AreMetricsEnabled() {
Julian Pastarmov70b7abd2011-08-02 16:10:49 +0200151 static struct stat stat_buffer;
Ken Mixter4c5daa42010-08-26 18:35:06 -0700152 time_t this_check_time = time(NULL);
Ken Mixter4c5daa42010-08-26 18:35:06 -0700153 if (this_check_time != cached_enabled_time_) {
154 cached_enabled_time_ = this_check_time;
Julian Pastarmov70b7abd2011-08-02 16:10:49 +0200155
156 if (!policy_provider_.get())
157 policy_provider_.reset(new policy::PolicyProvider());
Julian Pastarmovd605a002013-02-04 17:58:14 +0100158 policy_provider_->Reload();
Julian Pastarmov70b7abd2011-08-02 16:10:49 +0200159 // We initialize with the default value which is false and will be preserved
160 // if the policy is not set.
161 bool enabled = false;
162 bool has_policy = false;
163 if (policy_provider_->device_policy_is_loaded()) {
164 has_policy =
165 policy_provider_->GetDevicePolicy().GetMetricsEnabled(&enabled);
166 }
167 // If policy couldn't be loaded or the metrics policy is not set we should
168 // still respect the consent file if it is present for migration purposes.
169 // TODO(pastarmovj)
170 if (!has_policy) {
171 enabled = stat(consent_file_, &stat_buffer) >= 0;
172 }
173
Ken Mixterb2f17092011-07-22 14:59:51 -0700174 if (enabled && !IsGuestMode())
Ken Mixtereafbbdf2010-10-01 15:38:42 -0700175 cached_enabled_ = true;
176 else
177 cached_enabled_ = false;
Ken Mixter4c5daa42010-08-26 18:35:06 -0700178 }
179 return cached_enabled_;
180}
Darin Petkov11b8eb32010-05-18 11:00:59 -0700181
182bool MetricsLibrary::SendMessageToChrome(int32_t length, const char* message) {
Ken Mixter4c5daa42010-08-26 18:35:06 -0700183
Darin Petkov8842c8c2011-02-24 12:48:30 -0800184 int chrome_fd = HANDLE_EINTR(open(uma_events_file_,
185 O_WRONLY | O_APPEND | O_CREAT,
186 READ_WRITE_ALL_FILE_FLAGS));
Darin Petkov4fcb2ac2010-04-15 16:40:23 -0700187 // If we failed to open it, return.
Darin Petkov65b01462010-04-14 13:32:20 -0700188 if (chrome_fd < 0) {
Darin Petkov11b8eb32010-05-18 11:00:59 -0700189 PrintError("open", uma_events_file_, errno);
Darin Petkov4fcb2ac2010-04-15 16:40:23 -0700190 return false;
Darin Petkov65b01462010-04-14 13:32:20 -0700191 }
192
Darin Petkov4fcb2ac2010-04-15 16:40:23 -0700193 // Need to chmod because open flags are anded with umask. Ignore the
194 // exit code -- a chronos process may fail chmoding because the file
195 // has been created by a root process but that should be OK.
196 fchmod(chrome_fd, READ_WRITE_ALL_FILE_FLAGS);
Darin Petkov65b01462010-04-14 13:32:20 -0700197
Darin Petkov4fcb2ac2010-04-15 16:40:23 -0700198 // Grab an exclusive lock to protect Chrome from truncating
199 // underneath us. Keep the file locked as briefly as possible.
Darin Petkov8842c8c2011-02-24 12:48:30 -0800200 if (HANDLE_EINTR(flock(chrome_fd, LOCK_EX)) < 0) {
Darin Petkov11b8eb32010-05-18 11:00:59 -0700201 PrintError("flock", uma_events_file_, errno);
Darin Petkov8842c8c2011-02-24 12:48:30 -0800202 HANDLE_EINTR(close(chrome_fd));
Darin Petkov4fcb2ac2010-04-15 16:40:23 -0700203 return false;
Darin Petkov65b01462010-04-14 13:32:20 -0700204 }
205
Darin Petkov4fcb2ac2010-04-15 16:40:23 -0700206 bool success = true;
Darin Petkov8d3305e2011-02-25 14:19:30 -0800207 if (WriteFileDescriptor(chrome_fd, message, length) != length) {
Darin Petkov11b8eb32010-05-18 11:00:59 -0700208 PrintError("write", uma_events_file_, errno);
Darin Petkov4fcb2ac2010-04-15 16:40:23 -0700209 success = false;
210 }
Darin Petkov65b01462010-04-14 13:32:20 -0700211
Darin Petkov8842c8c2011-02-24 12:48:30 -0800212 // Close the file and release the lock.
213 HANDLE_EINTR(close(chrome_fd));
Darin Petkov4fcb2ac2010-04-15 16:40:23 -0700214 return success;
215}
216
Darin Petkov11b8eb32010-05-18 11:00:59 -0700217int32_t MetricsLibrary::FormatChromeMessage(int32_t buffer_size, char* buffer,
218 const char* format, ...) {
Darin Petkov4fcb2ac2010-04-15 16:40:23 -0700219 int32_t message_length;
220 size_t len_size = sizeof(message_length);
221
222 // Format the non-LENGTH contents in the buffer by leaving space for
223 // LENGTH at the start of the buffer.
224 va_list args;
225 va_start(args, format);
226 message_length = vsnprintf(&buffer[len_size], buffer_size - len_size,
227 format, args);
228 va_end(args);
229
230 if (message_length < 0) {
231 PrintError("chrome message format error", NULL, 0);
232 return -1;
233 }
234
235 // +1 to account for the trailing \0.
236 message_length += len_size + 1;
237 if (message_length > buffer_size) {
238 PrintError("chrome message too long", NULL, 0);
239 return -1;
240 }
241
242 // Prepend LENGTH to the message.
243 memcpy(buffer, &message_length, len_size);
244 return message_length;
245}
246
Darin Petkovfc91b422010-05-12 13:05:45 -0700247void MetricsLibrary::Init() {
Darin Petkov11b8eb32010-05-18 11:00:59 -0700248 uma_events_file_ = kUMAEventsPath;
Darin Petkovfc91b422010-05-12 13:05:45 -0700249}
250
Darin Petkovc2526a12010-04-21 14:24:04 -0700251bool MetricsLibrary::SendToAutotest(const string& name, int value) {
David James3b3add52010-06-04 15:01:19 -0700252 FILE* autotest_file = fopen(kAutotestPath, "a+");
Darin Petkov4fcb2ac2010-04-15 16:40:23 -0700253 if (autotest_file == NULL) {
254 PrintError("fopen", kAutotestPath, errno);
255 return false;
256 }
257
258 fprintf(autotest_file, "%s=%d\n", name.c_str(), value);
259 fclose(autotest_file);
260 return true;
261}
262
Darin Petkov21cd2c52010-05-12 15:26:16 -0700263bool MetricsLibrary::SendToUMA(const string& name, int sample,
264 int min, int max, int nbuckets) {
Darin Petkov4fcb2ac2010-04-15 16:40:23 -0700265 // Format the message.
266 char message[kBufferSize];
267 int32_t message_length =
268 FormatChromeMessage(kBufferSize, message,
Darin Petkovc2526a12010-04-21 14:24:04 -0700269 "histogram%c%s %d %d %d %d", '\0',
270 name.c_str(), sample, min, max, nbuckets);
Darin Petkov4fcb2ac2010-04-15 16:40:23 -0700271 if (message_length < 0)
272 return false;
273
274 // Send the message.
275 return SendMessageToChrome(message_length, message);
Darin Petkov65b01462010-04-14 13:32:20 -0700276}
Darin Petkov5b7dce12010-04-21 15:45:10 -0700277
Darin Petkov21cd2c52010-05-12 15:26:16 -0700278bool MetricsLibrary::SendEnumToUMA(const std::string& name, int sample,
279 int max) {
Darin Petkov5b7dce12010-04-21 15:45:10 -0700280 // Format the message.
281 char message[kBufferSize];
282 int32_t message_length =
283 FormatChromeMessage(kBufferSize, message,
284 "linearhistogram%c%s %d %d", '\0',
285 name.c_str(), sample, max);
Darin Petkoved824852011-01-06 10:51:47 -0800286 if (message_length < 0)
287 return false;
Darin Petkov5b7dce12010-04-21 15:45:10 -0700288
Darin Petkoved824852011-01-06 10:51:47 -0800289 // Send the message.
290 return SendMessageToChrome(message_length, message);
291}
292
Luigi Semenzatoa7ebeb32013-03-19 15:02:42 -0700293bool MetricsLibrary::SendSparseToUMA(const std::string& name, int sample) {
294 // Format the message.
295 char message[kBufferSize];
296 int32_t message_length =
297 FormatChromeMessage(kBufferSize, message, "sparsehistogram%c%s %d",
298 '\0', name.c_str(), sample);
299 if (message_length < 0)
300 return false;
301
302 // Send the message.
303 return SendMessageToChrome(message_length, message);
304}
305
Darin Petkoved824852011-01-06 10:51:47 -0800306bool MetricsLibrary::SendUserActionToUMA(const std::string& action) {
307 // Format the message.
308 char message[kBufferSize];
309 int32_t message_length =
310 FormatChromeMessage(kBufferSize, message,
311 "useraction%c%s", '\0', action.c_str());
Darin Petkov5b7dce12010-04-21 15:45:10 -0700312 if (message_length < 0)
313 return false;
314
315 // Send the message.
316 return SendMessageToChrome(message_length, message);
317}
Ken Mixterbe2e13b2011-01-22 06:15:56 -0800318
319bool MetricsLibrary::SendCrashToUMA(const char *crash_kind) {
320 // Format the message.
321 char message[kBufferSize];
322 int32_t message_length =
323 FormatChromeMessage(kBufferSize, message,
324 "crash%c%s", '\0', crash_kind);
325
326 if (message_length < 0)
327 return false;
328
329 // Send the message.
330 return SendMessageToChrome(message_length, message);
331}
Ken Mixterb2f17092011-07-22 14:59:51 -0700332
333void MetricsLibrary::SetPolicyProvider(policy::PolicyProvider* provider) {
334 policy_provider_.reset(provider);
335}
Luigi Semenzato32684222013-03-13 10:53:55 -0700336
337bool MetricsLibrary::SendCrosEventToUMA(const std::string& event) {
Chih-Chung Chang6844c062013-04-01 14:27:39 +0800338 for (size_t i = 0; i < ARRAY_SIZE(kCrosEventNames); i++) {
339 if (strcmp(event.c_str(), kCrosEventNames[i]) == 0) {
340 return SendEnumToUMA(kCrosEventHistogramName, i, kCrosEventHistogramMax);
341 }
Luigi Semenzato32684222013-03-13 10:53:55 -0700342 }
Chih-Chung Chang6844c062013-04-01 14:27:39 +0800343 return false;
Luigi Semenzato32684222013-03-13 10:53:55 -0700344}