blob: b15fd4999cfd1a065a47f3b5caeea37fcd1e0c2d [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
Luigi Semenzato41c54502014-05-13 15:16:24 -07007#include <base/logging.h>
8#include <base/strings/stringprintf.h>
Darin Petkov65b01462010-04-14 13:32:20 -07009#include <errno.h>
10#include <sys/file.h>
Ken Mixter4c5daa42010-08-26 18:35:06 -070011#include <sys/stat.h>
Darin Petkov4fcb2ac2010-04-15 16:40:23 -070012
13#include <cstdarg>
14#include <cstdio>
15#include <cstring>
Darin Petkov65b01462010-04-14 13:32:20 -070016
Chris Masonee10b5482013-02-14 12:15:35 -080017// HANDLE_EINTR macro, no libbase required.
18#include <base/posix/eintr_wrapper.h>
19
Ken Mixterb2f17092011-07-22 14:59:51 -070020#include "policy/device_policy.h"
Darin Petkov8842c8c2011-02-24 12:48:30 -080021
Darin Petkov65b01462010-04-14 13:32:20 -070022#define READ_WRITE_ALL_FILE_FLAGS \
23 (S_IRUSR | S_IWUSR | S_IRGRP | S_IWGRP | S_IROTH | S_IWOTH)
Chih-Chung Chang6844c062013-04-01 14:27:39 +080024#define ARRAY_SIZE(a) (sizeof(a) / sizeof((a)[0]))
Darin Petkov65b01462010-04-14 13:32:20 -070025
Ken Mixter4c5daa42010-08-26 18:35:06 -070026static const char kAutotestPath[] = "/var/log/metrics/autotest-events";
Luigi Semenzato31cda982014-05-19 08:30:42 -070027static const char kUMAEventsPath[] = "/var/run/metrics/uma-events";
Ken Mixter4c5daa42010-08-26 18:35:06 -070028static const char kConsentFile[] = "/home/chronos/Consent To Send Stats";
Darin Petkov4fcb2ac2010-04-15 16:40:23 -070029static const int32_t kBufferSize = 1024;
Luigi Semenzato32684222013-03-13 10:53:55 -070030static const char kCrosEventHistogramName[] = "Platform.CrOSEvent";
31static const int kCrosEventHistogramMax = 100;
Darin Petkov65b01462010-04-14 13:32:20 -070032
Chih-Chung Chang6844c062013-04-01 14:27:39 +080033/* Add new cros events here.
34 *
35 * The index of the event is sent in the message, so please do not
36 * reorder the names.
37 */
38static const char *kCrosEventNames[] = {
39 "ModemManagerCommandSendFailure", // 0
40 "HwWatchdogReboot", // 1
41 "Cras.NoCodecsFoundAtBoot", // 2
Darren Krahn6e55c1152013-07-19 14:09:50 -070042 "Chaps.DatabaseCorrupted", // 3
43 "Chaps.DatabaseRepairFailure", // 4
44 "Chaps.DatabaseCreateFailure", // 5
Darren Krahn86830ba2013-07-26 13:37:20 -070045 "Attestation.OriginSpecificExhausted", // 6
Luigi Semenzatoe57398a2013-11-11 14:24:44 -080046 "SpringPowerSupply.Original.High", // 7
47 "SpringPowerSupply.Other.High", // 8
Luigi Semenzatoe8fd9682013-11-13 16:28:43 -080048 "SpringPowerSupply.Original.Low", // 9
49 "SpringPowerSupply.ChargerIdle", // 10
Darren Krahn09a15fa2014-02-07 16:51:15 -080050 "TPM.NonZeroDictionaryAttackCounter", // 11
Chih-Chung Chang6844c062013-04-01 14:27:39 +080051};
52
Ken Mixter4c5daa42010-08-26 18:35:06 -070053time_t MetricsLibrary::cached_enabled_time_ = 0;
54bool MetricsLibrary::cached_enabled_ = false;
55
Darin Petkov8d3305e2011-02-25 14:19:30 -080056// Copied from libbase to avoid pulling in all of libbase just for libmetrics.
57static int WriteFileDescriptor(const int fd, const char* data, int size) {
58 // Allow for partial writes.
59 ssize_t bytes_written_total = 0;
60 for (ssize_t bytes_written_partial = 0; bytes_written_total < size;
61 bytes_written_total += bytes_written_partial) {
62 bytes_written_partial =
63 HANDLE_EINTR(write(fd, data + bytes_written_total,
64 size - bytes_written_total));
65 if (bytes_written_partial < 0)
66 return -1;
67 }
68
69 return bytes_written_total;
70}
71
Luigi Semenzato41c54502014-05-13 15:16:24 -070072MetricsLibrary::MetricsLibrary() : consent_file_(kConsentFile) {}
Daniel Eratfd158292014-03-09 21:39:08 -070073MetricsLibrary::~MetricsLibrary() {}
74
Ken Mixtereafbbdf2010-10-01 15:38:42 -070075// We take buffer and buffer_size as parameters in order to simplify testing
76// of various alignments of the |device_name| with |buffer_size|.
77bool MetricsLibrary::IsDeviceMounted(const char* device_name,
78 const char* mounts_file,
79 char* buffer,
80 int buffer_size,
81 bool* result) {
82 if (buffer == NULL || buffer_size < 1)
83 return false;
84 int mounts_fd = open(mounts_file, O_RDONLY);
85 if (mounts_fd < 0)
86 return false;
87 // match_offset describes:
88 // -1 -- not beginning of line
89 // 0..strlen(device_name)-1 -- this offset in device_name is next to match
90 // strlen(device_name) -- matched full name, just need a space.
91 int match_offset = 0;
92 bool match = false;
93 while (!match) {
94 int read_size = read(mounts_fd, buffer, buffer_size);
95 if (read_size <= 0) {
96 if (errno == -EINTR)
97 continue;
98 break;
99 }
100 for (int i = 0; i < read_size; ++i) {
101 if (buffer[i] == '\n') {
102 match_offset = 0;
103 continue;
104 }
105 if (match_offset < 0) {
106 continue;
107 }
108 if (device_name[match_offset] == '\0') {
109 if (buffer[i] == ' ') {
110 match = true;
111 break;
112 }
113 match_offset = -1;
114 continue;
115 }
116
117 if (buffer[i] == device_name[match_offset]) {
118 ++match_offset;
119 } else {
120 match_offset = -1;
121 }
122 }
123 }
124 close(mounts_fd);
125 *result = match;
126 return true;
127}
128
129bool MetricsLibrary::IsGuestMode() {
130 char buffer[256];
131 bool result = false;
132 if (!IsDeviceMounted("guestfs",
133 "/proc/mounts",
134 buffer,
135 sizeof(buffer),
136 &result)) {
137 return false;
138 }
Arkaitz Ruiz Alvarez9f1a7742011-05-26 12:22:22 -0700139 return result && (access("/var/run/state/logged-in", F_OK) == 0);
Ken Mixtereafbbdf2010-10-01 15:38:42 -0700140}
141
Ken Mixter4c5daa42010-08-26 18:35:06 -0700142bool MetricsLibrary::AreMetricsEnabled() {
Julian Pastarmov70b7abd2011-08-02 16:10:49 +0200143 static struct stat stat_buffer;
Ken Mixter4c5daa42010-08-26 18:35:06 -0700144 time_t this_check_time = time(NULL);
Ken Mixter4c5daa42010-08-26 18:35:06 -0700145 if (this_check_time != cached_enabled_time_) {
146 cached_enabled_time_ = this_check_time;
Julian Pastarmov70b7abd2011-08-02 16:10:49 +0200147
148 if (!policy_provider_.get())
149 policy_provider_.reset(new policy::PolicyProvider());
Julian Pastarmovd605a002013-02-04 17:58:14 +0100150 policy_provider_->Reload();
Julian Pastarmov70b7abd2011-08-02 16:10:49 +0200151 // We initialize with the default value which is false and will be preserved
152 // if the policy is not set.
153 bool enabled = false;
154 bool has_policy = false;
155 if (policy_provider_->device_policy_is_loaded()) {
156 has_policy =
157 policy_provider_->GetDevicePolicy().GetMetricsEnabled(&enabled);
158 }
159 // If policy couldn't be loaded or the metrics policy is not set we should
160 // still respect the consent file if it is present for migration purposes.
161 // TODO(pastarmovj)
162 if (!has_policy) {
Luigi Semenzato41c54502014-05-13 15:16:24 -0700163 enabled = stat(consent_file_.c_str(), &stat_buffer) >= 0;
Julian Pastarmov70b7abd2011-08-02 16:10:49 +0200164 }
165
Ken Mixterb2f17092011-07-22 14:59:51 -0700166 if (enabled && !IsGuestMode())
Ken Mixtereafbbdf2010-10-01 15:38:42 -0700167 cached_enabled_ = true;
168 else
169 cached_enabled_ = false;
Ken Mixter4c5daa42010-08-26 18:35:06 -0700170 }
171 return cached_enabled_;
172}
Darin Petkov11b8eb32010-05-18 11:00:59 -0700173
Luigi Semenzato31cda982014-05-19 08:30:42 -0700174bool MetricsLibrary::SendMessageToChrome(const std::string& message) {
Luigi Semenzato41c54502014-05-13 15:16:24 -0700175 int size = static_cast<int>(message.size());
176 if (size > kBufferSize) {
177 LOG(ERROR) << "chrome message too big (" << size << " bytes)";
178 return false;
179 }
180 // Use libc here instead of chromium base classes because we need a UNIX fd
181 // for flock.
Luigi Semenzato31cda982014-05-19 08:30:42 -0700182 int chrome_fd = HANDLE_EINTR(open(uma_events_file_.c_str(),
Darin Petkov8842c8c2011-02-24 12:48:30 -0800183 O_WRONLY | O_APPEND | O_CREAT,
184 READ_WRITE_ALL_FILE_FLAGS));
Darin Petkov4fcb2ac2010-04-15 16:40:23 -0700185 // If we failed to open it, return.
Darin Petkov65b01462010-04-14 13:32:20 -0700186 if (chrome_fd < 0) {
Luigi Semenzato31cda982014-05-19 08:30:42 -0700187 PLOG(ERROR) << uma_events_file_ << ": open";
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 // Need to chmod because open flags are anded with umask. Ignore the
192 // exit code -- a chronos process may fail chmoding because the file
193 // has been created by a root process but that should be OK.
194 fchmod(chrome_fd, READ_WRITE_ALL_FILE_FLAGS);
Darin Petkov65b01462010-04-14 13:32:20 -0700195
Darin Petkov4fcb2ac2010-04-15 16:40:23 -0700196 // Grab an exclusive lock to protect Chrome from truncating
Luigi Semenzato41c54502014-05-13 15:16:24 -0700197 // underneath us.
Darin Petkov8842c8c2011-02-24 12:48:30 -0800198 if (HANDLE_EINTR(flock(chrome_fd, LOCK_EX)) < 0) {
Luigi Semenzato31cda982014-05-19 08:30:42 -0700199 PLOG(ERROR) << uma_events_file_ << ": flock";
Mike Frysinger3e8a8512014-05-14 16:14:37 -0400200 IGNORE_EINTR(close(chrome_fd));
Darin Petkov4fcb2ac2010-04-15 16:40:23 -0700201 return false;
Darin Petkov65b01462010-04-14 13:32:20 -0700202 }
203
Darin Petkov4fcb2ac2010-04-15 16:40:23 -0700204 bool success = true;
Luigi Semenzato41c54502014-05-13 15:16:24 -0700205 if (WriteFileDescriptor(chrome_fd, message.c_str(), size) != size) {
Luigi Semenzato31cda982014-05-19 08:30:42 -0700206 PLOG(ERROR) << uma_events_file_ << ": write";
Darin Petkov4fcb2ac2010-04-15 16:40:23 -0700207 success = false;
208 }
Darin Petkov65b01462010-04-14 13:32:20 -0700209
Darin Petkov8842c8c2011-02-24 12:48:30 -0800210 // Close the file and release the lock.
Mike Frysinger3e8a8512014-05-14 16:14:37 -0400211 IGNORE_EINTR(close(chrome_fd));
Darin Petkov4fcb2ac2010-04-15 16:40:23 -0700212 return success;
213}
214
Luigi Semenzato41c54502014-05-13 15:16:24 -0700215const std::string MetricsLibrary::FormatChromeMessage(
216 const std::string& name,
217 const std::string& value) {
218 uint32 message_length =
219 sizeof(message_length) + name.size() + 1 + value.size() + 1;
220 std::string result;
221 result.reserve(message_length);
222 // Marshal the total message length in the native byte order.
223 result.assign(reinterpret_cast<char*>(&message_length),
224 sizeof(message_length));
225 result += name + '\0' + value + '\0';
226 return result;
Darin Petkov4fcb2ac2010-04-15 16:40:23 -0700227}
228
Darin Petkovfc91b422010-05-12 13:05:45 -0700229void MetricsLibrary::Init() {
Darin Petkov11b8eb32010-05-18 11:00:59 -0700230 uma_events_file_ = kUMAEventsPath;
Darin Petkovfc91b422010-05-12 13:05:45 -0700231}
232
Luigi Semenzato41c54502014-05-13 15:16:24 -0700233bool MetricsLibrary::SendToAutotest(const std::string& name, int value) {
David James3b3add52010-06-04 15:01:19 -0700234 FILE* autotest_file = fopen(kAutotestPath, "a+");
Darin Petkov4fcb2ac2010-04-15 16:40:23 -0700235 if (autotest_file == NULL) {
Luigi Semenzato41c54502014-05-13 15:16:24 -0700236 PLOG(ERROR) << kAutotestPath << ": fopen";
Darin Petkov4fcb2ac2010-04-15 16:40:23 -0700237 return false;
238 }
239
240 fprintf(autotest_file, "%s=%d\n", name.c_str(), value);
241 fclose(autotest_file);
242 return true;
243}
244
Luigi Semenzato41c54502014-05-13 15:16:24 -0700245bool MetricsLibrary::SendToUMA(const std::string& name,
246 int sample,
247 int min,
248 int max,
249 int nbuckets) {
Darin Petkov4fcb2ac2010-04-15 16:40:23 -0700250 // Format the message.
Luigi Semenzato41c54502014-05-13 15:16:24 -0700251 std::string value = base::StringPrintf("%s %d %d %d %d",
252 name.c_str(), sample, min, max, nbuckets);
253 std::string message = FormatChromeMessage("histogram", value);
Darin Petkov4fcb2ac2010-04-15 16:40:23 -0700254 // Send the message.
Luigi Semenzato41c54502014-05-13 15:16:24 -0700255 return SendMessageToChrome(message);
Darin Petkov65b01462010-04-14 13:32:20 -0700256}
Darin Petkov5b7dce12010-04-21 15:45:10 -0700257
Darin Petkov21cd2c52010-05-12 15:26:16 -0700258bool MetricsLibrary::SendEnumToUMA(const std::string& name, int sample,
259 int max) {
Darin Petkov5b7dce12010-04-21 15:45:10 -0700260 // Format the message.
Luigi Semenzato41c54502014-05-13 15:16:24 -0700261 std::string value = base::StringPrintf("%s %d %d", name.c_str(), sample, max);
262 std::string message = FormatChromeMessage("linearhistogram", value);
Darin Petkoved824852011-01-06 10:51:47 -0800263 // Send the message.
Luigi Semenzato41c54502014-05-13 15:16:24 -0700264 return SendMessageToChrome(message);
Darin Petkoved824852011-01-06 10:51:47 -0800265}
266
Luigi Semenzatoa7ebeb32013-03-19 15:02:42 -0700267bool MetricsLibrary::SendSparseToUMA(const std::string& name, int sample) {
268 // Format the message.
Luigi Semenzato41c54502014-05-13 15:16:24 -0700269 std::string value = base::StringPrintf("%s %d", name.c_str(), sample);
270 std::string message = FormatChromeMessage("sparsehistogram", value);
Luigi Semenzatoa7ebeb32013-03-19 15:02:42 -0700271 // Send the message.
Luigi Semenzato41c54502014-05-13 15:16:24 -0700272 return SendMessageToChrome(message);
Luigi Semenzatoa7ebeb32013-03-19 15:02:42 -0700273}
274
Darin Petkoved824852011-01-06 10:51:47 -0800275bool MetricsLibrary::SendUserActionToUMA(const std::string& action) {
276 // Format the message.
Luigi Semenzato41c54502014-05-13 15:16:24 -0700277 std::string message = FormatChromeMessage("useraction", action);
Darin Petkov5b7dce12010-04-21 15:45:10 -0700278 // Send the message.
Luigi Semenzato41c54502014-05-13 15:16:24 -0700279 return SendMessageToChrome(message);
Darin Petkov5b7dce12010-04-21 15:45:10 -0700280}
Ken Mixterbe2e13b2011-01-22 06:15:56 -0800281
282bool MetricsLibrary::SendCrashToUMA(const char *crash_kind) {
283 // Format the message.
Luigi Semenzato41c54502014-05-13 15:16:24 -0700284 std::string message = FormatChromeMessage("crash", crash_kind);
Ken Mixterbe2e13b2011-01-22 06:15:56 -0800285 // Send the message.
Luigi Semenzato41c54502014-05-13 15:16:24 -0700286 return SendMessageToChrome(message);
Ken Mixterbe2e13b2011-01-22 06:15:56 -0800287}
Ken Mixterb2f17092011-07-22 14:59:51 -0700288
289void MetricsLibrary::SetPolicyProvider(policy::PolicyProvider* provider) {
290 policy_provider_.reset(provider);
291}
Luigi Semenzato32684222013-03-13 10:53:55 -0700292
293bool MetricsLibrary::SendCrosEventToUMA(const std::string& event) {
Chih-Chung Chang6844c062013-04-01 14:27:39 +0800294 for (size_t i = 0; i < ARRAY_SIZE(kCrosEventNames); i++) {
295 if (strcmp(event.c_str(), kCrosEventNames[i]) == 0) {
296 return SendEnumToUMA(kCrosEventHistogramName, i, kCrosEventHistogramMax);
297 }
Luigi Semenzato32684222013-03-13 10:53:55 -0700298 }
Chih-Chung Chang6844c062013-04-01 14:27:39 +0800299 return false;
Luigi Semenzato32684222013-03-13 10:53:55 -0700300}