blob: ba8e9009a90a4ae5373dfdc704c8150a52a28840 [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
Chih-Chung Chang6844c062013-04-01 14:27:39 +080046};
47
Ken Mixter4c5daa42010-08-26 18:35:06 -070048time_t MetricsLibrary::cached_enabled_time_ = 0;
49bool MetricsLibrary::cached_enabled_ = false;
50
David James3b3add52010-06-04 15:01:19 -070051using std::string;
Darin Petkov65b01462010-04-14 13:32:20 -070052
53// TODO(sosa@chromium.org) - use Chromium logger instead of stderr
Darin Petkov11b8eb32010-05-18 11:00:59 -070054static void PrintError(const char* message, const char* file,
Darin Petkov4fcb2ac2010-04-15 16:40:23 -070055 int code) {
David James3b3add52010-06-04 15:01:19 -070056 static const char kProgramName[] = "libmetrics";
Darin Petkov65b01462010-04-14 13:32:20 -070057 if (code == 0) {
58 fprintf(stderr, "%s: %s\n", kProgramName, message);
59 } else if (file == NULL) {
60 fprintf(stderr, "%s: ", kProgramName);
61 perror(message);
62 } else {
63 fprintf(stderr, "%s: %s: ", kProgramName, file);
64 perror(message);
65 }
66}
67
Darin Petkov8d3305e2011-02-25 14:19:30 -080068// Copied from libbase to avoid pulling in all of libbase just for libmetrics.
69static int WriteFileDescriptor(const int fd, const char* data, int size) {
70 // Allow for partial writes.
71 ssize_t bytes_written_total = 0;
72 for (ssize_t bytes_written_partial = 0; bytes_written_total < size;
73 bytes_written_total += bytes_written_partial) {
74 bytes_written_partial =
75 HANDLE_EINTR(write(fd, data + bytes_written_total,
76 size - bytes_written_total));
77 if (bytes_written_partial < 0)
78 return -1;
79 }
80
81 return bytes_written_total;
82}
83
Darin Petkov11b8eb32010-05-18 11:00:59 -070084MetricsLibrary::MetricsLibrary()
Ken Mixter4c5daa42010-08-26 18:35:06 -070085 : uma_events_file_(NULL),
Ken Mixterb2f17092011-07-22 14:59:51 -070086 consent_file_(kConsentFile),
87 policy_provider_(NULL) {}
Ken Mixter4c5daa42010-08-26 18:35:06 -070088
Ken Mixtereafbbdf2010-10-01 15:38:42 -070089// We take buffer and buffer_size as parameters in order to simplify testing
90// of various alignments of the |device_name| with |buffer_size|.
91bool MetricsLibrary::IsDeviceMounted(const char* device_name,
92 const char* mounts_file,
93 char* buffer,
94 int buffer_size,
95 bool* result) {
96 if (buffer == NULL || buffer_size < 1)
97 return false;
98 int mounts_fd = open(mounts_file, O_RDONLY);
99 if (mounts_fd < 0)
100 return false;
101 // match_offset describes:
102 // -1 -- not beginning of line
103 // 0..strlen(device_name)-1 -- this offset in device_name is next to match
104 // strlen(device_name) -- matched full name, just need a space.
105 int match_offset = 0;
106 bool match = false;
107 while (!match) {
108 int read_size = read(mounts_fd, buffer, buffer_size);
109 if (read_size <= 0) {
110 if (errno == -EINTR)
111 continue;
112 break;
113 }
114 for (int i = 0; i < read_size; ++i) {
115 if (buffer[i] == '\n') {
116 match_offset = 0;
117 continue;
118 }
119 if (match_offset < 0) {
120 continue;
121 }
122 if (device_name[match_offset] == '\0') {
123 if (buffer[i] == ' ') {
124 match = true;
125 break;
126 }
127 match_offset = -1;
128 continue;
129 }
130
131 if (buffer[i] == device_name[match_offset]) {
132 ++match_offset;
133 } else {
134 match_offset = -1;
135 }
136 }
137 }
138 close(mounts_fd);
139 *result = match;
140 return true;
141}
142
143bool MetricsLibrary::IsGuestMode() {
144 char buffer[256];
145 bool result = false;
146 if (!IsDeviceMounted("guestfs",
147 "/proc/mounts",
148 buffer,
149 sizeof(buffer),
150 &result)) {
151 return false;
152 }
Arkaitz Ruiz Alvarez9f1a7742011-05-26 12:22:22 -0700153 return result && (access("/var/run/state/logged-in", F_OK) == 0);
Ken Mixtereafbbdf2010-10-01 15:38:42 -0700154}
155
Ken Mixter4c5daa42010-08-26 18:35:06 -0700156bool MetricsLibrary::AreMetricsEnabled() {
Julian Pastarmov70b7abd2011-08-02 16:10:49 +0200157 static struct stat stat_buffer;
Ken Mixter4c5daa42010-08-26 18:35:06 -0700158 time_t this_check_time = time(NULL);
Ken Mixter4c5daa42010-08-26 18:35:06 -0700159 if (this_check_time != cached_enabled_time_) {
160 cached_enabled_time_ = this_check_time;
Julian Pastarmov70b7abd2011-08-02 16:10:49 +0200161
162 if (!policy_provider_.get())
163 policy_provider_.reset(new policy::PolicyProvider());
Julian Pastarmovd605a002013-02-04 17:58:14 +0100164 policy_provider_->Reload();
Julian Pastarmov70b7abd2011-08-02 16:10:49 +0200165 // We initialize with the default value which is false and will be preserved
166 // if the policy is not set.
167 bool enabled = false;
168 bool has_policy = false;
169 if (policy_provider_->device_policy_is_loaded()) {
170 has_policy =
171 policy_provider_->GetDevicePolicy().GetMetricsEnabled(&enabled);
172 }
173 // If policy couldn't be loaded or the metrics policy is not set we should
174 // still respect the consent file if it is present for migration purposes.
175 // TODO(pastarmovj)
176 if (!has_policy) {
177 enabled = stat(consent_file_, &stat_buffer) >= 0;
178 }
179
Ken Mixterb2f17092011-07-22 14:59:51 -0700180 if (enabled && !IsGuestMode())
Ken Mixtereafbbdf2010-10-01 15:38:42 -0700181 cached_enabled_ = true;
182 else
183 cached_enabled_ = false;
Ken Mixter4c5daa42010-08-26 18:35:06 -0700184 }
185 return cached_enabled_;
186}
Darin Petkov11b8eb32010-05-18 11:00:59 -0700187
188bool MetricsLibrary::SendMessageToChrome(int32_t length, const char* message) {
Ken Mixter4c5daa42010-08-26 18:35:06 -0700189
Darin Petkov8842c8c2011-02-24 12:48:30 -0800190 int chrome_fd = HANDLE_EINTR(open(uma_events_file_,
191 O_WRONLY | O_APPEND | O_CREAT,
192 READ_WRITE_ALL_FILE_FLAGS));
Darin Petkov4fcb2ac2010-04-15 16:40:23 -0700193 // If we failed to open it, return.
Darin Petkov65b01462010-04-14 13:32:20 -0700194 if (chrome_fd < 0) {
Darin Petkov11b8eb32010-05-18 11:00:59 -0700195 PrintError("open", uma_events_file_, errno);
Darin Petkov4fcb2ac2010-04-15 16:40:23 -0700196 return false;
Darin Petkov65b01462010-04-14 13:32:20 -0700197 }
198
Darin Petkov4fcb2ac2010-04-15 16:40:23 -0700199 // Need to chmod because open flags are anded with umask. Ignore the
200 // exit code -- a chronos process may fail chmoding because the file
201 // has been created by a root process but that should be OK.
202 fchmod(chrome_fd, READ_WRITE_ALL_FILE_FLAGS);
Darin Petkov65b01462010-04-14 13:32:20 -0700203
Darin Petkov4fcb2ac2010-04-15 16:40:23 -0700204 // Grab an exclusive lock to protect Chrome from truncating
205 // underneath us. Keep the file locked as briefly as possible.
Darin Petkov8842c8c2011-02-24 12:48:30 -0800206 if (HANDLE_EINTR(flock(chrome_fd, LOCK_EX)) < 0) {
Darin Petkov11b8eb32010-05-18 11:00:59 -0700207 PrintError("flock", uma_events_file_, errno);
Darin Petkov8842c8c2011-02-24 12:48:30 -0800208 HANDLE_EINTR(close(chrome_fd));
Darin Petkov4fcb2ac2010-04-15 16:40:23 -0700209 return false;
Darin Petkov65b01462010-04-14 13:32:20 -0700210 }
211
Darin Petkov4fcb2ac2010-04-15 16:40:23 -0700212 bool success = true;
Darin Petkov8d3305e2011-02-25 14:19:30 -0800213 if (WriteFileDescriptor(chrome_fd, message, length) != length) {
Darin Petkov11b8eb32010-05-18 11:00:59 -0700214 PrintError("write", uma_events_file_, errno);
Darin Petkov4fcb2ac2010-04-15 16:40:23 -0700215 success = false;
216 }
Darin Petkov65b01462010-04-14 13:32:20 -0700217
Darin Petkov8842c8c2011-02-24 12:48:30 -0800218 // Close the file and release the lock.
219 HANDLE_EINTR(close(chrome_fd));
Darin Petkov4fcb2ac2010-04-15 16:40:23 -0700220 return success;
221}
222
Darin Petkov11b8eb32010-05-18 11:00:59 -0700223int32_t MetricsLibrary::FormatChromeMessage(int32_t buffer_size, char* buffer,
224 const char* format, ...) {
Darin Petkov4fcb2ac2010-04-15 16:40:23 -0700225 int32_t message_length;
226 size_t len_size = sizeof(message_length);
227
228 // Format the non-LENGTH contents in the buffer by leaving space for
229 // LENGTH at the start of the buffer.
230 va_list args;
231 va_start(args, format);
232 message_length = vsnprintf(&buffer[len_size], buffer_size - len_size,
233 format, args);
234 va_end(args);
235
236 if (message_length < 0) {
237 PrintError("chrome message format error", NULL, 0);
238 return -1;
239 }
240
241 // +1 to account for the trailing \0.
242 message_length += len_size + 1;
243 if (message_length > buffer_size) {
244 PrintError("chrome message too long", NULL, 0);
245 return -1;
246 }
247
248 // Prepend LENGTH to the message.
249 memcpy(buffer, &message_length, len_size);
250 return message_length;
251}
252
Darin Petkovfc91b422010-05-12 13:05:45 -0700253void MetricsLibrary::Init() {
Darin Petkov11b8eb32010-05-18 11:00:59 -0700254 uma_events_file_ = kUMAEventsPath;
Darin Petkovfc91b422010-05-12 13:05:45 -0700255}
256
Darin Petkovc2526a12010-04-21 14:24:04 -0700257bool MetricsLibrary::SendToAutotest(const string& name, int value) {
David James3b3add52010-06-04 15:01:19 -0700258 FILE* autotest_file = fopen(kAutotestPath, "a+");
Darin Petkov4fcb2ac2010-04-15 16:40:23 -0700259 if (autotest_file == NULL) {
260 PrintError("fopen", kAutotestPath, errno);
261 return false;
262 }
263
264 fprintf(autotest_file, "%s=%d\n", name.c_str(), value);
265 fclose(autotest_file);
266 return true;
267}
268
Darin Petkov21cd2c52010-05-12 15:26:16 -0700269bool MetricsLibrary::SendToUMA(const string& name, int sample,
270 int min, int max, int nbuckets) {
Darin Petkov4fcb2ac2010-04-15 16:40:23 -0700271 // Format the message.
272 char message[kBufferSize];
273 int32_t message_length =
274 FormatChromeMessage(kBufferSize, message,
Darin Petkovc2526a12010-04-21 14:24:04 -0700275 "histogram%c%s %d %d %d %d", '\0',
276 name.c_str(), sample, min, max, nbuckets);
Darin Petkov4fcb2ac2010-04-15 16:40:23 -0700277 if (message_length < 0)
278 return false;
279
280 // Send the message.
281 return SendMessageToChrome(message_length, message);
Darin Petkov65b01462010-04-14 13:32:20 -0700282}
Darin Petkov5b7dce12010-04-21 15:45:10 -0700283
Darin Petkov21cd2c52010-05-12 15:26:16 -0700284bool MetricsLibrary::SendEnumToUMA(const std::string& name, int sample,
285 int max) {
Darin Petkov5b7dce12010-04-21 15:45:10 -0700286 // Format the message.
287 char message[kBufferSize];
288 int32_t message_length =
289 FormatChromeMessage(kBufferSize, message,
290 "linearhistogram%c%s %d %d", '\0',
291 name.c_str(), sample, max);
Darin Petkoved824852011-01-06 10:51:47 -0800292 if (message_length < 0)
293 return false;
Darin Petkov5b7dce12010-04-21 15:45:10 -0700294
Darin Petkoved824852011-01-06 10:51:47 -0800295 // Send the message.
296 return SendMessageToChrome(message_length, message);
297}
298
Luigi Semenzatoa7ebeb32013-03-19 15:02:42 -0700299bool MetricsLibrary::SendSparseToUMA(const std::string& name, int sample) {
300 // Format the message.
301 char message[kBufferSize];
302 int32_t message_length =
303 FormatChromeMessage(kBufferSize, message, "sparsehistogram%c%s %d",
304 '\0', name.c_str(), sample);
305 if (message_length < 0)
306 return false;
307
308 // Send the message.
309 return SendMessageToChrome(message_length, message);
310}
311
Darin Petkoved824852011-01-06 10:51:47 -0800312bool MetricsLibrary::SendUserActionToUMA(const std::string& action) {
313 // Format the message.
314 char message[kBufferSize];
315 int32_t message_length =
316 FormatChromeMessage(kBufferSize, message,
317 "useraction%c%s", '\0', action.c_str());
Darin Petkov5b7dce12010-04-21 15:45:10 -0700318 if (message_length < 0)
319 return false;
320
321 // Send the message.
322 return SendMessageToChrome(message_length, message);
323}
Ken Mixterbe2e13b2011-01-22 06:15:56 -0800324
325bool MetricsLibrary::SendCrashToUMA(const char *crash_kind) {
326 // Format the message.
327 char message[kBufferSize];
328 int32_t message_length =
329 FormatChromeMessage(kBufferSize, message,
330 "crash%c%s", '\0', crash_kind);
331
332 if (message_length < 0)
333 return false;
334
335 // Send the message.
336 return SendMessageToChrome(message_length, message);
337}
Ken Mixterb2f17092011-07-22 14:59:51 -0700338
339void MetricsLibrary::SetPolicyProvider(policy::PolicyProvider* provider) {
340 policy_provider_.reset(provider);
341}
Luigi Semenzato32684222013-03-13 10:53:55 -0700342
343bool MetricsLibrary::SendCrosEventToUMA(const std::string& event) {
Chih-Chung Chang6844c062013-04-01 14:27:39 +0800344 for (size_t i = 0; i < ARRAY_SIZE(kCrosEventNames); i++) {
345 if (strcmp(event.c_str(), kCrosEventNames[i]) == 0) {
346 return SendEnumToUMA(kCrosEventHistogramName, i, kCrosEventHistogramMax);
347 }
Luigi Semenzato32684222013-03-13 10:53:55 -0700348 }
Chih-Chung Chang6844c062013-04-01 14:27:39 +0800349 return false;
Luigi Semenzato32684222013-03-13 10:53:55 -0700350}