blob: 707ea6874ca425548f86aeb4e8a36d49e8063aa1 [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
Darin Petkov8d3305e2011-02-25 14:19:30 -080015#include "base/eintr_wrapper.h" // HANDLE_EINTR macro, no libbase required.
Ken Mixterb2f17092011-07-22 14:59:51 -070016#include "policy/device_policy.h"
Darin Petkov8842c8c2011-02-24 12:48:30 -080017
Darin Petkov65b01462010-04-14 13:32:20 -070018#define READ_WRITE_ALL_FILE_FLAGS \
19 (S_IRUSR | S_IWUSR | S_IRGRP | S_IWGRP | S_IROTH | S_IWOTH)
20
Ken Mixter4c5daa42010-08-26 18:35:06 -070021static const char kAutotestPath[] = "/var/log/metrics/autotest-events";
22static const char kUMAEventsPath[] = "/var/log/metrics/uma-events";
23static const char kConsentFile[] = "/home/chronos/Consent To Send Stats";
Darin Petkov4fcb2ac2010-04-15 16:40:23 -070024static const int32_t kBufferSize = 1024;
Darin Petkov65b01462010-04-14 13:32:20 -070025
Ken Mixter4c5daa42010-08-26 18:35:06 -070026time_t MetricsLibrary::cached_enabled_time_ = 0;
27bool MetricsLibrary::cached_enabled_ = false;
28
David James3b3add52010-06-04 15:01:19 -070029using std::string;
Darin Petkov65b01462010-04-14 13:32:20 -070030
31// TODO(sosa@chromium.org) - use Chromium logger instead of stderr
Darin Petkov11b8eb32010-05-18 11:00:59 -070032static void PrintError(const char* message, const char* file,
Darin Petkov4fcb2ac2010-04-15 16:40:23 -070033 int code) {
David James3b3add52010-06-04 15:01:19 -070034 static const char kProgramName[] = "libmetrics";
Darin Petkov65b01462010-04-14 13:32:20 -070035 if (code == 0) {
36 fprintf(stderr, "%s: %s\n", kProgramName, message);
37 } else if (file == NULL) {
38 fprintf(stderr, "%s: ", kProgramName);
39 perror(message);
40 } else {
41 fprintf(stderr, "%s: %s: ", kProgramName, file);
42 perror(message);
43 }
44}
45
Darin Petkov8d3305e2011-02-25 14:19:30 -080046// Copied from libbase to avoid pulling in all of libbase just for libmetrics.
47static int WriteFileDescriptor(const int fd, const char* data, int size) {
48 // Allow for partial writes.
49 ssize_t bytes_written_total = 0;
50 for (ssize_t bytes_written_partial = 0; bytes_written_total < size;
51 bytes_written_total += bytes_written_partial) {
52 bytes_written_partial =
53 HANDLE_EINTR(write(fd, data + bytes_written_total,
54 size - bytes_written_total));
55 if (bytes_written_partial < 0)
56 return -1;
57 }
58
59 return bytes_written_total;
60}
61
Darin Petkov11b8eb32010-05-18 11:00:59 -070062MetricsLibrary::MetricsLibrary()
Ken Mixter4c5daa42010-08-26 18:35:06 -070063 : uma_events_file_(NULL),
Ken Mixterb2f17092011-07-22 14:59:51 -070064 consent_file_(kConsentFile),
65 policy_provider_(NULL) {}
Ken Mixter4c5daa42010-08-26 18:35:06 -070066
Ken Mixtereafbbdf2010-10-01 15:38:42 -070067// We take buffer and buffer_size as parameters in order to simplify testing
68// of various alignments of the |device_name| with |buffer_size|.
69bool MetricsLibrary::IsDeviceMounted(const char* device_name,
70 const char* mounts_file,
71 char* buffer,
72 int buffer_size,
73 bool* result) {
74 if (buffer == NULL || buffer_size < 1)
75 return false;
76 int mounts_fd = open(mounts_file, O_RDONLY);
77 if (mounts_fd < 0)
78 return false;
79 // match_offset describes:
80 // -1 -- not beginning of line
81 // 0..strlen(device_name)-1 -- this offset in device_name is next to match
82 // strlen(device_name) -- matched full name, just need a space.
83 int match_offset = 0;
84 bool match = false;
85 while (!match) {
86 int read_size = read(mounts_fd, buffer, buffer_size);
87 if (read_size <= 0) {
88 if (errno == -EINTR)
89 continue;
90 break;
91 }
92 for (int i = 0; i < read_size; ++i) {
93 if (buffer[i] == '\n') {
94 match_offset = 0;
95 continue;
96 }
97 if (match_offset < 0) {
98 continue;
99 }
100 if (device_name[match_offset] == '\0') {
101 if (buffer[i] == ' ') {
102 match = true;
103 break;
104 }
105 match_offset = -1;
106 continue;
107 }
108
109 if (buffer[i] == device_name[match_offset]) {
110 ++match_offset;
111 } else {
112 match_offset = -1;
113 }
114 }
115 }
116 close(mounts_fd);
117 *result = match;
118 return true;
119}
120
121bool MetricsLibrary::IsGuestMode() {
122 char buffer[256];
123 bool result = false;
124 if (!IsDeviceMounted("guestfs",
125 "/proc/mounts",
126 buffer,
127 sizeof(buffer),
128 &result)) {
129 return false;
130 }
Arkaitz Ruiz Alvarez9f1a7742011-05-26 12:22:22 -0700131 return result && (access("/var/run/state/logged-in", F_OK) == 0);
Ken Mixtereafbbdf2010-10-01 15:38:42 -0700132}
133
Ken Mixter4c5daa42010-08-26 18:35:06 -0700134bool MetricsLibrary::AreMetricsEnabled() {
Julian Pastarmov70b7abd2011-08-02 16:10:49 +0200135 static struct stat stat_buffer;
Ken Mixter4c5daa42010-08-26 18:35:06 -0700136 time_t this_check_time = time(NULL);
Ken Mixter4c5daa42010-08-26 18:35:06 -0700137 if (this_check_time != cached_enabled_time_) {
138 cached_enabled_time_ = this_check_time;
Julian Pastarmov70b7abd2011-08-02 16:10:49 +0200139
140 if (!policy_provider_.get())
141 policy_provider_.reset(new policy::PolicyProvider());
142 else
143 policy_provider_->Reload();
144 // We initialize with the default value which is false and will be preserved
145 // if the policy is not set.
146 bool enabled = false;
147 bool has_policy = false;
148 if (policy_provider_->device_policy_is_loaded()) {
149 has_policy =
150 policy_provider_->GetDevicePolicy().GetMetricsEnabled(&enabled);
151 }
152 // If policy couldn't be loaded or the metrics policy is not set we should
153 // still respect the consent file if it is present for migration purposes.
154 // TODO(pastarmovj)
155 if (!has_policy) {
156 enabled = stat(consent_file_, &stat_buffer) >= 0;
157 }
158
Ken Mixterb2f17092011-07-22 14:59:51 -0700159 if (enabled && !IsGuestMode())
Ken Mixtereafbbdf2010-10-01 15:38:42 -0700160 cached_enabled_ = true;
161 else
162 cached_enabled_ = false;
Ken Mixter4c5daa42010-08-26 18:35:06 -0700163 }
164 return cached_enabled_;
165}
Darin Petkov11b8eb32010-05-18 11:00:59 -0700166
167bool MetricsLibrary::SendMessageToChrome(int32_t length, const char* message) {
Ken Mixter4c5daa42010-08-26 18:35:06 -0700168 if (!AreMetricsEnabled())
169 return true;
170
Darin Petkov8842c8c2011-02-24 12:48:30 -0800171 int chrome_fd = HANDLE_EINTR(open(uma_events_file_,
172 O_WRONLY | O_APPEND | O_CREAT,
173 READ_WRITE_ALL_FILE_FLAGS));
Darin Petkov4fcb2ac2010-04-15 16:40:23 -0700174 // If we failed to open it, return.
Darin Petkov65b01462010-04-14 13:32:20 -0700175 if (chrome_fd < 0) {
Darin Petkov11b8eb32010-05-18 11:00:59 -0700176 PrintError("open", uma_events_file_, errno);
Darin Petkov4fcb2ac2010-04-15 16:40:23 -0700177 return false;
Darin Petkov65b01462010-04-14 13:32:20 -0700178 }
179
Darin Petkov4fcb2ac2010-04-15 16:40:23 -0700180 // Need to chmod because open flags are anded with umask. Ignore the
181 // exit code -- a chronos process may fail chmoding because the file
182 // has been created by a root process but that should be OK.
183 fchmod(chrome_fd, READ_WRITE_ALL_FILE_FLAGS);
Darin Petkov65b01462010-04-14 13:32:20 -0700184
Darin Petkov4fcb2ac2010-04-15 16:40:23 -0700185 // Grab an exclusive lock to protect Chrome from truncating
186 // underneath us. Keep the file locked as briefly as possible.
Darin Petkov8842c8c2011-02-24 12:48:30 -0800187 if (HANDLE_EINTR(flock(chrome_fd, LOCK_EX)) < 0) {
Darin Petkov11b8eb32010-05-18 11:00:59 -0700188 PrintError("flock", uma_events_file_, errno);
Darin Petkov8842c8c2011-02-24 12:48:30 -0800189 HANDLE_EINTR(close(chrome_fd));
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 bool success = true;
Darin Petkov8d3305e2011-02-25 14:19:30 -0800194 if (WriteFileDescriptor(chrome_fd, message, length) != length) {
Darin Petkov11b8eb32010-05-18 11:00:59 -0700195 PrintError("write", uma_events_file_, errno);
Darin Petkov4fcb2ac2010-04-15 16:40:23 -0700196 success = false;
197 }
Darin Petkov65b01462010-04-14 13:32:20 -0700198
Darin Petkov8842c8c2011-02-24 12:48:30 -0800199 // Close the file and release the lock.
200 HANDLE_EINTR(close(chrome_fd));
Darin Petkov4fcb2ac2010-04-15 16:40:23 -0700201 return success;
202}
203
Darin Petkov11b8eb32010-05-18 11:00:59 -0700204int32_t MetricsLibrary::FormatChromeMessage(int32_t buffer_size, char* buffer,
205 const char* format, ...) {
Darin Petkov4fcb2ac2010-04-15 16:40:23 -0700206 int32_t message_length;
207 size_t len_size = sizeof(message_length);
208
209 // Format the non-LENGTH contents in the buffer by leaving space for
210 // LENGTH at the start of the buffer.
211 va_list args;
212 va_start(args, format);
213 message_length = vsnprintf(&buffer[len_size], buffer_size - len_size,
214 format, args);
215 va_end(args);
216
217 if (message_length < 0) {
218 PrintError("chrome message format error", NULL, 0);
219 return -1;
220 }
221
222 // +1 to account for the trailing \0.
223 message_length += len_size + 1;
224 if (message_length > buffer_size) {
225 PrintError("chrome message too long", NULL, 0);
226 return -1;
227 }
228
229 // Prepend LENGTH to the message.
230 memcpy(buffer, &message_length, len_size);
231 return message_length;
232}
233
Darin Petkovfc91b422010-05-12 13:05:45 -0700234void MetricsLibrary::Init() {
Darin Petkov11b8eb32010-05-18 11:00:59 -0700235 uma_events_file_ = kUMAEventsPath;
Darin Petkovfc91b422010-05-12 13:05:45 -0700236}
237
Darin Petkovc2526a12010-04-21 14:24:04 -0700238bool MetricsLibrary::SendToAutotest(const string& name, int value) {
David James3b3add52010-06-04 15:01:19 -0700239 FILE* autotest_file = fopen(kAutotestPath, "a+");
Darin Petkov4fcb2ac2010-04-15 16:40:23 -0700240 if (autotest_file == NULL) {
241 PrintError("fopen", kAutotestPath, errno);
242 return false;
243 }
244
245 fprintf(autotest_file, "%s=%d\n", name.c_str(), value);
246 fclose(autotest_file);
247 return true;
248}
249
Darin Petkov21cd2c52010-05-12 15:26:16 -0700250bool MetricsLibrary::SendToUMA(const string& name, int sample,
251 int min, int max, int nbuckets) {
Darin Petkov4fcb2ac2010-04-15 16:40:23 -0700252 // Format the message.
253 char message[kBufferSize];
254 int32_t message_length =
255 FormatChromeMessage(kBufferSize, message,
Darin Petkovc2526a12010-04-21 14:24:04 -0700256 "histogram%c%s %d %d %d %d", '\0',
257 name.c_str(), sample, min, max, nbuckets);
Darin Petkov4fcb2ac2010-04-15 16:40:23 -0700258 if (message_length < 0)
259 return false;
260
261 // Send the message.
262 return SendMessageToChrome(message_length, message);
Darin Petkov65b01462010-04-14 13:32:20 -0700263}
Darin Petkov5b7dce12010-04-21 15:45:10 -0700264
Darin Petkov21cd2c52010-05-12 15:26:16 -0700265bool MetricsLibrary::SendEnumToUMA(const std::string& name, int sample,
266 int max) {
Darin Petkov5b7dce12010-04-21 15:45:10 -0700267 // Format the message.
268 char message[kBufferSize];
269 int32_t message_length =
270 FormatChromeMessage(kBufferSize, message,
271 "linearhistogram%c%s %d %d", '\0',
272 name.c_str(), sample, max);
Darin Petkoved824852011-01-06 10:51:47 -0800273 if (message_length < 0)
274 return false;
Darin Petkov5b7dce12010-04-21 15:45:10 -0700275
Darin Petkoved824852011-01-06 10:51:47 -0800276 // Send the message.
277 return SendMessageToChrome(message_length, message);
278}
279
280bool MetricsLibrary::SendUserActionToUMA(const std::string& action) {
281 // Format the message.
282 char message[kBufferSize];
283 int32_t message_length =
284 FormatChromeMessage(kBufferSize, message,
285 "useraction%c%s", '\0', action.c_str());
Darin Petkov5b7dce12010-04-21 15:45:10 -0700286 if (message_length < 0)
287 return false;
288
289 // Send the message.
290 return SendMessageToChrome(message_length, message);
291}
Ken Mixterbe2e13b2011-01-22 06:15:56 -0800292
293bool MetricsLibrary::SendCrashToUMA(const char *crash_kind) {
294 // Format the message.
295 char message[kBufferSize];
296 int32_t message_length =
297 FormatChromeMessage(kBufferSize, message,
298 "crash%c%s", '\0', crash_kind);
299
300 if (message_length < 0)
301 return false;
302
303 // Send the message.
304 return SendMessageToChrome(message_length, message);
305}
Ken Mixterb2f17092011-07-22 14:59:51 -0700306
307void MetricsLibrary::SetPolicyProvider(policy::PolicyProvider* provider) {
308 policy_provider_.reset(provider);
309}