blob: fe481228e0a2b47a609b96e99d0a90dd8e65f6c5 [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)
22
Ken Mixter4c5daa42010-08-26 18:35:06 -070023static const char kAutotestPath[] = "/var/log/metrics/autotest-events";
24static const char kUMAEventsPath[] = "/var/log/metrics/uma-events";
25static const char kConsentFile[] = "/home/chronos/Consent To Send Stats";
Darin Petkov4fcb2ac2010-04-15 16:40:23 -070026static const int32_t kBufferSize = 1024;
Darin Petkov65b01462010-04-14 13:32:20 -070027
Ken Mixter4c5daa42010-08-26 18:35:06 -070028time_t MetricsLibrary::cached_enabled_time_ = 0;
29bool MetricsLibrary::cached_enabled_ = false;
30
David James3b3add52010-06-04 15:01:19 -070031using std::string;
Darin Petkov65b01462010-04-14 13:32:20 -070032
33// TODO(sosa@chromium.org) - use Chromium logger instead of stderr
Darin Petkov11b8eb32010-05-18 11:00:59 -070034static void PrintError(const char* message, const char* file,
Darin Petkov4fcb2ac2010-04-15 16:40:23 -070035 int code) {
David James3b3add52010-06-04 15:01:19 -070036 static const char kProgramName[] = "libmetrics";
Darin Petkov65b01462010-04-14 13:32:20 -070037 if (code == 0) {
38 fprintf(stderr, "%s: %s\n", kProgramName, message);
39 } else if (file == NULL) {
40 fprintf(stderr, "%s: ", kProgramName);
41 perror(message);
42 } else {
43 fprintf(stderr, "%s: %s: ", kProgramName, file);
44 perror(message);
45 }
46}
47
Darin Petkov8d3305e2011-02-25 14:19:30 -080048// Copied from libbase to avoid pulling in all of libbase just for libmetrics.
49static int WriteFileDescriptor(const int fd, const char* data, int size) {
50 // Allow for partial writes.
51 ssize_t bytes_written_total = 0;
52 for (ssize_t bytes_written_partial = 0; bytes_written_total < size;
53 bytes_written_total += bytes_written_partial) {
54 bytes_written_partial =
55 HANDLE_EINTR(write(fd, data + bytes_written_total,
56 size - bytes_written_total));
57 if (bytes_written_partial < 0)
58 return -1;
59 }
60
61 return bytes_written_total;
62}
63
Darin Petkov11b8eb32010-05-18 11:00:59 -070064MetricsLibrary::MetricsLibrary()
Ken Mixter4c5daa42010-08-26 18:35:06 -070065 : uma_events_file_(NULL),
Ken Mixterb2f17092011-07-22 14:59:51 -070066 consent_file_(kConsentFile),
67 policy_provider_(NULL) {}
Ken Mixter4c5daa42010-08-26 18:35:06 -070068
Ken Mixtereafbbdf2010-10-01 15:38:42 -070069// We take buffer and buffer_size as parameters in order to simplify testing
70// of various alignments of the |device_name| with |buffer_size|.
71bool MetricsLibrary::IsDeviceMounted(const char* device_name,
72 const char* mounts_file,
73 char* buffer,
74 int buffer_size,
75 bool* result) {
76 if (buffer == NULL || buffer_size < 1)
77 return false;
78 int mounts_fd = open(mounts_file, O_RDONLY);
79 if (mounts_fd < 0)
80 return false;
81 // match_offset describes:
82 // -1 -- not beginning of line
83 // 0..strlen(device_name)-1 -- this offset in device_name is next to match
84 // strlen(device_name) -- matched full name, just need a space.
85 int match_offset = 0;
86 bool match = false;
87 while (!match) {
88 int read_size = read(mounts_fd, buffer, buffer_size);
89 if (read_size <= 0) {
90 if (errno == -EINTR)
91 continue;
92 break;
93 }
94 for (int i = 0; i < read_size; ++i) {
95 if (buffer[i] == '\n') {
96 match_offset = 0;
97 continue;
98 }
99 if (match_offset < 0) {
100 continue;
101 }
102 if (device_name[match_offset] == '\0') {
103 if (buffer[i] == ' ') {
104 match = true;
105 break;
106 }
107 match_offset = -1;
108 continue;
109 }
110
111 if (buffer[i] == device_name[match_offset]) {
112 ++match_offset;
113 } else {
114 match_offset = -1;
115 }
116 }
117 }
118 close(mounts_fd);
119 *result = match;
120 return true;
121}
122
123bool MetricsLibrary::IsGuestMode() {
124 char buffer[256];
125 bool result = false;
126 if (!IsDeviceMounted("guestfs",
127 "/proc/mounts",
128 buffer,
129 sizeof(buffer),
130 &result)) {
131 return false;
132 }
Arkaitz Ruiz Alvarez9f1a7742011-05-26 12:22:22 -0700133 return result && (access("/var/run/state/logged-in", F_OK) == 0);
Ken Mixtereafbbdf2010-10-01 15:38:42 -0700134}
135
Ken Mixter4c5daa42010-08-26 18:35:06 -0700136bool MetricsLibrary::AreMetricsEnabled() {
Julian Pastarmov70b7abd2011-08-02 16:10:49 +0200137 static struct stat stat_buffer;
Ken Mixter4c5daa42010-08-26 18:35:06 -0700138 time_t this_check_time = time(NULL);
Ken Mixter4c5daa42010-08-26 18:35:06 -0700139 if (this_check_time != cached_enabled_time_) {
140 cached_enabled_time_ = this_check_time;
Julian Pastarmov70b7abd2011-08-02 16:10:49 +0200141
142 if (!policy_provider_.get())
143 policy_provider_.reset(new policy::PolicyProvider());
Julian Pastarmovd605a002013-02-04 17:58:14 +0100144 policy_provider_->Reload();
Julian Pastarmov70b7abd2011-08-02 16:10:49 +0200145 // We initialize with the default value which is false and will be preserved
146 // if the policy is not set.
147 bool enabled = false;
148 bool has_policy = false;
149 if (policy_provider_->device_policy_is_loaded()) {
150 has_policy =
151 policy_provider_->GetDevicePolicy().GetMetricsEnabled(&enabled);
152 }
153 // If policy couldn't be loaded or the metrics policy is not set we should
154 // still respect the consent file if it is present for migration purposes.
155 // TODO(pastarmovj)
156 if (!has_policy) {
157 enabled = stat(consent_file_, &stat_buffer) >= 0;
158 }
159
Ken Mixterb2f17092011-07-22 14:59:51 -0700160 if (enabled && !IsGuestMode())
Ken Mixtereafbbdf2010-10-01 15:38:42 -0700161 cached_enabled_ = true;
162 else
163 cached_enabled_ = false;
Ken Mixter4c5daa42010-08-26 18:35:06 -0700164 }
165 return cached_enabled_;
166}
Darin Petkov11b8eb32010-05-18 11:00:59 -0700167
168bool MetricsLibrary::SendMessageToChrome(int32_t length, const char* message) {
Ken Mixter4c5daa42010-08-26 18:35:06 -0700169
Darin Petkov8842c8c2011-02-24 12:48:30 -0800170 int chrome_fd = HANDLE_EINTR(open(uma_events_file_,
171 O_WRONLY | O_APPEND | O_CREAT,
172 READ_WRITE_ALL_FILE_FLAGS));
Darin Petkov4fcb2ac2010-04-15 16:40:23 -0700173 // If we failed to open it, return.
Darin Petkov65b01462010-04-14 13:32:20 -0700174 if (chrome_fd < 0) {
Darin Petkov11b8eb32010-05-18 11:00:59 -0700175 PrintError("open", uma_events_file_, errno);
Darin Petkov4fcb2ac2010-04-15 16:40:23 -0700176 return false;
Darin Petkov65b01462010-04-14 13:32:20 -0700177 }
178
Darin Petkov4fcb2ac2010-04-15 16:40:23 -0700179 // Need to chmod because open flags are anded with umask. Ignore the
180 // exit code -- a chronos process may fail chmoding because the file
181 // has been created by a root process but that should be OK.
182 fchmod(chrome_fd, READ_WRITE_ALL_FILE_FLAGS);
Darin Petkov65b01462010-04-14 13:32:20 -0700183
Darin Petkov4fcb2ac2010-04-15 16:40:23 -0700184 // Grab an exclusive lock to protect Chrome from truncating
185 // underneath us. Keep the file locked as briefly as possible.
Darin Petkov8842c8c2011-02-24 12:48:30 -0800186 if (HANDLE_EINTR(flock(chrome_fd, LOCK_EX)) < 0) {
Darin Petkov11b8eb32010-05-18 11:00:59 -0700187 PrintError("flock", uma_events_file_, errno);
Darin Petkov8842c8c2011-02-24 12:48:30 -0800188 HANDLE_EINTR(close(chrome_fd));
Darin Petkov4fcb2ac2010-04-15 16:40:23 -0700189 return false;
Darin Petkov65b01462010-04-14 13:32:20 -0700190 }
191
Darin Petkov4fcb2ac2010-04-15 16:40:23 -0700192 bool success = true;
Darin Petkov8d3305e2011-02-25 14:19:30 -0800193 if (WriteFileDescriptor(chrome_fd, message, length) != length) {
Darin Petkov11b8eb32010-05-18 11:00:59 -0700194 PrintError("write", uma_events_file_, errno);
Darin Petkov4fcb2ac2010-04-15 16:40:23 -0700195 success = false;
196 }
Darin Petkov65b01462010-04-14 13:32:20 -0700197
Darin Petkov8842c8c2011-02-24 12:48:30 -0800198 // Close the file and release the lock.
199 HANDLE_EINTR(close(chrome_fd));
Darin Petkov4fcb2ac2010-04-15 16:40:23 -0700200 return success;
201}
202
Darin Petkov11b8eb32010-05-18 11:00:59 -0700203int32_t MetricsLibrary::FormatChromeMessage(int32_t buffer_size, char* buffer,
204 const char* format, ...) {
Darin Petkov4fcb2ac2010-04-15 16:40:23 -0700205 int32_t message_length;
206 size_t len_size = sizeof(message_length);
207
208 // Format the non-LENGTH contents in the buffer by leaving space for
209 // LENGTH at the start of the buffer.
210 va_list args;
211 va_start(args, format);
212 message_length = vsnprintf(&buffer[len_size], buffer_size - len_size,
213 format, args);
214 va_end(args);
215
216 if (message_length < 0) {
217 PrintError("chrome message format error", NULL, 0);
218 return -1;
219 }
220
221 // +1 to account for the trailing \0.
222 message_length += len_size + 1;
223 if (message_length > buffer_size) {
224 PrintError("chrome message too long", NULL, 0);
225 return -1;
226 }
227
228 // Prepend LENGTH to the message.
229 memcpy(buffer, &message_length, len_size);
230 return message_length;
231}
232
Darin Petkovfc91b422010-05-12 13:05:45 -0700233void MetricsLibrary::Init() {
Darin Petkov11b8eb32010-05-18 11:00:59 -0700234 uma_events_file_ = kUMAEventsPath;
Darin Petkovfc91b422010-05-12 13:05:45 -0700235}
236
Darin Petkovc2526a12010-04-21 14:24:04 -0700237bool MetricsLibrary::SendToAutotest(const string& name, int value) {
David James3b3add52010-06-04 15:01:19 -0700238 FILE* autotest_file = fopen(kAutotestPath, "a+");
Darin Petkov4fcb2ac2010-04-15 16:40:23 -0700239 if (autotest_file == NULL) {
240 PrintError("fopen", kAutotestPath, errno);
241 return false;
242 }
243
244 fprintf(autotest_file, "%s=%d\n", name.c_str(), value);
245 fclose(autotest_file);
246 return true;
247}
248
Darin Petkov21cd2c52010-05-12 15:26:16 -0700249bool MetricsLibrary::SendToUMA(const string& name, int sample,
250 int min, int max, int nbuckets) {
Darin Petkov4fcb2ac2010-04-15 16:40:23 -0700251 // Format the message.
252 char message[kBufferSize];
253 int32_t message_length =
254 FormatChromeMessage(kBufferSize, message,
Darin Petkovc2526a12010-04-21 14:24:04 -0700255 "histogram%c%s %d %d %d %d", '\0',
256 name.c_str(), sample, min, max, nbuckets);
Darin Petkov4fcb2ac2010-04-15 16:40:23 -0700257 if (message_length < 0)
258 return false;
259
260 // Send the message.
261 return SendMessageToChrome(message_length, message);
Darin Petkov65b01462010-04-14 13:32:20 -0700262}
Darin Petkov5b7dce12010-04-21 15:45:10 -0700263
Darin Petkov21cd2c52010-05-12 15:26:16 -0700264bool MetricsLibrary::SendEnumToUMA(const std::string& name, int sample,
265 int max) {
Darin Petkov5b7dce12010-04-21 15:45:10 -0700266 // Format the message.
267 char message[kBufferSize];
268 int32_t message_length =
269 FormatChromeMessage(kBufferSize, message,
270 "linearhistogram%c%s %d %d", '\0',
271 name.c_str(), sample, max);
Darin Petkoved824852011-01-06 10:51:47 -0800272 if (message_length < 0)
273 return false;
Darin Petkov5b7dce12010-04-21 15:45:10 -0700274
Darin Petkoved824852011-01-06 10:51:47 -0800275 // Send the message.
276 return SendMessageToChrome(message_length, message);
277}
278
279bool MetricsLibrary::SendUserActionToUMA(const std::string& action) {
280 // Format the message.
281 char message[kBufferSize];
282 int32_t message_length =
283 FormatChromeMessage(kBufferSize, message,
284 "useraction%c%s", '\0', action.c_str());
Darin Petkov5b7dce12010-04-21 15:45:10 -0700285 if (message_length < 0)
286 return false;
287
288 // Send the message.
289 return SendMessageToChrome(message_length, message);
290}
Ken Mixterbe2e13b2011-01-22 06:15:56 -0800291
292bool MetricsLibrary::SendCrashToUMA(const char *crash_kind) {
293 // Format the message.
294 char message[kBufferSize];
295 int32_t message_length =
296 FormatChromeMessage(kBufferSize, message,
297 "crash%c%s", '\0', crash_kind);
298
299 if (message_length < 0)
300 return false;
301
302 // Send the message.
303 return SendMessageToChrome(message_length, message);
304}
Ken Mixterb2f17092011-07-22 14:59:51 -0700305
306void MetricsLibrary::SetPolicyProvider(policy::PolicyProvider* provider) {
307 policy_provider_.reset(provider);
308}