blob: e93c9a8181d81cb576f27f49e42f067e8256041e [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
5#include "metrics_daemon.h"
Darin Petkov65b01462010-04-14 13:32:20 -07006
Darin Petkov703ec972010-04-27 11:02:18 -07007#include <dbus/dbus-glib-lowlevel.h>
Darin Petkov65b01462010-04-14 13:32:20 -07008
9#include <base/logging.h>
10
Darin Petkovf1e85e42010-06-10 15:59:53 -070011#include "counter.h"
12
Darin Petkovf27f0362010-06-04 13:14:19 -070013using base::Time;
14using base::TimeDelta;
15using base::TimeTicks;
16
Darin Petkov703ec972010-04-27 11:02:18 -070017#define SAFE_MESSAGE(e) (e.message ? e.message : "unknown error")
Darin Petkove3348402010-06-04 14:07:41 -070018#define DBUS_IFACE_FLIMFLAM_MANAGER "org.chromium.flimflam.Manager"
David James6bf6e252010-06-06 18:52:40 -070019#define DBUS_IFACE_POWER_MANAGER "org.chromium.PowerManager"
Darin Petkov41e06232010-05-03 16:45:37 -070020#define DBUS_IFACE_SESSION_MANAGER "org.chromium.SessionManagerInterface"
21
22// File to aggregate daily usage before sending to UMA.
23// TODO(petkov): This file should probably live in a user-specific stateful
24// location, e.g., /home/chronos/user.
25static const char kDailyUseRecordFile[] = "/var/log/metrics/daily-usage";
26
27static const int kSecondsPerMinute = 60;
28static const int kMinutesPerHour = 60;
29static const int kHoursPerDay = 24;
30static const int kMinutesPerDay = kHoursPerDay * kMinutesPerHour;
Darin Petkov41e06232010-05-03 16:45:37 -070031
32// The daily use monitor is scheduled to a 1-minute interval after
33// initial user activity and then it's exponentially backed off to
34// 10-minute intervals. Although not required, the back off is
35// implemented because the histogram buckets are spaced exponentially
36// anyway and to avoid too frequent metrics daemon process wake-ups
37// and file I/O.
38static const int kUseMonitorIntervalInit = 1 * kSecondsPerMinute;
39static const int kUseMonitorIntervalMax = 10 * kSecondsPerMinute;
Darin Petkov65b01462010-04-14 13:32:20 -070040
Darin Petkov2ccef012010-05-05 16:06:37 -070041// static metrics parameters.
42const char MetricsDaemon::kMetricDailyUseTimeName[] =
43 "Logging.DailyUseTime";
44const int MetricsDaemon::kMetricDailyUseTimeMin = 1;
45const int MetricsDaemon::kMetricDailyUseTimeMax = kMinutesPerDay;
46const int MetricsDaemon::kMetricDailyUseTimeBuckets = 50;
47
48const char MetricsDaemon::kMetricTimeToNetworkDropName[] =
49 "Network.TimeToDrop";
50const int MetricsDaemon::kMetricTimeToNetworkDropMin = 1;
51const int MetricsDaemon::kMetricTimeToNetworkDropMax =
52 8 /* hours */ * kMinutesPerHour * kSecondsPerMinute;
53const int MetricsDaemon::kMetricTimeToNetworkDropBuckets = 50;
54
Darin Petkov703ec972010-04-27 11:02:18 -070055// static
Darin Petkov41e06232010-05-03 16:45:37 -070056const char* MetricsDaemon::kDBusMatches_[] = {
Darin Petkov703ec972010-04-27 11:02:18 -070057 "type='signal',"
Darin Petkove3348402010-06-04 14:07:41 -070058 "sender='org.chromium.flimflam',"
59 "interface='" DBUS_IFACE_FLIMFLAM_MANAGER "',"
Darin Petkov703ec972010-04-27 11:02:18 -070060 "path='/',"
61 "member='StateChanged'",
62
63 "type='signal',"
64 "interface='" DBUS_IFACE_POWER_MANAGER "',"
Benson Leung53faeb02010-06-08 15:59:13 -070065 "path='/'",
Darin Petkov41e06232010-05-03 16:45:37 -070066
67 "type='signal',"
68 "sender='org.chromium.SessionManager',"
69 "interface='" DBUS_IFACE_SESSION_MANAGER "',"
70 "path='/org/chromium/SessionManager',"
71 "member='SessionStateChanged'",
Darin Petkov703ec972010-04-27 11:02:18 -070072};
73
74// static
Darin Petkov41e06232010-05-03 16:45:37 -070075const char* MetricsDaemon::kNetworkStates_[] = {
Darin Petkov703ec972010-04-27 11:02:18 -070076#define STATE(name, capname) #name,
Darin Petkov65b01462010-04-14 13:32:20 -070077#include "network_states.h"
78};
79
Darin Petkov703ec972010-04-27 11:02:18 -070080// static
Darin Petkov41e06232010-05-03 16:45:37 -070081const char* MetricsDaemon::kPowerStates_[] = {
Darin Petkov703ec972010-04-27 11:02:18 -070082#define STATE(name, capname) #name,
83#include "power_states.h"
84};
85
Darin Petkov41e06232010-05-03 16:45:37 -070086// static
Darin Petkov41e06232010-05-03 16:45:37 -070087const char* MetricsDaemon::kSessionStates_[] = {
88#define STATE(name, capname) #name,
89#include "session_states.h"
90};
91
Darin Petkovf1e85e42010-06-10 15:59:53 -070092MetricsDaemon::MetricsDaemon()
93 : network_state_(kUnknownNetworkState),
94 power_state_(kUnknownPowerState),
95 session_state_(kUnknownSessionState),
96 user_active_(false),
97 usemon_interval_(0),
98 usemon_source_(NULL) {}
99
100MetricsDaemon::~MetricsDaemon() {}
101
Darin Petkov2ccef012010-05-05 16:06:37 -0700102void MetricsDaemon::Run(bool run_as_daemon) {
Darin Petkov65b01462010-04-14 13:32:20 -0700103 if (!run_as_daemon || daemon(0, 0) == 0) {
104 Loop();
105 }
106}
107
Darin Petkovfc91b422010-05-12 13:05:45 -0700108void MetricsDaemon::Init(bool testing, MetricsLibraryInterface* metrics_lib) {
Darin Petkov65b01462010-04-14 13:32:20 -0700109 testing_ = testing;
Darin Petkovfc91b422010-05-12 13:05:45 -0700110 DCHECK(metrics_lib != NULL);
111 metrics_lib_ = metrics_lib;
Darin Petkovf1e85e42010-06-10 15:59:53 -0700112 daily_use_.reset(new chromeos_metrics::TaggedCounter());
113 daily_use_->Init(kDailyUseRecordFile, &DailyUseReporter, this);
Darin Petkov2ccef012010-05-05 16:06:37 -0700114
115 // Don't setup D-Bus and GLib in test mode.
116 if (testing)
117 return;
Darin Petkov65b01462010-04-14 13:32:20 -0700118
Darin Petkov703ec972010-04-27 11:02:18 -0700119 g_thread_init(NULL);
120 g_type_init();
121 dbus_g_thread_init();
Darin Petkov65b01462010-04-14 13:32:20 -0700122
Darin Petkov703ec972010-04-27 11:02:18 -0700123 DBusError error;
124 dbus_error_init(&error);
Darin Petkov65b01462010-04-14 13:32:20 -0700125
David James3b3add52010-06-04 15:01:19 -0700126 DBusConnection* connection = dbus_bus_get(DBUS_BUS_SYSTEM, &error);
Darin Petkov703ec972010-04-27 11:02:18 -0700127 LOG_IF(FATAL, dbus_error_is_set(&error)) <<
128 "No D-Bus connection: " << SAFE_MESSAGE(error);
Darin Petkov65b01462010-04-14 13:32:20 -0700129
Darin Petkov703ec972010-04-27 11:02:18 -0700130 dbus_connection_setup_with_g_main(connection, NULL);
Darin Petkov65b01462010-04-14 13:32:20 -0700131
Darin Petkov703ec972010-04-27 11:02:18 -0700132 // Registers D-Bus matches for the signals we would like to catch.
David James3b3add52010-06-04 15:01:19 -0700133 for (unsigned int m = 0; m < sizeof(kDBusMatches_) / sizeof(char*); m++) {
Darin Petkov41e06232010-05-03 16:45:37 -0700134 const char* match = kDBusMatches_[m];
135 DLOG(INFO) << "adding dbus match: " << match;
Darin Petkov703ec972010-04-27 11:02:18 -0700136 dbus_bus_add_match(connection, match, &error);
137 LOG_IF(FATAL, dbus_error_is_set(&error)) <<
138 "unable to add a match: " << SAFE_MESSAGE(error);
139 }
140
141 // Adds the D-Bus filter routine to be called back whenever one of
142 // the registered D-Bus matches is successful. The daemon is not
143 // activated for D-Bus messages that don't match.
144 CHECK(dbus_connection_add_filter(connection, MessageFilter, this, NULL));
Darin Petkov65b01462010-04-14 13:32:20 -0700145}
146
147void MetricsDaemon::Loop() {
Darin Petkov703ec972010-04-27 11:02:18 -0700148 GMainLoop* loop = g_main_loop_new(NULL, false);
149 g_main_loop_run(loop);
Darin Petkov65b01462010-04-14 13:32:20 -0700150}
151
Darin Petkov703ec972010-04-27 11:02:18 -0700152// static
153DBusHandlerResult MetricsDaemon::MessageFilter(DBusConnection* connection,
154 DBusMessage* message,
155 void* user_data) {
Darin Petkovf27f0362010-06-04 13:14:19 -0700156 Time now = Time::Now();
157 TimeTicks ticks = TimeTicks::Now();
158 DLOG(INFO) << "message intercepted @ " << now.ToInternalValue();
Darin Petkov703ec972010-04-27 11:02:18 -0700159
160 int message_type = dbus_message_get_type(message);
161 if (message_type != DBUS_MESSAGE_TYPE_SIGNAL) {
Darin Petkov41e06232010-05-03 16:45:37 -0700162 DLOG(WARNING) << "unexpected message type " << message_type;
Darin Petkov703ec972010-04-27 11:02:18 -0700163 return DBUS_HANDLER_RESULT_NOT_YET_HANDLED;
164 }
165
166 // Signal messages always have interfaces.
167 const char* interface = dbus_message_get_interface(message);
168 CHECK(interface != NULL);
169
170 MetricsDaemon* daemon = static_cast<MetricsDaemon*>(user_data);
171
172 DBusMessageIter iter;
173 dbus_message_iter_init(message, &iter);
Darin Petkove3348402010-06-04 14:07:41 -0700174 if (strcmp(interface, DBUS_IFACE_FLIMFLAM_MANAGER) == 0) {
Darin Petkov41e06232010-05-03 16:45:37 -0700175 CHECK(strcmp(dbus_message_get_member(message),
176 "StateChanged") == 0);
Darin Petkov703ec972010-04-27 11:02:18 -0700177
David James3b3add52010-06-04 15:01:19 -0700178 char* state_name;
Darin Petkov703ec972010-04-27 11:02:18 -0700179 dbus_message_iter_get_basic(&iter, &state_name);
Darin Petkovf27f0362010-06-04 13:14:19 -0700180 daemon->NetStateChanged(state_name, ticks);
Darin Petkov703ec972010-04-27 11:02:18 -0700181 } else if (strcmp(interface, DBUS_IFACE_POWER_MANAGER) == 0) {
David James6bf6e252010-06-06 18:52:40 -0700182 const char* member = dbus_message_get_member(message);
183 if (strcmp(member, "ScreenIsLocked") == 0) {
184 daemon->SetUserActiveState(false, now);
185 } else if (strcmp(member, "ScreenIsUnlocked") == 0) {
186 daemon->SetUserActiveState(true, now);
187 } else if (strcmp(member, "PowerStateChanged") == 0) {
188 char* state_name;
189 dbus_message_iter_get_basic(&iter, &state_name);
190 daemon->PowerStateChanged(state_name, now);
191 }
Darin Petkov41e06232010-05-03 16:45:37 -0700192 } else if (strcmp(interface, DBUS_IFACE_SESSION_MANAGER) == 0) {
193 CHECK(strcmp(dbus_message_get_member(message),
194 "SessionStateChanged") == 0);
195
David James3b3add52010-06-04 15:01:19 -0700196 char* state_name;
Darin Petkov41e06232010-05-03 16:45:37 -0700197 dbus_message_iter_get_basic(&iter, &state_name);
198 daemon->SessionStateChanged(state_name, now);
Darin Petkov703ec972010-04-27 11:02:18 -0700199 } else {
Darin Petkov41e06232010-05-03 16:45:37 -0700200 DLOG(WARNING) << "unexpected interface: " << interface;
Darin Petkov703ec972010-04-27 11:02:18 -0700201 return DBUS_HANDLER_RESULT_NOT_YET_HANDLED;
202 }
203
204 return DBUS_HANDLER_RESULT_HANDLED;
Darin Petkov65b01462010-04-14 13:32:20 -0700205}
206
Darin Petkovf27f0362010-06-04 13:14:19 -0700207void MetricsDaemon::NetStateChanged(const char* state_name, TimeTicks ticks) {
Darin Petkov41e06232010-05-03 16:45:37 -0700208 DLOG(INFO) << "network state: " << state_name;
Darin Petkov703ec972010-04-27 11:02:18 -0700209
Darin Petkov703ec972010-04-27 11:02:18 -0700210 NetworkState state = LookupNetworkState(state_name);
211
212 // Logs the time in seconds between the network going online to
Darin Petkov2ccef012010-05-05 16:06:37 -0700213 // going offline (or, more precisely, going not online) in order to
214 // measure the mean time to network dropping. Going offline as part
215 // of suspend-to-RAM is not logged as network drop -- the assumption
216 // is that the message for suspend-to-RAM comes before the network
217 // offline message which seems to and should be the case.
218 if (state != kNetworkStateOnline &&
Darin Petkov703ec972010-04-27 11:02:18 -0700219 network_state_ == kNetworkStateOnline &&
220 power_state_ != kPowerStateMem) {
Darin Petkovf27f0362010-06-04 13:14:19 -0700221 TimeDelta since_online = ticks - network_state_last_;
222 int online_time = static_cast<int>(since_online.InSeconds());
Darin Petkov11b8eb32010-05-18 11:00:59 -0700223 SendMetric(kMetricTimeToNetworkDropName, online_time,
224 kMetricTimeToNetworkDropMin,
225 kMetricTimeToNetworkDropMax,
226 kMetricTimeToNetworkDropBuckets);
Darin Petkov65b01462010-04-14 13:32:20 -0700227 }
228
Darin Petkov703ec972010-04-27 11:02:18 -0700229 network_state_ = state;
Darin Petkovf27f0362010-06-04 13:14:19 -0700230 network_state_last_ = ticks;
Darin Petkov65b01462010-04-14 13:32:20 -0700231}
232
Darin Petkov703ec972010-04-27 11:02:18 -0700233MetricsDaemon::NetworkState
234MetricsDaemon::LookupNetworkState(const char* state_name) {
Darin Petkov65b01462010-04-14 13:32:20 -0700235 for (int i = 0; i < kNumberNetworkStates; i++) {
Darin Petkov41e06232010-05-03 16:45:37 -0700236 if (strcmp(state_name, kNetworkStates_[i]) == 0) {
Darin Petkov703ec972010-04-27 11:02:18 -0700237 return static_cast<NetworkState>(i);
Darin Petkov65b01462010-04-14 13:32:20 -0700238 }
239 }
Darin Petkov41e06232010-05-03 16:45:37 -0700240 DLOG(WARNING) << "unknown network connection state: " << state_name;
Darin Petkov703ec972010-04-27 11:02:18 -0700241 return kUnknownNetworkState;
242}
243
Darin Petkovf27f0362010-06-04 13:14:19 -0700244void MetricsDaemon::PowerStateChanged(const char* state_name, Time now) {
Darin Petkov41e06232010-05-03 16:45:37 -0700245 DLOG(INFO) << "power state: " << state_name;
Darin Petkov703ec972010-04-27 11:02:18 -0700246 power_state_ = LookupPowerState(state_name);
Darin Petkov41e06232010-05-03 16:45:37 -0700247
248 if (power_state_ != kPowerStateOn)
249 SetUserActiveState(false, now);
Darin Petkov703ec972010-04-27 11:02:18 -0700250}
251
252MetricsDaemon::PowerState
253MetricsDaemon::LookupPowerState(const char* state_name) {
254 for (int i = 0; i < kNumberPowerStates; i++) {
Darin Petkov41e06232010-05-03 16:45:37 -0700255 if (strcmp(state_name, kPowerStates_[i]) == 0) {
Darin Petkov703ec972010-04-27 11:02:18 -0700256 return static_cast<PowerState>(i);
257 }
258 }
Darin Petkov41e06232010-05-03 16:45:37 -0700259 DLOG(WARNING) << "unknown power state: " << state_name;
Darin Petkov703ec972010-04-27 11:02:18 -0700260 return kUnknownPowerState;
Darin Petkov65b01462010-04-14 13:32:20 -0700261}
262
Darin Petkovf27f0362010-06-04 13:14:19 -0700263void MetricsDaemon::SessionStateChanged(const char* state_name, Time now) {
Darin Petkov41e06232010-05-03 16:45:37 -0700264 DLOG(INFO) << "user session state: " << state_name;
265 session_state_ = LookupSessionState(state_name);
266 SetUserActiveState(session_state_ == kSessionStateStarted, now);
267}
268
269MetricsDaemon::SessionState
270MetricsDaemon::LookupSessionState(const char* state_name) {
271 for (int i = 0; i < kNumberSessionStates; i++) {
272 if (strcmp(state_name, kSessionStates_[i]) == 0) {
273 return static_cast<SessionState>(i);
274 }
275 }
276 DLOG(WARNING) << "unknown user session state: " << state_name;
277 return kUnknownSessionState;
278}
279
Darin Petkovf27f0362010-06-04 13:14:19 -0700280void MetricsDaemon::SetUserActiveState(bool active, Time now) {
Darin Petkov41e06232010-05-03 16:45:37 -0700281 DLOG(INFO) << "user: " << (active ? "active" : "inactive");
282
283 // Calculates the seconds of active use since the last update and
Darin Petkovf27f0362010-06-04 13:14:19 -0700284 // the day since Epoch, and logs the usage data. Guards against the
285 // time jumping back and forth due to the user changing it by
286 // discarding the new use time.
287 int seconds = 0;
288 if (user_active_ && now > user_active_last_) {
289 TimeDelta since_active = now - user_active_last_;
290 if (since_active < TimeDelta::FromSeconds(
291 kUseMonitorIntervalMax + kSecondsPerMinute)) {
292 seconds = static_cast<int>(since_active.InSeconds());
293 }
294 }
295 TimeDelta since_epoch = now - Time();
296 int day = since_epoch.InDays();
Darin Petkovf1e85e42010-06-10 15:59:53 -0700297 daily_use_->Update(day, seconds);
Darin Petkov41e06232010-05-03 16:45:37 -0700298
299 // Schedules a use monitor on inactive->active transitions and
300 // unschedules it on active->inactive transitions.
301 if (!user_active_ && active)
302 ScheduleUseMonitor(kUseMonitorIntervalInit, /* backoff */ false);
303 else if (user_active_ && !active)
304 UnscheduleUseMonitor();
305
306 // Remembers the current active state and the time of the last
307 // activity update.
308 user_active_ = active;
309 user_active_last_ = now;
310}
311
Darin Petkov41e06232010-05-03 16:45:37 -0700312// static
313gboolean MetricsDaemon::UseMonitorStatic(gpointer data) {
314 return static_cast<MetricsDaemon*>(data)->UseMonitor() ? TRUE : FALSE;
315}
316
317bool MetricsDaemon::UseMonitor() {
Darin Petkovf27f0362010-06-04 13:14:19 -0700318 SetUserActiveState(user_active_, Time::Now());
Darin Petkov41e06232010-05-03 16:45:37 -0700319
320 // If a new monitor source/instance is scheduled, returns false to
321 // tell GLib to destroy this monitor source/instance. Returns true
322 // otherwise to keep calling back this monitor.
323 return !ScheduleUseMonitor(usemon_interval_ * 2, /* backoff */ true);
324}
325
326bool MetricsDaemon::ScheduleUseMonitor(int interval, bool backoff)
327{
Darin Petkov2ccef012010-05-05 16:06:37 -0700328 if (testing_)
329 return false;
330
Darin Petkov41e06232010-05-03 16:45:37 -0700331 // Caps the interval -- the bigger the interval, the more active use
332 // time will be potentially dropped on system shutdown.
333 if (interval > kUseMonitorIntervalMax)
334 interval = kUseMonitorIntervalMax;
335
336 if (backoff) {
337 // Back-off mode is used by the use monitor to reschedule itself
338 // with exponential back-off in time. This mode doesn't create a
339 // new timeout source if the new interval is the same as the old
340 // one. Also, if a new timeout source is created, the old one is
341 // not destroyed explicitly here -- it will be destroyed by GLib
342 // when the monitor returns FALSE (see UseMonitor and
343 // UseMonitorStatic).
344 if (interval == usemon_interval_)
345 return false;
346 } else {
347 UnscheduleUseMonitor();
348 }
349
350 // Schedules a new use monitor for |interval| seconds from now.
351 DLOG(INFO) << "scheduling use monitor in " << interval << " seconds";
352 usemon_source_ = g_timeout_source_new_seconds(interval);
353 g_source_set_callback(usemon_source_, UseMonitorStatic, this,
354 NULL); // No destroy notification.
355 g_source_attach(usemon_source_,
356 NULL); // Default context.
357 usemon_interval_ = interval;
358 return true;
359}
360
361void MetricsDaemon::UnscheduleUseMonitor() {
362 // If there's a use monitor scheduled already, destroys it.
363 if (usemon_source_ == NULL)
364 return;
365
366 DLOG(INFO) << "destroying use monitor";
367 g_source_destroy(usemon_source_);
368 usemon_source_ = NULL;
369 usemon_interval_ = 0;
370}
371
Darin Petkovf1e85e42010-06-10 15:59:53 -0700372// static
373void MetricsDaemon::DailyUseReporter(void* handle, int tag, int count) {
374 MetricsDaemon* daemon = static_cast<MetricsDaemon*>(handle);
375 int minutes = (count + kSecondsPerMinute / 2) / kSecondsPerMinute;
376 daemon->SendMetric(kMetricDailyUseTimeName, minutes,
377 kMetricDailyUseTimeMin,
378 kMetricDailyUseTimeMax,
379 kMetricDailyUseTimeBuckets);
380}
381
Darin Petkov11b8eb32010-05-18 11:00:59 -0700382void MetricsDaemon::SendMetric(const std::string& name, int sample,
383 int min, int max, int nbuckets) {
Darin Petkovfc91b422010-05-12 13:05:45 -0700384 DLOG(INFO) << "received metric: " << name << " " << sample << " "
385 << min << " " << max << " " << nbuckets;
386 metrics_lib_->SendToUMA(name, sample, min, max, nbuckets);
Darin Petkov65b01462010-04-14 13:32:20 -0700387}