blob: 68646bcb206e0ba6f9494d2483d24c685d0700ed [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#ifndef METRICS_DAEMON_H_
6#define METRICS_DAEMON_H_
7
Darin Petkov703ec972010-04-27 11:02:18 -07008#include <dbus/dbus.h>
Darin Petkov41e06232010-05-03 16:45:37 -07009#include <glib.h>
Ken Mixter4c5daa42010-08-26 18:35:06 -070010#include <map>
Darin Petkov65b01462010-04-14 13:32:20 -070011
Ken Mixter4c5daa42010-08-26 18:35:06 -070012#include <base/file_path.h>
Chris Masone817016a2011-05-12 14:14:48 -070013#include <base/memory/scoped_ptr.h>
Darin Petkovf1e85e42010-06-10 15:59:53 -070014#include <base/time.h>
15#include <gtest/gtest_prod.h> // for FRIEND_TEST
16
Darin Petkovfc91b422010-05-12 13:05:45 -070017#include "metrics_library.h"
18
Ken Mixterccd84c02010-08-16 19:57:13 -070019namespace chromeos_metrics {
20class FrequencyCounter;
Ken Mixter4c5daa42010-08-26 18:35:06 -070021class TaggedCounter;
22class TaggedCounterReporter;
Ken Mixterccd84c02010-08-16 19:57:13 -070023}
Darin Petkov2ccef012010-05-05 16:06:37 -070024
Darin Petkov65b01462010-04-14 13:32:20 -070025class MetricsDaemon {
26
27 public:
Darin Petkovf1e85e42010-06-10 15:59:53 -070028 MetricsDaemon();
29 ~MetricsDaemon();
Darin Petkov65b01462010-04-14 13:32:20 -070030
Darin Petkov11b8eb32010-05-18 11:00:59 -070031 // Initializes.
Luigi Semenzatoc88e42d2011-02-17 10:21:16 -080032 void Init(bool testing, MetricsLibraryInterface* metrics_lib,
Luigi Semenzato8accd332011-05-17 16:37:18 -070033 const std::string& diskstats_path);
Darin Petkov11b8eb32010-05-18 11:00:59 -070034
Darin Petkov703ec972010-04-27 11:02:18 -070035 // Does all the work. If |run_as_daemon| is true, daemonizes by
Darin Petkov2ccef012010-05-05 16:06:37 -070036 // forking.
37 void Run(bool run_as_daemon);
Darin Petkov65b01462010-04-14 13:32:20 -070038
39 private:
Darin Petkov2ccef012010-05-05 16:06:37 -070040 friend class MetricsDaemonTest;
Ken Mixterccd84c02010-08-16 19:57:13 -070041 FRIEND_TEST(MetricsDaemonTest, CheckSystemCrash);
Ken Mixter4c5daa42010-08-26 18:35:06 -070042 FRIEND_TEST(MetricsDaemonTest, ComputeEpochNoCurrent);
43 FRIEND_TEST(MetricsDaemonTest, ComputeEpochNoLast);
44 FRIEND_TEST(MetricsDaemonTest, GetHistogramPath);
45 FRIEND_TEST(MetricsDaemonTest, IsNewEpoch);
Darin Petkov2ccef012010-05-05 16:06:37 -070046 FRIEND_TEST(MetricsDaemonTest, LookupPowerState);
47 FRIEND_TEST(MetricsDaemonTest, LookupScreenSaverState);
48 FRIEND_TEST(MetricsDaemonTest, LookupSessionState);
Darin Petkove579d662010-05-05 16:19:39 -070049 FRIEND_TEST(MetricsDaemonTest, MessageFilter);
Darin Petkov2ccef012010-05-05 16:06:37 -070050 FRIEND_TEST(MetricsDaemonTest, PowerStateChanged);
Darin Petkov38d5cb02010-06-24 12:10:26 -070051 FRIEND_TEST(MetricsDaemonTest, ProcessKernelCrash);
Luigi Semenzato29c7ef92011-04-12 14:12:35 -070052 FRIEND_TEST(MetricsDaemonTest, ProcessMeminfo);
53 FRIEND_TEST(MetricsDaemonTest, ProcessMeminfo2);
Ken Mixterccd84c02010-08-16 19:57:13 -070054 FRIEND_TEST(MetricsDaemonTest, ProcessUncleanShutdown);
Darin Petkov1bb904e2010-06-16 15:58:06 -070055 FRIEND_TEST(MetricsDaemonTest, ProcessUserCrash);
Ken Mixterccd84c02010-08-16 19:57:13 -070056 FRIEND_TEST(MetricsDaemonTest, ReportCrashesDailyFrequency);
57 FRIEND_TEST(MetricsDaemonTest, ReportDailyUse);
Luigi Semenzatoc88e42d2011-02-17 10:21:16 -080058 FRIEND_TEST(MetricsDaemonTest, ReportDiskStats);
Ken Mixterccd84c02010-08-16 19:57:13 -070059 FRIEND_TEST(MetricsDaemonTest, ReportKernelCrashInterval);
60 FRIEND_TEST(MetricsDaemonTest, ReportUncleanShutdownInterval);
61 FRIEND_TEST(MetricsDaemonTest, ReportUserCrashInterval);
Darin Petkov2ccef012010-05-05 16:06:37 -070062 FRIEND_TEST(MetricsDaemonTest, ScreenSaverStateChanged);
Darin Petkov11b8eb32010-05-18 11:00:59 -070063 FRIEND_TEST(MetricsDaemonTest, SendMetric);
Darin Petkov2ccef012010-05-05 16:06:37 -070064 FRIEND_TEST(MetricsDaemonTest, SessionStateChanged);
Darin Petkovf1e85e42010-06-10 15:59:53 -070065 FRIEND_TEST(MetricsDaemonTest, SetUserActiveState);
Darin Petkovf27f0362010-06-04 13:14:19 -070066 FRIEND_TEST(MetricsDaemonTest, SetUserActiveStateTimeJump);
Darin Petkov2ccef012010-05-05 16:06:37 -070067
Darin Petkov703ec972010-04-27 11:02:18 -070068 // The power states (see power_states.h).
69 enum PowerState {
70 kUnknownPowerState = -1, // Initial/unknown power state.
71#define STATE(name, capname) kPowerState ## capname,
72#include "power_states.h"
73 kNumberPowerStates
74 };
Darin Petkov65b01462010-04-14 13:32:20 -070075
Darin Petkov41e06232010-05-03 16:45:37 -070076 // The user session states (see session_states.h).
77 enum SessionState {
78 kUnknownSessionState = -1, // Initial/unknown user session state.
79#define STATE(name, capname) kSessionState ## capname,
80#include "session_states.h"
81 kNumberSessionStates
82 };
83
Luigi Semenzatoc88e42d2011-02-17 10:21:16 -080084 // State for disk stats collector callback.
85 enum DiskStatsState {
86 kDiskStatsShort, // short wait before short interval collection
87 kDiskStatsLong, // final wait before new collection
88 };
89
Darin Petkov41e06232010-05-03 16:45:37 -070090 // Data record for aggregating daily usage.
91 class UseRecord {
92 public:
93 UseRecord() : day_(0), seconds_(0) {}
94 int day_;
95 int seconds_;
96 };
97
Luigi Semenzato8accd332011-05-17 16:37:18 -070098 // Record for retrieving and reporting values from /proc/meminfo.
99 struct MeminfoRecord {
100 const char* name; // print name
101 const char* match; // string to match in output of /proc/meminfo
102 int log_scale; // report with log scale instead of linear percent
103 int value; // value from /proc/meminfo
104 };
105
Ken Mixter4c5daa42010-08-26 18:35:06 -0700106 typedef std::map<std::string, chromeos_metrics::FrequencyCounter*>
107 FrequencyCounters;
108
Darin Petkov2ccef012010-05-05 16:06:37 -0700109 // Metric parameters.
Ken Mixterccd84c02010-08-16 19:57:13 -0700110 static const char kMetricAnyCrashesDailyName[];
Ken Mixter4c5daa42010-08-26 18:35:06 -0700111 static const char kMetricAnyCrashesWeeklyName[];
112 static const char kMetricCrashFrequencyBuckets;
113 static const char kMetricCrashFrequencyMax;
114 static const char kMetricCrashFrequencyMin;
Ken Mixterccd84c02010-08-16 19:57:13 -0700115 static const int kMetricCrashIntervalBuckets;
116 static const int kMetricCrashIntervalMax;
117 static const int kMetricCrashIntervalMin;
118 static const int kMetricDailyUseTimeBuckets;
119 static const int kMetricDailyUseTimeMax;
120 static const int kMetricDailyUseTimeMin;
Darin Petkov2ccef012010-05-05 16:06:37 -0700121 static const char kMetricDailyUseTimeName[];
Ken Mixterccd84c02010-08-16 19:57:13 -0700122 static const char kMetricKernelCrashesDailyName[];
Ken Mixter4c5daa42010-08-26 18:35:06 -0700123 static const char kMetricKernelCrashesWeeklyName[];
Darin Petkov38d5cb02010-06-24 12:10:26 -0700124 static const char kMetricKernelCrashIntervalName[];
Ken Mixter4c5daa42010-08-26 18:35:06 -0700125 static const char kMetricsPath[];
Ken Mixterccd84c02010-08-16 19:57:13 -0700126 static const char kMetricUncleanShutdownIntervalName[];
127 static const char kMetricUncleanShutdownsDailyName[];
Ken Mixter4c5daa42010-08-26 18:35:06 -0700128 static const char kMetricUncleanShutdownsWeeklyName[];
Ken Mixterccd84c02010-08-16 19:57:13 -0700129 static const char kMetricUserCrashesDailyName[];
Ken Mixter4c5daa42010-08-26 18:35:06 -0700130 static const char kMetricUserCrashesWeeklyName[];
Darin Petkov1bb904e2010-06-16 15:58:06 -0700131 static const char kMetricUserCrashIntervalName[];
Luigi Semenzatoc88e42d2011-02-17 10:21:16 -0800132 static const char kMetricReadSectorsLongName[];
133 static const char kMetricReadSectorsShortName[];
134 static const char kMetricWriteSectorsLongName[];
135 static const char kMetricWriteSectorsShortName[];
136 static const int kMetricDiskStatsShortInterval;
137 static const int kMetricDiskStatsLongInterval;
Luigi Semenzato29c7ef92011-04-12 14:12:35 -0700138 static const int kMetricMeminfoInterval;
Luigi Semenzatoc88e42d2011-02-17 10:21:16 -0800139 static const int kMetricSectorsIOMax;
140 static const int kMetricSectorsBuckets;
141 static const char kMetricsDiskStatsPath[];
Darin Petkov2ccef012010-05-05 16:06:37 -0700142
Darin Petkov41e06232010-05-03 16:45:37 -0700143 // D-Bus message match strings.
144 static const char* kDBusMatches_[];
145
Darin Petkov41e06232010-05-03 16:45:37 -0700146 // Array of power states.
147 static const char* kPowerStates_[kNumberPowerStates];
148
Darin Petkov41e06232010-05-03 16:45:37 -0700149 // Array of user session states.
150 static const char* kSessionStates_[kNumberSessionStates];
151
Luigi Semenzato8accd332011-05-17 16:37:18 -0700152 // Returns the active time since boot (uptime minus sleep time) in seconds.
153 double GetActiveTime();
154
Ken Mixter4c5daa42010-08-26 18:35:06 -0700155 // Clears and deletes the data contained in frequency_counters_.
156 void DeleteFrequencyCounters();
157
158 // Configures the given crash interval reporter.
159 void ConfigureCrashIntervalReporter(
160 const char* histogram_name,
161 scoped_ptr<chromeos_metrics::TaggedCounterReporter>* reporter);
162
163 // Configures the given frequency counter reporter.
164 void ConfigureCrashFrequencyReporter(const char* histogram_name);
165
166 // Returns file path to persistent file for generating given histogram.
167 FilePath GetHistogramPath(const char* histogram_name);
168
Darin Petkov65b01462010-04-14 13:32:20 -0700169 // Creates the event loop and enters it.
170 void Loop();
171
Darin Petkov703ec972010-04-27 11:02:18 -0700172 // D-Bus filter callback.
173 static DBusHandlerResult MessageFilter(DBusConnection* connection,
174 DBusMessage* message,
175 void* user_data);
Darin Petkov65b01462010-04-14 13:32:20 -0700176
Darin Petkov703ec972010-04-27 11:02:18 -0700177 // Processes power state change.
Darin Petkovf27f0362010-06-04 13:14:19 -0700178 void PowerStateChanged(const char* state_name, base::Time now);
Darin Petkov703ec972010-04-27 11:02:18 -0700179
180 // Given the state name, returns the state id.
181 PowerState LookupPowerState(const char* state_name);
Darin Petkov65b01462010-04-14 13:32:20 -0700182
Darin Petkov41e06232010-05-03 16:45:37 -0700183 // Processes user session state change.
Darin Petkovf27f0362010-06-04 13:14:19 -0700184 void SessionStateChanged(const char* state_name, base::Time now);
Darin Petkov41e06232010-05-03 16:45:37 -0700185
186 // Given the state name, returns the state id.
187 SessionState LookupSessionState(const char* state_name);
188
189 // Updates the user-active state to |active| and logs the usage data
190 // since the last update. If the user has just become active,
191 // reschedule the daily use monitor for more frequent updates --
192 // this is followed by an exponential back-off (see UseMonitor).
Darin Petkovf27f0362010-06-04 13:14:19 -0700193 // While in active use, this method should be called at intervals no
194 // longer than kUseMonitorIntervalMax otherwise new use time will be
195 // discarded.
196 void SetUserActiveState(bool active, base::Time now);
Darin Petkov41e06232010-05-03 16:45:37 -0700197
198 // Updates the daily usage file, if necessary, by adding |seconds|
199 // of active use to the |day| since Epoch. If there's usage data for
200 // day in the past in the usage file, that data is sent to UMA and
201 // removed from the file. If there's already usage data for |day| in
202 // the usage file, the |seconds| are accumulated.
203 void LogDailyUseRecord(int day, int seconds);
204
Darin Petkov1bb904e2010-06-16 15:58:06 -0700205 // Updates the active use time and logs time between user-space
206 // process crashes.
207 void ProcessUserCrash();
208
Darin Petkov38d5cb02010-06-24 12:10:26 -0700209 // Updates the active use time and logs time between kernel crashes.
210 void ProcessKernelCrash();
211
Ken Mixterccd84c02010-08-16 19:57:13 -0700212 // Updates the active use time and logs time between unclean shutdowns.
213 void ProcessUncleanShutdown();
214
215 // Checks if a kernel crash has been detected and returns true if
216 // so. The method assumes that a kernel crash has happened if
217 // |crash_file| exists. It removes the file immediately if it
218 // exists, so it must not be called more than once.
219 bool CheckSystemCrash(const std::string& crash_file);
Darin Petkov38d5cb02010-06-24 12:10:26 -0700220
Darin Petkov41e06232010-05-03 16:45:37 -0700221 // Callbacks for the daily use monitor. The daily use monitor uses
222 // LogDailyUseRecord to aggregate current usage data and send it to
223 // UMA, if necessary. It also reschedules itself using an
224 // exponentially bigger interval (up to a certain maximum) -- so
225 // usage is monitored less frequently with longer active use.
226 static gboolean UseMonitorStatic(gpointer data);
227 bool UseMonitor();
228
229 // Schedules or reschedules a daily use monitor for |interval|
230 // seconds from now. |backoff| mode is used by the use monitor to
231 // reschedule itself. If there's a monitor scheduled already and
232 // |backoff| is false, unschedules it first. Doesn't schedule a
233 // monitor for more than kUseMonitorIntervalMax seconds in the
234 // future (see metrics_daemon.cc). Returns true if a new use monitor
235 // was scheduled, false otherwise (note that if |backoff| is false a
236 // new use monitor will always be scheduled).
237 bool ScheduleUseMonitor(int interval, bool backoff);
238
239 // Unschedules a scheduled use monitor, if any.
240 void UnscheduleUseMonitor();
241
Ken Mixter4c5daa42010-08-26 18:35:06 -0700242 // Report daily use through UMA.
243 static void ReportDailyUse(void* handle, int tag, int count);
244
Darin Petkov11b8eb32010-05-18 11:00:59 -0700245 // Sends a regular (exponential) histogram sample to Chrome for
246 // transport to UMA. See MetricsLibrary::SendToUMA in
247 // metrics_library.h for a description of the arguments.
248 void SendMetric(const std::string& name, int sample,
249 int min, int max, int nbuckets);
Darin Petkov65b01462010-04-14 13:32:20 -0700250
Luigi Semenzato29c7ef92011-04-12 14:12:35 -0700251 // Sends a linear histogram sample to Chrome for transport to UMA. See
252 // MetricsLibrary::SendToUMA in metrics_library.h for a description of the
253 // arguments.
254 void SendLinearMetric(const std::string& name, int sample,
255 int max, int nbuckets);
256
Luigi Semenzatoc88e42d2011-02-17 10:21:16 -0800257 // Initializes disk stats reporting.
258 void DiskStatsReporterInit();
259
260 // Schedules a callback for the next disk stats collection.
261 void ScheduleDiskStatsCallback(int wait);
262
263 // Reads cumulative disk statistics from sysfs.
264 void DiskStatsReadStats(long int* read_sectors, long int* write_sectors);
265
266 // Reports disk statistics (static version for glib). Arguments are a glib
267 // artifact.
268 static gboolean DiskStatsCallbackStatic(void* handle);
269
270 // Reports disk statistics.
271 void DiskStatsCallback();
272
Luigi Semenzato29c7ef92011-04-12 14:12:35 -0700273 // Schedules meminfo collection callback.
274 void ScheduleMeminfoCallback(int wait);
275
276 // Reports memory statistics (static version for glib). Argument is a glib
277 // artifact.
278 static gboolean MeminfoCallbackStatic(void* handle);
279
280 // Reports memory statistics. Returns false on failure.
281 gboolean MeminfoCallback();
282
283 // Parses content of /proc/meminfo and sends fields of interest to UMA.
Luigi Semenzato8accd332011-05-17 16:37:18 -0700284 // Returns false on errors. |meminfo_raw| contains the content of
285 // /proc/meminfo.
286 gboolean ProcessMeminfo(const std::string& meminfo_raw);
287
288 // Parses meminfo data from |meminfo_raw|. |fields| is a vector containing
289 // the fields of interest. The order of the fields must be the same in which
290 // /proc/meminfo prints them. The result of parsing fields[i] is placed in
291 // fields[i].value.
292 gboolean FillMeminfo(const std::string& meminfo_raw,
293 std::vector<MeminfoRecord>* fields);
294
295 // Schedule a memory use callback. |new_callback| is true when this callback
296 // is scheduled for the first time. When |new_callback| is false,
297 // |time_elapsed| is the active (non-sleep) time that has passed between now
298 // and the original callback scheduling time. We use it to reschedule a
299 // callback that fired too early because we slept.
300 void ScheduleMemuseCallback(gboolean new_callback, double time_elapsed);
301
302 // Static wrapper for MemuseCallback. Always returns false.
303 static gboolean MemuseCallbackStatic(void* handle);
304
305 // Calls MemuseCallbackWork, and possibly schedules next callback, if enough
306 // active time has passed. Otherwise reschedules itself to simulate active
307 // time callbacks (i.e. wall clock time minus sleep time).
308 void MemuseCallback();
309
310 // Reads /proc/meminfo and sends total anonymous memory usage to UMA.
311 gboolean MemuseCallbackWork();
312
313 // Parse meminfo data and send to UMA.
314 gboolean ProcessMemuse(const std::string& meminfo_raw);
Luigi Semenzato29c7ef92011-04-12 14:12:35 -0700315
Darin Petkov2ccef012010-05-05 16:06:37 -0700316 // Test mode.
Darin Petkov41e06232010-05-03 16:45:37 -0700317 bool testing_;
Darin Petkov65b01462010-04-14 13:32:20 -0700318
Darin Petkovfc91b422010-05-12 13:05:45 -0700319 // The metrics library handle.
320 MetricsLibraryInterface* metrics_lib_;
321
Darin Petkovf27f0362010-06-04 13:14:19 -0700322 // Timestamps last network state update. This timestamp is used to
323 // sample the time from the network going online to going offline so
324 // TimeTicks ensures a monotonically increasing TimeDelta.
325 base::TimeTicks network_state_last_;
Darin Petkov65b01462010-04-14 13:32:20 -0700326
Darin Petkov41e06232010-05-03 16:45:37 -0700327 // Current power state.
328 PowerState power_state_;
329
Darin Petkov41e06232010-05-03 16:45:37 -0700330 // Current user session state.
331 SessionState session_state_;
332
333 // Is the user currently active: power is on, user session has
334 // started, screen is not locked.
335 bool user_active_;
336
Darin Petkov1bb904e2010-06-16 15:58:06 -0700337 // Timestamps last user active update. Active use time is aggregated
338 // each day before sending to UMA so using time since the epoch as
339 // the timestamp.
Darin Petkovf27f0362010-06-04 13:14:19 -0700340 base::Time user_active_last_;
Darin Petkov41e06232010-05-03 16:45:37 -0700341
Darin Petkov1bb904e2010-06-16 15:58:06 -0700342 // Daily active use time in seconds.
Ken Mixter4c5daa42010-08-26 18:35:06 -0700343 scoped_ptr<chromeos_metrics::TaggedCounter> daily_use_;
Darin Petkov41e06232010-05-03 16:45:37 -0700344
Darin Petkov1bb904e2010-06-16 15:58:06 -0700345 // Active use time between user-space process crashes.
Ken Mixter4c5daa42010-08-26 18:35:06 -0700346 scoped_ptr<chromeos_metrics::TaggedCounterReporter> user_crash_interval_;
Darin Petkov1bb904e2010-06-16 15:58:06 -0700347
Darin Petkov38d5cb02010-06-24 12:10:26 -0700348 // Active use time between kernel crashes.
Ken Mixter4c5daa42010-08-26 18:35:06 -0700349 scoped_ptr<chromeos_metrics::TaggedCounterReporter> kernel_crash_interval_;
Darin Petkov38d5cb02010-06-24 12:10:26 -0700350
Ken Mixterccd84c02010-08-16 19:57:13 -0700351 // Active use time between unclean shutdowns crashes.
Ken Mixter4c5daa42010-08-26 18:35:06 -0700352 scoped_ptr<chromeos_metrics::TaggedCounterReporter>
Ken Mixterccd84c02010-08-16 19:57:13 -0700353 unclean_shutdown_interval_;
354
Ken Mixter4c5daa42010-08-26 18:35:06 -0700355 // Map of all frequency counters, to simplify flushing them.
356 FrequencyCounters frequency_counters_;
Ken Mixterccd84c02010-08-16 19:57:13 -0700357
Darin Petkov41e06232010-05-03 16:45:37 -0700358 // Sleep period until the next daily usage aggregation performed by
359 // the daily use monitor (see ScheduleUseMonitor).
360 int usemon_interval_;
361
362 // Scheduled daily use monitor source (see ScheduleUseMonitor).
363 GSource* usemon_source_;
Luigi Semenzatoc88e42d2011-02-17 10:21:16 -0800364
Luigi Semenzato8accd332011-05-17 16:37:18 -0700365 // Time of initial scheduling of memuse callback
366 double memuse_initial_time_;
367
368 // Selects the wait time for the next memory use callback.
369 unsigned int memuse_interval_index_;
370
Luigi Semenzatoc88e42d2011-02-17 10:21:16 -0800371 // Contains the most recent disk stats.
372 long int read_sectors_;
373 long int write_sectors_;
374
375 DiskStatsState diskstats_state_;
Luigi Semenzato0f132bb2011-02-28 11:17:43 -0800376 std::string diskstats_path_;
Luigi Semenzato8accd332011-05-17 16:37:18 -0700377 double diskstats_initial_time_;
Darin Petkov65b01462010-04-14 13:32:20 -0700378};
379
380#endif // METRICS_DAEMON_H_