blob: 99e0deb9f712a5b2d05aa0f46ac8ce4e718ce3a9 [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
Darin Petkov8842c8c2011-02-24 12:48:30 -0800169 int chrome_fd = HANDLE_EINTR(open(uma_events_file_,
170 O_WRONLY | O_APPEND | O_CREAT,
171 READ_WRITE_ALL_FILE_FLAGS));
Darin Petkov4fcb2ac2010-04-15 16:40:23 -0700172 // If we failed to open it, return.
Darin Petkov65b01462010-04-14 13:32:20 -0700173 if (chrome_fd < 0) {
Darin Petkov11b8eb32010-05-18 11:00:59 -0700174 PrintError("open", uma_events_file_, errno);
Darin Petkov4fcb2ac2010-04-15 16:40:23 -0700175 return false;
Darin Petkov65b01462010-04-14 13:32:20 -0700176 }
177
Darin Petkov4fcb2ac2010-04-15 16:40:23 -0700178 // Need to chmod because open flags are anded with umask. Ignore the
179 // exit code -- a chronos process may fail chmoding because the file
180 // has been created by a root process but that should be OK.
181 fchmod(chrome_fd, READ_WRITE_ALL_FILE_FLAGS);
Darin Petkov65b01462010-04-14 13:32:20 -0700182
Darin Petkov4fcb2ac2010-04-15 16:40:23 -0700183 // Grab an exclusive lock to protect Chrome from truncating
184 // underneath us. Keep the file locked as briefly as possible.
Darin Petkov8842c8c2011-02-24 12:48:30 -0800185 if (HANDLE_EINTR(flock(chrome_fd, LOCK_EX)) < 0) {
Darin Petkov11b8eb32010-05-18 11:00:59 -0700186 PrintError("flock", uma_events_file_, errno);
Darin Petkov8842c8c2011-02-24 12:48:30 -0800187 HANDLE_EINTR(close(chrome_fd));
Darin Petkov4fcb2ac2010-04-15 16:40:23 -0700188 return false;
Darin Petkov65b01462010-04-14 13:32:20 -0700189 }
190
Darin Petkov4fcb2ac2010-04-15 16:40:23 -0700191 bool success = true;
Darin Petkov8d3305e2011-02-25 14:19:30 -0800192 if (WriteFileDescriptor(chrome_fd, message, length) != length) {
Darin Petkov11b8eb32010-05-18 11:00:59 -0700193 PrintError("write", uma_events_file_, errno);
Darin Petkov4fcb2ac2010-04-15 16:40:23 -0700194 success = false;
195 }
Darin Petkov65b01462010-04-14 13:32:20 -0700196
Darin Petkov8842c8c2011-02-24 12:48:30 -0800197 // Close the file and release the lock.
198 HANDLE_EINTR(close(chrome_fd));
Darin Petkov4fcb2ac2010-04-15 16:40:23 -0700199 return success;
200}
201
Darin Petkov11b8eb32010-05-18 11:00:59 -0700202int32_t MetricsLibrary::FormatChromeMessage(int32_t buffer_size, char* buffer,
203 const char* format, ...) {
Darin Petkov4fcb2ac2010-04-15 16:40:23 -0700204 int32_t message_length;
205 size_t len_size = sizeof(message_length);
206
207 // Format the non-LENGTH contents in the buffer by leaving space for
208 // LENGTH at the start of the buffer.
209 va_list args;
210 va_start(args, format);
211 message_length = vsnprintf(&buffer[len_size], buffer_size - len_size,
212 format, args);
213 va_end(args);
214
215 if (message_length < 0) {
216 PrintError("chrome message format error", NULL, 0);
217 return -1;
218 }
219
220 // +1 to account for the trailing \0.
221 message_length += len_size + 1;
222 if (message_length > buffer_size) {
223 PrintError("chrome message too long", NULL, 0);
224 return -1;
225 }
226
227 // Prepend LENGTH to the message.
228 memcpy(buffer, &message_length, len_size);
229 return message_length;
230}
231
Darin Petkovfc91b422010-05-12 13:05:45 -0700232void MetricsLibrary::Init() {
Darin Petkov11b8eb32010-05-18 11:00:59 -0700233 uma_events_file_ = kUMAEventsPath;
Darin Petkovfc91b422010-05-12 13:05:45 -0700234}
235
Darin Petkovc2526a12010-04-21 14:24:04 -0700236bool MetricsLibrary::SendToAutotest(const string& name, int value) {
David James3b3add52010-06-04 15:01:19 -0700237 FILE* autotest_file = fopen(kAutotestPath, "a+");
Darin Petkov4fcb2ac2010-04-15 16:40:23 -0700238 if (autotest_file == NULL) {
239 PrintError("fopen", kAutotestPath, errno);
240 return false;
241 }
242
243 fprintf(autotest_file, "%s=%d\n", name.c_str(), value);
244 fclose(autotest_file);
245 return true;
246}
247
Darin Petkov21cd2c52010-05-12 15:26:16 -0700248bool MetricsLibrary::SendToUMA(const string& name, int sample,
249 int min, int max, int nbuckets) {
Darin Petkov4fcb2ac2010-04-15 16:40:23 -0700250 // Format the message.
251 char message[kBufferSize];
252 int32_t message_length =
253 FormatChromeMessage(kBufferSize, message,
Darin Petkovc2526a12010-04-21 14:24:04 -0700254 "histogram%c%s %d %d %d %d", '\0',
255 name.c_str(), sample, min, max, nbuckets);
Darin Petkov4fcb2ac2010-04-15 16:40:23 -0700256 if (message_length < 0)
257 return false;
258
259 // Send the message.
260 return SendMessageToChrome(message_length, message);
Darin Petkov65b01462010-04-14 13:32:20 -0700261}
Darin Petkov5b7dce12010-04-21 15:45:10 -0700262
Darin Petkov21cd2c52010-05-12 15:26:16 -0700263bool MetricsLibrary::SendEnumToUMA(const std::string& name, int sample,
264 int max) {
Darin Petkov5b7dce12010-04-21 15:45:10 -0700265 // Format the message.
266 char message[kBufferSize];
267 int32_t message_length =
268 FormatChromeMessage(kBufferSize, message,
269 "linearhistogram%c%s %d %d", '\0',
270 name.c_str(), sample, max);
Darin Petkoved824852011-01-06 10:51:47 -0800271 if (message_length < 0)
272 return false;
Darin Petkov5b7dce12010-04-21 15:45:10 -0700273
Darin Petkoved824852011-01-06 10:51:47 -0800274 // Send the message.
275 return SendMessageToChrome(message_length, message);
276}
277
278bool MetricsLibrary::SendUserActionToUMA(const std::string& action) {
279 // Format the message.
280 char message[kBufferSize];
281 int32_t message_length =
282 FormatChromeMessage(kBufferSize, message,
283 "useraction%c%s", '\0', action.c_str());
Darin Petkov5b7dce12010-04-21 15:45:10 -0700284 if (message_length < 0)
285 return false;
286
287 // Send the message.
288 return SendMessageToChrome(message_length, message);
289}
Ken Mixterbe2e13b2011-01-22 06:15:56 -0800290
291bool MetricsLibrary::SendCrashToUMA(const char *crash_kind) {
292 // Format the message.
293 char message[kBufferSize];
294 int32_t message_length =
295 FormatChromeMessage(kBufferSize, message,
296 "crash%c%s", '\0', crash_kind);
297
298 if (message_length < 0)
299 return false;
300
301 // Send the message.
302 return SendMessageToChrome(message_length, message);
303}
Ken Mixterb2f17092011-07-22 14:59:51 -0700304
305void MetricsLibrary::SetPolicyProvider(policy::PolicyProvider* provider) {
306 policy_provider_.reset(provider);
307}