blob: 4fbc1d8dd37a34e9e36c67551dc8c268de1e81d1 [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
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";
Luigi Semenzato31cda982014-05-19 08:30:42 -070025static const char kUMAEventsPath[] = "/var/run/metrics/uma-events";
Ken Mixter4c5daa42010-08-26 18:35:06 -070026static 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
Luigi Semenzatoe8fd9682013-11-13 16:28:43 -080046 "SpringPowerSupply.Original.Low", // 9
47 "SpringPowerSupply.ChargerIdle", // 10
Darren Krahn09a15fa2014-02-07 16:51:15 -080048 "TPM.NonZeroDictionaryAttackCounter", // 11
Chih-Chung Chang6844c062013-04-01 14:27:39 +080049};
50
Ken Mixter4c5daa42010-08-26 18:35:06 -070051time_t MetricsLibrary::cached_enabled_time_ = 0;
52bool MetricsLibrary::cached_enabled_ = false;
53
Darin Petkov8d3305e2011-02-25 14:19:30 -080054// Copied from libbase to avoid pulling in all of libbase just for libmetrics.
55static int WriteFileDescriptor(const int fd, const char* data, int size) {
56 // Allow for partial writes.
57 ssize_t bytes_written_total = 0;
58 for (ssize_t bytes_written_partial = 0; bytes_written_total < size;
59 bytes_written_total += bytes_written_partial) {
60 bytes_written_partial =
61 HANDLE_EINTR(write(fd, data + bytes_written_total,
62 size - bytes_written_total));
63 if (bytes_written_partial < 0)
64 return -1;
65 }
66
67 return bytes_written_total;
68}
69
Luigi Semenzato41c54502014-05-13 15:16:24 -070070MetricsLibrary::MetricsLibrary() : consent_file_(kConsentFile) {}
Daniel Eratfd158292014-03-09 21:39:08 -070071MetricsLibrary::~MetricsLibrary() {}
72
Ken Mixtereafbbdf2010-10-01 15:38:42 -070073// We take buffer and buffer_size as parameters in order to simplify testing
74// of various alignments of the |device_name| with |buffer_size|.
75bool MetricsLibrary::IsDeviceMounted(const char* device_name,
76 const char* mounts_file,
77 char* buffer,
78 int buffer_size,
79 bool* result) {
80 if (buffer == NULL || buffer_size < 1)
81 return false;
82 int mounts_fd = open(mounts_file, O_RDONLY);
83 if (mounts_fd < 0)
84 return false;
85 // match_offset describes:
86 // -1 -- not beginning of line
87 // 0..strlen(device_name)-1 -- this offset in device_name is next to match
88 // strlen(device_name) -- matched full name, just need a space.
89 int match_offset = 0;
90 bool match = false;
91 while (!match) {
92 int read_size = read(mounts_fd, buffer, buffer_size);
93 if (read_size <= 0) {
94 if (errno == -EINTR)
95 continue;
96 break;
97 }
98 for (int i = 0; i < read_size; ++i) {
99 if (buffer[i] == '\n') {
100 match_offset = 0;
101 continue;
102 }
103 if (match_offset < 0) {
104 continue;
105 }
106 if (device_name[match_offset] == '\0') {
107 if (buffer[i] == ' ') {
108 match = true;
109 break;
110 }
111 match_offset = -1;
112 continue;
113 }
114
115 if (buffer[i] == device_name[match_offset]) {
116 ++match_offset;
117 } else {
118 match_offset = -1;
119 }
120 }
121 }
122 close(mounts_fd);
123 *result = match;
124 return true;
125}
126
127bool MetricsLibrary::IsGuestMode() {
128 char buffer[256];
129 bool result = false;
130 if (!IsDeviceMounted("guestfs",
131 "/proc/mounts",
132 buffer,
133 sizeof(buffer),
134 &result)) {
135 return false;
136 }
Arkaitz Ruiz Alvarez9f1a7742011-05-26 12:22:22 -0700137 return result && (access("/var/run/state/logged-in", F_OK) == 0);
Ken Mixtereafbbdf2010-10-01 15:38:42 -0700138}
139
Ken Mixter4c5daa42010-08-26 18:35:06 -0700140bool MetricsLibrary::AreMetricsEnabled() {
Julian Pastarmov70b7abd2011-08-02 16:10:49 +0200141 static struct stat stat_buffer;
Ken Mixter4c5daa42010-08-26 18:35:06 -0700142 time_t this_check_time = time(NULL);
Ken Mixter4c5daa42010-08-26 18:35:06 -0700143 if (this_check_time != cached_enabled_time_) {
144 cached_enabled_time_ = this_check_time;
Julian Pastarmov70b7abd2011-08-02 16:10:49 +0200145
146 if (!policy_provider_.get())
147 policy_provider_.reset(new policy::PolicyProvider());
Julian Pastarmovd605a002013-02-04 17:58:14 +0100148 policy_provider_->Reload();
Julian Pastarmov70b7abd2011-08-02 16:10:49 +0200149 // We initialize with the default value which is false and will be preserved
150 // if the policy is not set.
151 bool enabled = false;
152 bool has_policy = false;
153 if (policy_provider_->device_policy_is_loaded()) {
154 has_policy =
155 policy_provider_->GetDevicePolicy().GetMetricsEnabled(&enabled);
156 }
157 // If policy couldn't be loaded or the metrics policy is not set we should
158 // still respect the consent file if it is present for migration purposes.
159 // TODO(pastarmovj)
160 if (!has_policy) {
Luigi Semenzato41c54502014-05-13 15:16:24 -0700161 enabled = stat(consent_file_.c_str(), &stat_buffer) >= 0;
Julian Pastarmov70b7abd2011-08-02 16:10:49 +0200162 }
163
Ken Mixterb2f17092011-07-22 14:59:51 -0700164 if (enabled && !IsGuestMode())
Ken Mixtereafbbdf2010-10-01 15:38:42 -0700165 cached_enabled_ = true;
166 else
167 cached_enabled_ = false;
Ken Mixter4c5daa42010-08-26 18:35:06 -0700168 }
169 return cached_enabled_;
170}
Darin Petkov11b8eb32010-05-18 11:00:59 -0700171
Luigi Semenzato31cda982014-05-19 08:30:42 -0700172bool MetricsLibrary::SendMessageToChrome(const std::string& message) {
Luigi Semenzato41c54502014-05-13 15:16:24 -0700173 int size = static_cast<int>(message.size());
174 if (size > kBufferSize) {
175 LOG(ERROR) << "chrome message too big (" << size << " bytes)";
176 return false;
177 }
178 // Use libc here instead of chromium base classes because we need a UNIX fd
Luigi Semenzatoa5db2202014-05-23 15:06:24 -0700179 // for flock. |uma_events_file_| must exist already.
Luigi Semenzato31cda982014-05-19 08:30:42 -0700180 int chrome_fd = HANDLE_EINTR(open(uma_events_file_.c_str(),
Luigi Semenzatoa5db2202014-05-23 15:06:24 -0700181 O_WRONLY | O_APPEND));
Darin Petkov4fcb2ac2010-04-15 16:40:23 -0700182 // If we failed to open it, return.
Darin Petkov65b01462010-04-14 13:32:20 -0700183 if (chrome_fd < 0) {
Luigi Semenzato31cda982014-05-19 08:30:42 -0700184 PLOG(ERROR) << uma_events_file_ << ": open";
Darin Petkov4fcb2ac2010-04-15 16:40:23 -0700185 return false;
Darin Petkov65b01462010-04-14 13:32:20 -0700186 }
187
Darin Petkov4fcb2ac2010-04-15 16:40:23 -0700188 // Grab an exclusive lock to protect Chrome from truncating
Luigi Semenzato41c54502014-05-13 15:16:24 -0700189 // underneath us.
Darin Petkov8842c8c2011-02-24 12:48:30 -0800190 if (HANDLE_EINTR(flock(chrome_fd, LOCK_EX)) < 0) {
Luigi Semenzato31cda982014-05-19 08:30:42 -0700191 PLOG(ERROR) << uma_events_file_ << ": flock";
Mike Frysinger3e8a8512014-05-14 16:14:37 -0400192 IGNORE_EINTR(close(chrome_fd));
Darin Petkov4fcb2ac2010-04-15 16:40:23 -0700193 return false;
Darin Petkov65b01462010-04-14 13:32:20 -0700194 }
195
Darin Petkov4fcb2ac2010-04-15 16:40:23 -0700196 bool success = true;
Luigi Semenzato41c54502014-05-13 15:16:24 -0700197 if (WriteFileDescriptor(chrome_fd, message.c_str(), size) != size) {
Luigi Semenzato31cda982014-05-19 08:30:42 -0700198 PLOG(ERROR) << uma_events_file_ << ": write";
Darin Petkov4fcb2ac2010-04-15 16:40:23 -0700199 success = false;
200 }
Darin Petkov65b01462010-04-14 13:32:20 -0700201
Darin Petkov8842c8c2011-02-24 12:48:30 -0800202 // Close the file and release the lock.
Mike Frysinger3e8a8512014-05-14 16:14:37 -0400203 IGNORE_EINTR(close(chrome_fd));
Darin Petkov4fcb2ac2010-04-15 16:40:23 -0700204 return success;
205}
206
Luigi Semenzato41c54502014-05-13 15:16:24 -0700207const std::string MetricsLibrary::FormatChromeMessage(
208 const std::string& name,
209 const std::string& value) {
210 uint32 message_length =
211 sizeof(message_length) + name.size() + 1 + value.size() + 1;
212 std::string result;
213 result.reserve(message_length);
214 // Marshal the total message length in the native byte order.
215 result.assign(reinterpret_cast<char*>(&message_length),
216 sizeof(message_length));
217 result += name + '\0' + value + '\0';
218 return result;
Darin Petkov4fcb2ac2010-04-15 16:40:23 -0700219}
220
Darin Petkovfc91b422010-05-12 13:05:45 -0700221void MetricsLibrary::Init() {
Darin Petkov11b8eb32010-05-18 11:00:59 -0700222 uma_events_file_ = kUMAEventsPath;
Darin Petkovfc91b422010-05-12 13:05:45 -0700223}
224
Luigi Semenzato41c54502014-05-13 15:16:24 -0700225bool MetricsLibrary::SendToAutotest(const std::string& name, int value) {
David James3b3add52010-06-04 15:01:19 -0700226 FILE* autotest_file = fopen(kAutotestPath, "a+");
Darin Petkov4fcb2ac2010-04-15 16:40:23 -0700227 if (autotest_file == NULL) {
Luigi Semenzato41c54502014-05-13 15:16:24 -0700228 PLOG(ERROR) << kAutotestPath << ": fopen";
Darin Petkov4fcb2ac2010-04-15 16:40:23 -0700229 return false;
230 }
231
232 fprintf(autotest_file, "%s=%d\n", name.c_str(), value);
233 fclose(autotest_file);
234 return true;
235}
236
Luigi Semenzato41c54502014-05-13 15:16:24 -0700237bool MetricsLibrary::SendToUMA(const std::string& name,
238 int sample,
239 int min,
240 int max,
241 int nbuckets) {
Darin Petkov4fcb2ac2010-04-15 16:40:23 -0700242 // Format the message.
Luigi Semenzato41c54502014-05-13 15:16:24 -0700243 std::string value = base::StringPrintf("%s %d %d %d %d",
244 name.c_str(), sample, min, max, nbuckets);
245 std::string message = FormatChromeMessage("histogram", value);
Darin Petkov4fcb2ac2010-04-15 16:40:23 -0700246 // Send the message.
Luigi Semenzato41c54502014-05-13 15:16:24 -0700247 return SendMessageToChrome(message);
Darin Petkov65b01462010-04-14 13:32:20 -0700248}
Darin Petkov5b7dce12010-04-21 15:45:10 -0700249
Darin Petkov21cd2c52010-05-12 15:26:16 -0700250bool MetricsLibrary::SendEnumToUMA(const std::string& name, int sample,
251 int max) {
Darin Petkov5b7dce12010-04-21 15:45:10 -0700252 // Format the message.
Luigi Semenzato41c54502014-05-13 15:16:24 -0700253 std::string value = base::StringPrintf("%s %d %d", name.c_str(), sample, max);
254 std::string message = FormatChromeMessage("linearhistogram", value);
Darin Petkoved824852011-01-06 10:51:47 -0800255 // Send the message.
Luigi Semenzato41c54502014-05-13 15:16:24 -0700256 return SendMessageToChrome(message);
Darin Petkoved824852011-01-06 10:51:47 -0800257}
258
Luigi Semenzatoa7ebeb32013-03-19 15:02:42 -0700259bool MetricsLibrary::SendSparseToUMA(const std::string& name, int sample) {
260 // Format the message.
Luigi Semenzato41c54502014-05-13 15:16:24 -0700261 std::string value = base::StringPrintf("%s %d", name.c_str(), sample);
262 std::string message = FormatChromeMessage("sparsehistogram", value);
Luigi Semenzatoa7ebeb32013-03-19 15:02:42 -0700263 // Send the message.
Luigi Semenzato41c54502014-05-13 15:16:24 -0700264 return SendMessageToChrome(message);
Luigi Semenzatoa7ebeb32013-03-19 15:02:42 -0700265}
266
Darin Petkoved824852011-01-06 10:51:47 -0800267bool MetricsLibrary::SendUserActionToUMA(const std::string& action) {
268 // Format the message.
Luigi Semenzato41c54502014-05-13 15:16:24 -0700269 std::string message = FormatChromeMessage("useraction", action);
Darin Petkov5b7dce12010-04-21 15:45:10 -0700270 // Send the message.
Luigi Semenzato41c54502014-05-13 15:16:24 -0700271 return SendMessageToChrome(message);
Darin Petkov5b7dce12010-04-21 15:45:10 -0700272}
Ken Mixterbe2e13b2011-01-22 06:15:56 -0800273
274bool MetricsLibrary::SendCrashToUMA(const char *crash_kind) {
275 // Format the message.
Luigi Semenzato41c54502014-05-13 15:16:24 -0700276 std::string message = FormatChromeMessage("crash", crash_kind);
Ken Mixterbe2e13b2011-01-22 06:15:56 -0800277 // Send the message.
Luigi Semenzato41c54502014-05-13 15:16:24 -0700278 return SendMessageToChrome(message);
Ken Mixterbe2e13b2011-01-22 06:15:56 -0800279}
Ken Mixterb2f17092011-07-22 14:59:51 -0700280
281void MetricsLibrary::SetPolicyProvider(policy::PolicyProvider* provider) {
282 policy_provider_.reset(provider);
283}
Luigi Semenzato32684222013-03-13 10:53:55 -0700284
285bool MetricsLibrary::SendCrosEventToUMA(const std::string& event) {
Chih-Chung Chang6844c062013-04-01 14:27:39 +0800286 for (size_t i = 0; i < ARRAY_SIZE(kCrosEventNames); i++) {
287 if (strcmp(event.c_str(), kCrosEventNames[i]) == 0) {
288 return SendEnumToUMA(kCrosEventHistogramName, i, kCrosEventHistogramMax);
289 }
Luigi Semenzato32684222013-03-13 10:53:55 -0700290 }
Chih-Chung Chang6844c062013-04-01 14:27:39 +0800291 return false;
Luigi Semenzato32684222013-03-13 10:53:55 -0700292}