blob: 87eae58bec0654fa963e08145bbd82286a7edcb7 [file] [log] [blame]
tfarina@chromium.org4d818fee2010-06-06 13:32:271// Copyright (c) 2010 The Chromium Authors. All rights reserved.
license.botbf09a502008-08-24 00:55:552// Use of this source code is governed by a BSD-style license that can be
3// found in the LICENSE file.
initial.commit09911bf2008-07-26 23:55:294
5
6
7//------------------------------------------------------------------------------
8// Description of the life cycle of a instance of MetricsService.
9//
10// OVERVIEW
11//
12// A MetricsService instance is typically created at application startup. It
13// is the central controller for the acquisition of log data, and the automatic
14// transmission of that log data to an external server. Its major job is to
15// manage logs, grouping them for transmission, and transmitting them. As part
16// of its grouping, MS finalizes logs by including some just-in-time gathered
17// memory statistics, snapshotting the current stats of numerous histograms,
18// closing the logs, translating to XML text, and compressing the results for
19// transmission. Transmission includes submitting a compressed log as data in a
jar@chromium.org281d2882009-01-20 20:32:4220// URL-post, and retransmitting (or retaining at process termination) if the
initial.commit09911bf2008-07-26 23:55:2921// attempted transmission failed. Retention across process terminations is done
ziadh@chromium.org46f89e142010-07-19 08:00:4222// using the the PrefServices facilities. The retained logs (the ones that never
23// got transmitted) are compressed and base64-encoded before being persisted.
initial.commit09911bf2008-07-26 23:55:2924//
jar@chromium.org281d2882009-01-20 20:32:4225// Logs fall into one of two categories: "initial logs," and "ongoing logs."
26// There is at most one initial log sent for each complete run of the chromium
initial.commit09911bf2008-07-26 23:55:2927// product (from startup, to browser shutdown). An initial log is generally
28// transmitted some short time (1 minute?) after startup, and includes stats
29// such as recent crash info, the number and types of plugins, etc. The
jar@chromium.org281d2882009-01-20 20:32:4230// external server's response to the initial log conceptually tells this MS if
31// it should continue transmitting logs (during this session). The server
32// response can actually be much more detailed, and always includes (at a
33// minimum) how often additional ongoing logs should be sent.
initial.commit09911bf2008-07-26 23:55:2934//
35// After the above initial log, a series of ongoing logs will be transmitted.
36// The first ongoing log actually begins to accumulate information stating when
37// the MS was first constructed. Note that even though the initial log is
38// commonly sent a full minute after startup, the initial log does not include
39// much in the way of user stats. The most common interlog period (delay)
jar@google.com0b33f80b2008-12-17 21:34:3640// is 20 minutes. That time period starts when the first user action causes a
initial.commit09911bf2008-07-26 23:55:2941// logging event. This means that if there is no user action, there may be long
jar@chromium.org281d2882009-01-20 20:32:4242// periods without any (ongoing) log transmissions. Ongoing logs typically
initial.commit09911bf2008-07-26 23:55:2943// contain very detailed records of user activities (ex: opened tab, closed
44// tab, fetched URL, maximized window, etc.) In addition, just before an
45// ongoing log is closed out, a call is made to gather memory statistics. Those
46// memory statistics are deposited into a histogram, and the log finalization
47// code is then called. In the finalization, a call to a Histogram server
48// acquires a list of all local histograms that have been flagged for upload
jar@chromium.org281d2882009-01-20 20:32:4249// to the UMA server. The finalization also acquires a the most recent number
50// of page loads, along with any counts of renderer or plugin crashes.
initial.commit09911bf2008-07-26 23:55:2951//
52// When the browser shuts down, there will typically be a fragment of an ongoing
53// log that has not yet been transmitted. At shutdown time, that fragment
54// is closed (including snapshotting histograms), and converted to text. Note
55// that memory stats are not gathered during shutdown, as gathering *might* be
56// too time consuming. The textual representation of the fragment of the
57// ongoing log is then stored persistently as a string in the PrefServices, for
58// potential transmission during a future run of the product.
59//
60// There are two slightly abnormal shutdown conditions. There is a
61// "disconnected scenario," and a "really fast startup and shutdown" scenario.
62// In the "never connected" situation, the user has (during the running of the
63// process) never established an internet connection. As a result, attempts to
64// transmit the initial log have failed, and a lot(?) of data has accumulated in
65// the ongoing log (which didn't yet get closed, because there was never even a
66// contemplation of sending it). There is also a kindred "lost connection"
67// situation, where a loss of connection prevented an ongoing log from being
68// transmitted, and a (still open) log was stuck accumulating a lot(?) of data,
69// while the earlier log retried its transmission. In both of these
70// disconnected situations, two logs need to be, and are, persistently stored
71// for future transmission.
72//
73// The other unusual shutdown condition, termed "really fast startup and
74// shutdown," involves the deliberate user termination of the process before
75// the initial log is even formed or transmitted. In that situation, no logging
76// is done, but the historical crash statistics remain (unlogged) for inclusion
77// in a future run's initial log. (i.e., we don't lose crash stats).
78//
79// With the above overview, we can now describe the state machine's various
80// stats, based on the State enum specified in the state_ member. Those states
81// are:
82//
83// INITIALIZED, // Constructor was called.
zelidrag@chromium.org85ed9d42010-06-08 22:37:4484// INIT_TASK_SCHEDULED, // Waiting for deferred init tasks to complete.
85// INIT_TASK_DONE, // Waiting for timer to send initial log.
initial.commit09911bf2008-07-26 23:55:2986// INITIAL_LOG_READY, // Initial log generated, and waiting for reply.
87// SEND_OLD_INITIAL_LOGS, // Sending unsent logs from previous session.
88// SENDING_OLD_LOGS, // Sending unsent logs from previous session.
89// SENDING_CURRENT_LOGS, // Sending standard current logs as they accrue.
90//
91// In more detail, we have:
92//
93// INITIALIZED, // Constructor was called.
94// The MS has been constructed, but has taken no actions to compose the
95// initial log.
96//
zelidrag@chromium.org85ed9d42010-06-08 22:37:4497// INIT_TASK_SCHEDULED, // Waiting for deferred init tasks to complete.
initial.commit09911bf2008-07-26 23:55:2998// Typically about 30 seconds after startup, a task is sent to a second thread
zelidrag@chromium.org85ed9d42010-06-08 22:37:4499// (the file thread) to perform deferred (lower priority and slower)
100// initialization steps such as getting the list of plugins. That task will
101// (when complete) make an async callback (via a Task) to indicate the
102// completion.
initial.commit09911bf2008-07-26 23:55:29103//
zelidrag@chromium.org85ed9d42010-06-08 22:37:44104// INIT_TASK_DONE, // Waiting for timer to send initial log.
initial.commit09911bf2008-07-26 23:55:29105// The callback has arrived, and it is now possible for an initial log to be
106// created. This callback typically arrives back less than one second after
zelidrag@chromium.org85ed9d42010-06-08 22:37:44107// the deferred init task is dispatched.
initial.commit09911bf2008-07-26 23:55:29108//
109// INITIAL_LOG_READY, // Initial log generated, and waiting for reply.
110// This state is entered only after an initial log has been composed, and
111// prepared for transmission. It is also the case that any previously unsent
112// logs have been loaded into instance variables for possible transmission.
113//
114// SEND_OLD_INITIAL_LOGS, // Sending unsent logs from previous session.
115// This state indicates that the initial log for this session has been
116// successfully sent and it is now time to send any "initial logs" that were
117// saved from previous sessions. Most commonly, there are none, but all old
118// logs that were "initial logs" must be sent before this state is exited.
119//
120// SENDING_OLD_LOGS, // Sending unsent logs from previous session.
121// This state indicates that there are no more unsent initial logs, and now any
122// ongoing logs from previous sessions should be transmitted. All such logs
123// will be transmitted before exiting this state, and proceeding with ongoing
124// logs from the current session (see next state).
125//
126// SENDING_CURRENT_LOGS, // Sending standard current logs as they accrue.
jar@google.com0b33f80b2008-12-17 21:34:36127// Current logs are being accumulated. Typically every 20 minutes a log is
initial.commit09911bf2008-07-26 23:55:29128// closed and finalized for transmission, at the same time as a new log is
129// started.
130//
131// The progression through the above states is simple, and sequential, in the
132// most common use cases. States proceed from INITIAL to SENDING_CURRENT_LOGS,
133// and remain in the latter until shutdown.
134//
135// The one unusual case is when the user asks that we stop logging. When that
136// happens, any pending (transmission in progress) log is pushed into the list
137// of old unsent logs (the appropriate list, depending on whether it is an
138// initial log, or an ongoing log). An addition, any log that is currently
139// accumulating is also finalized, and pushed into the unsent log list. With
jar@chromium.org281d2882009-01-20 20:32:42140// those pushes performed, we regress back to the SEND_OLD_INITIAL_LOGS state in
initial.commit09911bf2008-07-26 23:55:29141// case the user enables log recording again during this session. This way
142// anything we have "pushed back" will be sent automatically if/when we progress
143// back to SENDING_CURRENT_LOG state.
144//
145// Also note that whenever the member variables containing unsent logs are
146// modified (i.e., when we send an old log), we mirror the list of logs into
147// the PrefServices. This ensures that IF we crash, we won't start up and
148// retransmit our old logs again.
149//
150// Due to race conditions, it is always possible that a log file could be sent
151// twice. For example, if a log file is sent, but not yet acknowledged by
152// the external server, and the user shuts down, then a copy of the log may be
153// saved for re-transmission. These duplicates could be filtered out server
jar@chromium.org281d2882009-01-20 20:32:42154// side, but are not expected to be a significant problem.
initial.commit09911bf2008-07-26 23:55:29155//
156//
157//------------------------------------------------------------------------------
158
maruel@chromium.org40bcc302009-03-02 20:50:39159#include "chrome/browser/metrics/metrics_service.h"
160
paul@chromium.orgdc6f4962009-02-13 01:25:50161#if defined(OS_WIN)
initial.commit09911bf2008-07-26 23:55:29162#include <windows.h>
maruel@chromium.org40bcc302009-03-02 20:50:39163#include <objbase.h>
paul@chromium.orgdc6f4962009-02-13 01:25:50164#endif
initial.commit09911bf2008-07-26 23:55:29165
ziadh@chromium.org46f89e142010-07-19 08:00:42166#include "base/base64.h"
167#include "base/md5.h"
pkasting@chromium.org4d022ff2009-10-23 18:47:09168#include "base/thread.h"
sky@google.comd8e41ed2008-09-11 15:22:32169#include "chrome/browser/bookmarks/bookmark_model.h"
initial.commit09911bf2008-07-26 23:55:29170#include "chrome/browser/browser_list.h"
171#include "chrome/browser/browser_process.h"
172#include "chrome/browser/load_notification_details.h"
173#include "chrome/browser/memory_details.h"
phajdan.jr@chromium.org7c927b62010-02-24 09:54:13174#include "chrome/browser/metrics/histogram_synchronizer.h"
phajdan.jr@chromium.org052313b2010-02-19 09:43:08175#include "chrome/browser/pref_service.h"
initial.commit09911bf2008-07-26 23:55:29176#include "chrome/browser/profile.h"
brettw@chromium.org8c8657d62009-01-16 18:31:26177#include "chrome/browser/renderer_host/render_process_host.h"
ben@chromium.orgd54e03a52009-01-16 00:31:04178#include "chrome/browser/search_engines/template_url_model.h"
kuchhal@chromium.org157d5472009-11-05 22:31:03179#include "chrome/common/child_process_logging.h"
jar@chromium.org92745242009-06-12 16:52:21180#include "chrome/common/chrome_switches.h"
brettw@chromium.orgbfd04a62009-02-01 18:16:56181#include "chrome/common/notification_service.h"
initial.commit09911bf2008-07-26 23:55:29182#include "chrome/common/pref_names.h"
jam@chromium.orge09ba552009-02-05 03:26:29183#include "chrome/common/render_messages.h"
jam@chromium.org35fa6a22009-08-15 00:04:01184#include "webkit/glue/plugins/plugin_list.h"
mad@google.comae393ec702010-06-27 16:23:14185#include "libxml/xmlwriter.h"
initial.commit09911bf2008-07-26 23:55:29186
pkasting@chromium.org4d022ff2009-10-23 18:47:09187#if !defined(OS_WIN)
188#include "base/rand_util.h"
189#endif
190
phajdan.jr@chromium.orge06131d2010-02-10 18:40:33191// TODO(port): port browser_distribution.h.
192#if !defined(OS_POSIX)
kuchhal@chromium.org79bf0b72009-04-27 21:30:55193#include "chrome/installer/util/browser_distribution.h"
paul@chromium.orgdc6f4962009-02-13 01:25:50194#endif
195
rvargas@google.com5ccaa412009-11-13 22:00:16196#if defined(OS_CHROMEOS)
197#include "chrome/browser/chromeos/external_metrics.h"
zelidrag@chromium.org85ed9d42010-06-08 22:37:44198
199static const char kHardwareClassTool[] = "/usr/bin/hardware_class";
200static const char kUnknownHardwareClass[] = "unknown";
rvargas@google.com5ccaa412009-11-13 22:00:16201#endif
202
ziadh@chromium.org46f89e142010-07-19 08:00:42203namespace {
204MetricsService::LogRecallStatus MakeRecallStatusHistogram(
205 MetricsService::LogRecallStatus status) {
206 UMA_HISTOGRAM_ENUMERATION("PrefService.PersistentLogRecall", status,
207 MetricsService::END_RECALL_STATUS);
208 return status;
209}
210
211// TODO(ziadh): Remove this when done with experiment.
212void MakeStoreStatusHistogram(MetricsService::LogStoreStatus status) {
213 UMA_HISTOGRAM_ENUMERATION("PrefService.PersistentLogStore", status,
214 MetricsService::END_STORE_STATUS);
215}
216} // namespace
217
dsh@google.come1acf6f2008-10-27 20:43:33218using base::Time;
219using base::TimeDelta;
220
initial.commit09911bf2008-07-26 23:55:29221// Check to see that we're being called on only one thread.
222static bool IsSingleThreaded();
223
initial.commit09911bf2008-07-26 23:55:29224static const char kMetricsType[] = "application/vnd.mozilla.metrics.bz2";
225
226// The delay, in seconds, after startup before sending the first log message.
petersont@google.com252873ef2008-08-04 21:59:45227static const int kInitialInterlogDuration = 60; // one minute
228
jar@chromium.orgc9a3ef82009-05-28 22:02:46229// This specifies the amount of time to wait for all renderers to send their
230// data.
231static const int kMaxHistogramGatheringWaitDuration = 60000; // 60 seconds.
232
petersont@google.com252873ef2008-08-04 21:59:45233// The default maximum number of events in a log uploaded to the UMA server.
jar@google.com0b33f80b2008-12-17 21:34:36234static const int kInitialEventLimit = 2400;
jar@google.com68475e602008-08-22 03:21:15235
236// If an upload fails, and the transmission was over this byte count, then we
237// will discard the log, and not try to retransmit it. We also don't persist
238// the log to the prefs for transmission during the next chrome session if this
239// limit is exceeded.
240static const int kUploadLogAvoidRetransmitSize = 50000;
initial.commit09911bf2008-07-26 23:55:29241
242// When we have logs from previous Chrome sessions to send, how long should we
243// delay (in seconds) between each log transmission.
244static const int kUnsentLogDelay = 15; // 15 seconds
245
246// Minimum time a log typically exists before sending, in seconds.
247// This number is supplied by the server, but until we parse it out of a server
248// response, we use this duration to specify how long we should wait before
249// sending the next log. If the channel is busy, such as when there is a
250// failure during an attempt to transmit a previous log, then a log may wait
jar@chromium.org2fe42fe2010-05-07 19:22:39251// (and continue to accrue new log entries) for a much greater period of time.
252static const int kMinSecondsPerLog = 30 * 60; // Thirty minutes.
initial.commit09911bf2008-07-26 23:55:29253
initial.commit09911bf2008-07-26 23:55:29254// When we don't succeed at transmitting a log to a server, we progressively
255// wait longer and longer before sending the next log. This backoff process
256// help reduce load on the server, and makes the amount of backoff vary between
257// clients so that a collision (server overload?) on retransmit is less likely.
258// The following is the constant we use to expand that inter-log duration.
259static const double kBackoff = 1.1;
260// We limit the maximum backoff to be no greater than some multiple of the
261// default kMinSecondsPerLog. The following is that maximum ratio.
262static const int kMaxBackoff = 10;
263
264// Interval, in seconds, between state saves.
265static const int kSaveStateInterval = 5 * 60; // five minutes
266
267// The number of "initial" logs we're willing to save, and hope to send during
268// a future Chrome session. Initial logs contain crash stats, and are pretty
269// small.
270static const size_t kMaxInitialLogsPersisted = 20;
271
272// The number of ongoing logs we're willing to save persistently, and hope to
jar@chromium.org281d2882009-01-20 20:32:42273// send during a this or future sessions. Note that each log may be pretty
initial.commit09911bf2008-07-26 23:55:29274// large, as presumably the related "initial" log wasn't sent (probably nothing
275// was, as the user was probably off-line). As a result, the log probably kept
276// accumulating while the "initial" log was stalled (pending_), and couldn't be
277// sent. As a result, we don't want to save too many of these mega-logs.
278// A "standard shutdown" will create a small log, including just the data that
279// was not yet been transmitted, and that is normal (to have exactly one
280// ongoing_log_ at startup).
jar@chromium.org281d2882009-01-20 20:32:42281static const size_t kMaxOngoingLogsPersisted = 8;
initial.commit09911bf2008-07-26 23:55:29282
ziadh@chromium.org46f89e142010-07-19 08:00:42283// We append (2) more elements to persisted lists: the size of the list and a
284// checksum of the elements.
285static const size_t kChecksumEntryCount = 2;
286
initial.commit09911bf2008-07-26 23:55:29287
288// Handles asynchronous fetching of memory details.
289// Will run the provided task after finished.
290class MetricsMemoryDetails : public MemoryDetails {
291 public:
292 explicit MetricsMemoryDetails(Task* completion) : completion_(completion) {}
293
294 virtual void OnDetailsAvailable() {
295 MessageLoop::current()->PostTask(FROM_HERE, completion_);
296 }
297
298 private:
jam@chromium.orge6e6ba42009-11-07 01:56:19299 ~MetricsMemoryDetails() {}
300
initial.commit09911bf2008-07-26 23:55:29301 Task* completion_;
tfarina@chromium.org4d818fee2010-06-06 13:32:27302 DISALLOW_COPY_AND_ASSIGN(MetricsMemoryDetails);
initial.commit09911bf2008-07-26 23:55:29303};
304
zelidrag@chromium.org85ed9d42010-06-08 22:37:44305class MetricsService::InitTaskComplete : public Task {
jam@chromium.org35fa6a22009-08-15 00:04:01306 public:
zelidrag@chromium.org85ed9d42010-06-08 22:37:44307 explicit InitTaskComplete(const std::string& hardware_class,
308 const std::vector<WebPluginInfo>& plugins)
309 : hardware_class_(hardware_class), plugins_(plugins) {}
310
jamesr@chromium.org7f2e792e2009-11-30 23:18:29311 virtual void Run() {
zelidrag@chromium.org85ed9d42010-06-08 22:37:44312 g_browser_process->metrics_service()->OnInitTaskComplete(
313 hardware_class_, plugins_);
initial.commit09911bf2008-07-26 23:55:29314 }
jam@chromium.org35fa6a22009-08-15 00:04:01315
jamesr@chromium.org7f2e792e2009-11-30 23:18:29316 private:
zelidrag@chromium.org85ed9d42010-06-08 22:37:44317 std::string hardware_class_;
jamesr@chromium.org7f2e792e2009-11-30 23:18:29318 std::vector<WebPluginInfo> plugins_;
initial.commit09911bf2008-07-26 23:55:29319};
320
zelidrag@chromium.org85ed9d42010-06-08 22:37:44321class MetricsService::InitTask : public Task {
jamesr@chromium.org7f2e792e2009-11-30 23:18:29322 public:
zelidrag@chromium.org85ed9d42010-06-08 22:37:44323 explicit InitTask(MessageLoop* callback_loop)
jamesr@chromium.org7f2e792e2009-11-30 23:18:29324 : callback_loop_(callback_loop) {}
325
326 virtual void Run() {
327 std::vector<WebPluginInfo> plugins;
328 NPAPI::PluginList::Singleton()->GetPlugins(false, &plugins);
zelidrag@chromium.org85ed9d42010-06-08 22:37:44329 std::string hardware_class; // Empty string by default.
330#if defined(OS_CHROMEOS)
331 hardware_class = MetricsService::GetHardwareClass();
332#endif // OS_CHROMEOS
333 callback_loop_->PostTask(FROM_HERE, new InitTaskComplete(
334 hardware_class, plugins));
jamesr@chromium.org7f2e792e2009-11-30 23:18:29335 }
336
337 private:
338 MessageLoop* callback_loop_;
339};
evan@chromium.org90d41372009-11-30 21:52:32340
initial.commit09911bf2008-07-26 23:55:29341// static
342void MetricsService::RegisterPrefs(PrefService* local_state) {
343 DCHECK(IsSingleThreaded());
estade@chromium.org20ce516d2010-06-18 02:20:04344 local_state->RegisterStringPref(prefs::kMetricsClientID, "");
robertshield@google.com0bb1a622009-03-04 03:22:32345 local_state->RegisterInt64Pref(prefs::kMetricsClientIDTimestamp, 0);
346 local_state->RegisterInt64Pref(prefs::kStabilityLaunchTimeSec, 0);
347 local_state->RegisterInt64Pref(prefs::kStabilityLastTimestampSec, 0);
estade@chromium.org20ce516d2010-06-18 02:20:04348 local_state->RegisterStringPref(prefs::kStabilityStatsVersion, "");
jar@chromium.org225c50842010-01-19 21:19:13349 local_state->RegisterInt64Pref(prefs::kStabilityStatsBuildTime, 0);
initial.commit09911bf2008-07-26 23:55:29350 local_state->RegisterBooleanPref(prefs::kStabilityExitedCleanly, true);
351 local_state->RegisterBooleanPref(prefs::kStabilitySessionEndCompleted, true);
352 local_state->RegisterIntegerPref(prefs::kMetricsSessionID, -1);
353 local_state->RegisterIntegerPref(prefs::kStabilityLaunchCount, 0);
354 local_state->RegisterIntegerPref(prefs::kStabilityCrashCount, 0);
355 local_state->RegisterIntegerPref(prefs::kStabilityIncompleteSessionEndCount,
356 0);
357 local_state->RegisterIntegerPref(prefs::kStabilityPageLoadCount, 0);
initial.commit09911bf2008-07-26 23:55:29358 local_state->RegisterIntegerPref(prefs::kStabilityRendererCrashCount, 0);
asargent@chromium.org1f085622009-12-04 05:33:45359 local_state->RegisterIntegerPref(prefs::kStabilityExtensionRendererCrashCount,
360 0);
initial.commit09911bf2008-07-26 23:55:29361 local_state->RegisterIntegerPref(prefs::kStabilityRendererHangCount, 0);
asargent@chromium.org1f085622009-12-04 05:33:45362 local_state->RegisterIntegerPref(prefs::kStabilityChildProcessCrashCount, 0);
cpu@google.come73c01972008-08-13 00:18:24363 local_state->RegisterIntegerPref(prefs::kStabilityBreakpadRegistrationFail,
364 0);
365 local_state->RegisterIntegerPref(prefs::kStabilityBreakpadRegistrationSuccess,
366 0);
367 local_state->RegisterIntegerPref(prefs::kStabilityDebuggerPresent, 0);
368 local_state->RegisterIntegerPref(prefs::kStabilityDebuggerNotPresent, 0);
369
initial.commit09911bf2008-07-26 23:55:29370 local_state->RegisterDictionaryPref(prefs::kProfileMetrics);
371 local_state->RegisterIntegerPref(prefs::kNumBookmarksOnBookmarkBar, 0);
372 local_state->RegisterIntegerPref(prefs::kNumFoldersOnBookmarkBar, 0);
373 local_state->RegisterIntegerPref(prefs::kNumBookmarksInOtherBookmarkFolder,
374 0);
375 local_state->RegisterIntegerPref(prefs::kNumFoldersInOtherBookmarkFolder, 0);
376 local_state->RegisterIntegerPref(prefs::kNumKeywords, 0);
377 local_state->RegisterListPref(prefs::kMetricsInitialLogs);
378 local_state->RegisterListPref(prefs::kMetricsOngoingLogs);
robertshield@google.com0bb1a622009-03-04 03:22:32379
380 local_state->RegisterInt64Pref(prefs::kUninstallMetricsPageLoadCount, 0);
381 local_state->RegisterInt64Pref(prefs::kUninstallLaunchCount, 0);
robertshield@google.com6b5f21d2009-04-13 17:01:35382 local_state->RegisterInt64Pref(prefs::kUninstallMetricsInstallDate, 0);
robertshield@google.com0bb1a622009-03-04 03:22:32383 local_state->RegisterInt64Pref(prefs::kUninstallMetricsUptimeSec, 0);
384 local_state->RegisterInt64Pref(prefs::kUninstallLastLaunchTimeSec, 0);
385 local_state->RegisterInt64Pref(prefs::kUninstallLastObservedRunTimeSec, 0);
initial.commit09911bf2008-07-26 23:55:29386}
387
jar@chromium.org541f77922009-02-23 21:14:38388// static
389void MetricsService::DiscardOldStabilityStats(PrefService* local_state) {
390 local_state->SetBoolean(prefs::kStabilityExitedCleanly, true);
jar@chromium.orgc9abf242009-07-18 06:00:38391 local_state->SetBoolean(prefs::kStabilitySessionEndCompleted, true);
jar@chromium.org541f77922009-02-23 21:14:38392
393 local_state->SetInteger(prefs::kStabilityIncompleteSessionEndCount, 0);
394 local_state->SetInteger(prefs::kStabilityBreakpadRegistrationSuccess, 0);
395 local_state->SetInteger(prefs::kStabilityBreakpadRegistrationFail, 0);
396 local_state->SetInteger(prefs::kStabilityDebuggerPresent, 0);
397 local_state->SetInteger(prefs::kStabilityDebuggerNotPresent, 0);
398
399 local_state->SetInteger(prefs::kStabilityLaunchCount, 0);
400 local_state->SetInteger(prefs::kStabilityCrashCount, 0);
401
402 local_state->SetInteger(prefs::kStabilityPageLoadCount, 0);
403 local_state->SetInteger(prefs::kStabilityRendererCrashCount, 0);
404 local_state->SetInteger(prefs::kStabilityRendererHangCount, 0);
405
jar@chromium.org9165f742010-03-10 22:55:01406 local_state->SetInt64(prefs::kStabilityLaunchTimeSec, 0);
407 local_state->SetInt64(prefs::kStabilityLastTimestampSec, 0);
jar@chromium.org541f77922009-02-23 21:14:38408
409 local_state->ClearPref(prefs::kStabilityPluginStats);
jar@chromium.orgae155cb92009-06-19 06:10:37410
411 ListValue* unsent_initial_logs = local_state->GetMutableList(
412 prefs::kMetricsInitialLogs);
413 unsent_initial_logs->Clear();
414
415 ListValue* unsent_ongoing_logs = local_state->GetMutableList(
416 prefs::kMetricsOngoingLogs);
417 unsent_ongoing_logs->Clear();
jar@chromium.org541f77922009-02-23 21:14:38418}
419
initial.commit09911bf2008-07-26 23:55:29420MetricsService::MetricsService()
petersont@google.comd01b8732008-10-16 02:18:07421 : recording_active_(false),
422 reporting_active_(false),
423 user_permits_upload_(false),
424 server_permits_upload_(true),
425 state_(INITIALIZED),
initial.commit09911bf2008-07-26 23:55:29426 current_fetch_(NULL),
petersont@google.comd01b8732008-10-16 02:18:07427 idle_since_last_transmission_(false),
initial.commit09911bf2008-07-26 23:55:29428 next_window_id_(0),
maruel@chromium.org40bcc302009-03-02 20:50:39429 ALLOW_THIS_IN_INITIALIZER_LIST(log_sender_factory_(this)),
430 ALLOW_THIS_IN_INITIALIZER_LIST(state_saver_factory_(this)),
petersont@google.com252873ef2008-08-04 21:59:45431 interlog_duration_(TimeDelta::FromSeconds(kInitialInterlogDuration)),
petersont@google.comd01b8732008-10-16 02:18:07432 log_event_limit_(kInitialEventLimit),
initial.commit09911bf2008-07-26 23:55:29433 timer_pending_(false) {
434 DCHECK(IsSingleThreaded());
435 InitializeMetricsState();
436}
437
438MetricsService::~MetricsService() {
439 SetRecording(false);
440}
441
petersont@google.comd01b8732008-10-16 02:18:07442void MetricsService::SetUserPermitsUpload(bool enabled) {
443 HandleIdleSinceLastTransmission(false);
444 user_permits_upload_ = enabled;
445}
446
447void MetricsService::Start() {
448 SetRecording(true);
449 SetReporting(true);
450}
451
452void MetricsService::StartRecordingOnly() {
453 SetRecording(true);
454 SetReporting(false);
455}
456
457void MetricsService::Stop() {
458 SetReporting(false);
459 SetRecording(false);
460}
461
initial.commit09911bf2008-07-26 23:55:29462void MetricsService::SetRecording(bool enabled) {
463 DCHECK(IsSingleThreaded());
464
petersont@google.comd01b8732008-10-16 02:18:07465 if (enabled == recording_active_)
initial.commit09911bf2008-07-26 23:55:29466 return;
467
468 if (enabled) {
jar@chromium.orgb0c819f2009-03-08 04:52:15469 if (client_id_.empty()) {
470 PrefService* pref = g_browser_process->local_state();
471 DCHECK(pref);
estade@chromium.orgddd231e2010-06-29 20:35:19472 client_id_ = pref->GetString(prefs::kMetricsClientID);
jar@chromium.orgb0c819f2009-03-08 04:52:15473 if (client_id_.empty()) {
474 client_id_ = GenerateClientID();
estade@chromium.orgddd231e2010-06-29 20:35:19475 pref->SetString(prefs::kMetricsClientID, client_id_);
jar@chromium.orgb0c819f2009-03-08 04:52:15476
477 // Might as well make a note of how long this ID has existed
478 pref->SetString(prefs::kMetricsClientIDTimestamp,
estade@chromium.orgddd231e2010-06-29 20:35:19479 Int64ToString(Time::Now().ToTimeT()));
jar@chromium.orgb0c819f2009-03-08 04:52:15480 }
481 }
kuchhal@chromium.org157d5472009-11-05 22:31:03482 child_process_logging::SetClientId(client_id_);
initial.commit09911bf2008-07-26 23:55:29483 StartRecording();
pkasting@chromium.org005ef3e2009-05-22 20:55:46484
485 registrar_.Add(this, NotificationType::BROWSER_OPENED,
486 NotificationService::AllSources());
487 registrar_.Add(this, NotificationType::BROWSER_CLOSED,
488 NotificationService::AllSources());
489 registrar_.Add(this, NotificationType::USER_ACTION,
490 NotificationService::AllSources());
491 registrar_.Add(this, NotificationType::TAB_PARENTED,
492 NotificationService::AllSources());
493 registrar_.Add(this, NotificationType::TAB_CLOSING,
494 NotificationService::AllSources());
495 registrar_.Add(this, NotificationType::LOAD_START,
496 NotificationService::AllSources());
497 registrar_.Add(this, NotificationType::LOAD_STOP,
498 NotificationService::AllSources());
kkania@chromium.orgcd69619b2010-05-05 02:41:38499 registrar_.Add(this, NotificationType::RENDERER_PROCESS_CLOSED,
pkasting@chromium.org005ef3e2009-05-22 20:55:46500 NotificationService::AllSources());
501 registrar_.Add(this, NotificationType::RENDERER_PROCESS_HANG,
502 NotificationService::AllSources());
503 registrar_.Add(this, NotificationType::CHILD_PROCESS_HOST_CONNECTED,
504 NotificationService::AllSources());
505 registrar_.Add(this, NotificationType::CHILD_INSTANCE_CREATED,
506 NotificationService::AllSources());
507 registrar_.Add(this, NotificationType::CHILD_PROCESS_CRASHED,
508 NotificationService::AllSources());
509 registrar_.Add(this, NotificationType::TEMPLATE_URL_MODEL_LOADED,
510 NotificationService::AllSources());
511 registrar_.Add(this, NotificationType::OMNIBOX_OPENED_URL,
512 NotificationService::AllSources());
513 registrar_.Add(this, NotificationType::BOOKMARK_MODEL_LOADED,
514 NotificationService::AllSources());
initial.commit09911bf2008-07-26 23:55:29515 } else {
pkasting@chromium.org005ef3e2009-05-22 20:55:46516 registrar_.RemoveAll();
initial.commit09911bf2008-07-26 23:55:29517 PushPendingLogsToUnsentLists();
518 DCHECK(!pending_log());
519 if (state_ > INITIAL_LOG_READY && unsent_logs())
520 state_ = SEND_OLD_INITIAL_LOGS;
521 }
petersont@google.comd01b8732008-10-16 02:18:07522 recording_active_ = enabled;
initial.commit09911bf2008-07-26 23:55:29523}
524
petersont@google.comd01b8732008-10-16 02:18:07525bool MetricsService::recording_active() const {
initial.commit09911bf2008-07-26 23:55:29526 DCHECK(IsSingleThreaded());
petersont@google.comd01b8732008-10-16 02:18:07527 return recording_active_;
initial.commit09911bf2008-07-26 23:55:29528}
529
petersont@google.comd01b8732008-10-16 02:18:07530void MetricsService::SetReporting(bool enable) {
531 if (reporting_active_ != enable) {
532 reporting_active_ = enable;
533 if (reporting_active_)
initial.commit09911bf2008-07-26 23:55:29534 StartLogTransmissionTimer();
535 }
petersont@google.comd01b8732008-10-16 02:18:07536}
537
538bool MetricsService::reporting_active() const {
539 DCHECK(IsSingleThreaded());
540 return reporting_active_;
initial.commit09911bf2008-07-26 23:55:29541}
542
543void MetricsService::Observe(NotificationType type,
544 const NotificationSource& source,
545 const NotificationDetails& details) {
546 DCHECK(current_log_);
547 DCHECK(IsSingleThreaded());
548
549 if (!CanLogNotification(type, source, details))
550 return;
551
brettw@chromium.orgbfd04a62009-02-01 18:16:56552 switch (type.value) {
553 case NotificationType::USER_ACTION:
evan@chromium.orgafe3a1672009-11-17 19:04:12554 current_log_->RecordUserAction(*Details<const char*>(details).ptr());
initial.commit09911bf2008-07-26 23:55:29555 break;
556
brettw@chromium.orgbfd04a62009-02-01 18:16:56557 case NotificationType::BROWSER_OPENED:
558 case NotificationType::BROWSER_CLOSED:
initial.commit09911bf2008-07-26 23:55:29559 LogWindowChange(type, source, details);
560 break;
561
brettw@chromium.orgbfd04a62009-02-01 18:16:56562 case NotificationType::TAB_PARENTED:
563 case NotificationType::TAB_CLOSING:
initial.commit09911bf2008-07-26 23:55:29564 LogWindowChange(type, source, details);
565 break;
566
brettw@chromium.orgbfd04a62009-02-01 18:16:56567 case NotificationType::LOAD_STOP:
initial.commit09911bf2008-07-26 23:55:29568 LogLoadComplete(type, source, details);
569 break;
570
brettw@chromium.orgbfd04a62009-02-01 18:16:56571 case NotificationType::LOAD_START:
initial.commit09911bf2008-07-26 23:55:29572 LogLoadStarted();
573 break;
574
kkania@chromium.orgcd69619b2010-05-05 02:41:38575 case NotificationType::RENDERER_PROCESS_CLOSED:
asargent@chromium.org1f085622009-12-04 05:33:45576 {
kkania@chromium.orgcd69619b2010-05-05 02:41:38577 RenderProcessHost::RendererClosedDetails* process_details =
578 Details<RenderProcessHost::RendererClosedDetails>(details).ptr();
579 if (process_details->did_crash) {
580 if (process_details->was_extension_renderer) {
581 LogExtensionRendererCrash();
582 } else {
583 LogRendererCrash();
584 }
585 }
asargent@chromium.org1f085622009-12-04 05:33:45586 }
initial.commit09911bf2008-07-26 23:55:29587 break;
588
brettw@chromium.orgbfd04a62009-02-01 18:16:56589 case NotificationType::RENDERER_PROCESS_HANG:
initial.commit09911bf2008-07-26 23:55:29590 LogRendererHang();
591 break;
592
jam@chromium.orga27a9382009-02-11 23:55:10593 case NotificationType::CHILD_PROCESS_HOST_CONNECTED:
594 case NotificationType::CHILD_PROCESS_CRASHED:
595 case NotificationType::CHILD_INSTANCE_CREATED:
596 LogChildProcessChange(type, source, details);
initial.commit09911bf2008-07-26 23:55:29597 break;
598
brettw@chromium.orgbfd04a62009-02-01 18:16:56599 case NotificationType::TEMPLATE_URL_MODEL_LOADED:
initial.commit09911bf2008-07-26 23:55:29600 LogKeywords(Source<TemplateURLModel>(source).ptr());
601 break;
602
ananta@chromium.org1226abb2010-06-10 18:01:28603 case NotificationType::OMNIBOX_OPENED_URL: {
604 MetricsLog* current_log = current_log_->AsMetricsLog();
605 DCHECK(current_log);
606 current_log->RecordOmniboxOpenedURL(
initial.commit09911bf2008-07-26 23:55:29607 *Details<AutocompleteLog>(details).ptr());
608 break;
ananta@chromium.org1226abb2010-06-10 18:01:28609 }
initial.commit09911bf2008-07-26 23:55:29610
tim@chromium.orgb61236c62009-04-09 22:43:55611 case NotificationType::BOOKMARK_MODEL_LOADED: {
612 Profile* p = Source<Profile>(source).ptr();
613 if (p)
614 LogBookmarks(p->GetBookmarkModel());
initial.commit09911bf2008-07-26 23:55:29615 break;
tim@chromium.orgb61236c62009-04-09 22:43:55616 }
initial.commit09911bf2008-07-26 23:55:29617 default:
jar@chromium.orgb42c5e42010-06-03 20:43:25618 LOG(DFATAL);
initial.commit09911bf2008-07-26 23:55:29619 break;
620 }
petersont@google.comd01b8732008-10-16 02:18:07621
622 HandleIdleSinceLastTransmission(false);
623
624 if (current_log_)
jar@chromium.org281d2882009-01-20 20:32:42625 DLOG(INFO) << "METRICS: NUMBER OF EVENTS = " << current_log_->num_events();
petersont@google.comd01b8732008-10-16 02:18:07626}
627
628void MetricsService::HandleIdleSinceLastTransmission(bool in_idle) {
629 // If there wasn't a lot of action, maybe the computer was asleep, in which
630 // case, the log transmissions should have stopped. Here we start them up
631 // again.
pkasting@chromium.orgcac78842008-11-27 01:02:20632 if (!in_idle && idle_since_last_transmission_)
633 StartLogTransmissionTimer();
634 idle_since_last_transmission_ = in_idle;
initial.commit09911bf2008-07-26 23:55:29635}
636
637void MetricsService::RecordCleanShutdown() {
638 RecordBooleanPrefValue(prefs::kStabilityExitedCleanly, true);
639}
640
641void MetricsService::RecordStartOfSessionEnd() {
642 RecordBooleanPrefValue(prefs::kStabilitySessionEndCompleted, false);
643}
644
645void MetricsService::RecordCompletedSessionEnd() {
646 RecordBooleanPrefValue(prefs::kStabilitySessionEndCompleted, true);
647}
648
cpu@google.come73c01972008-08-13 00:18:24649void MetricsService:: RecordBreakpadRegistration(bool success) {
jar@google.com68475e602008-08-22 03:21:15650 if (!success)
cpu@google.come73c01972008-08-13 00:18:24651 IncrementPrefValue(prefs::kStabilityBreakpadRegistrationFail);
652 else
653 IncrementPrefValue(prefs::kStabilityBreakpadRegistrationSuccess);
654}
655
656void MetricsService::RecordBreakpadHasDebugger(bool has_debugger) {
657 if (!has_debugger)
658 IncrementPrefValue(prefs::kStabilityDebuggerNotPresent);
659 else
jar@google.com68475e602008-08-22 03:21:15660 IncrementPrefValue(prefs::kStabilityDebuggerPresent);
cpu@google.come73c01972008-08-13 00:18:24661}
662
initial.commit09911bf2008-07-26 23:55:29663//------------------------------------------------------------------------------
664// private methods
665//------------------------------------------------------------------------------
666
667
668//------------------------------------------------------------------------------
669// Initialization methods
670
671void MetricsService::InitializeMetricsState() {
kuchhal@chromium.org79bf0b72009-04-27 21:30:55672#if defined(OS_POSIX)
673 server_url_ = L"https://clients4.google.com/firefox/metrics/collect";
674#else
675 BrowserDistribution* dist = BrowserDistribution::GetDistribution();
676 server_url_ = dist->GetStatsServerURL();
677#endif
678
initial.commit09911bf2008-07-26 23:55:29679 PrefService* pref = g_browser_process->local_state();
680 DCHECK(pref);
681
jar@chromium.org225c50842010-01-19 21:19:13682 if ((pref->GetInt64(prefs::kStabilityStatsBuildTime)
683 != MetricsLog::GetBuildTime()) ||
estade@chromium.orgddd231e2010-06-29 20:35:19684 (pref->GetString(prefs::kStabilityStatsVersion)
jar@chromium.org225c50842010-01-19 21:19:13685 != MetricsLog::GetVersionString())) {
jar@chromium.org541f77922009-02-23 21:14:38686 // This is a new version, so we don't want to confuse the stats about the
687 // old version with info that we upload.
688 DiscardOldStabilityStats(pref);
689 pref->SetString(prefs::kStabilityStatsVersion,
estade@chromium.orgddd231e2010-06-29 20:35:19690 MetricsLog::GetVersionString());
jar@chromium.org225c50842010-01-19 21:19:13691 pref->SetInt64(prefs::kStabilityStatsBuildTime,
692 MetricsLog::GetBuildTime());
jar@chromium.org541f77922009-02-23 21:14:38693 }
694
initial.commit09911bf2008-07-26 23:55:29695 // Update session ID
696 session_id_ = pref->GetInteger(prefs::kMetricsSessionID);
697 ++session_id_;
698 pref->SetInteger(prefs::kMetricsSessionID, session_id_);
699
initial.commit09911bf2008-07-26 23:55:29700 // Stability bookkeeping
cpu@google.come73c01972008-08-13 00:18:24701 IncrementPrefValue(prefs::kStabilityLaunchCount);
initial.commit09911bf2008-07-26 23:55:29702
cpu@google.come73c01972008-08-13 00:18:24703 if (!pref->GetBoolean(prefs::kStabilityExitedCleanly)) {
704 IncrementPrefValue(prefs::kStabilityCrashCount);
initial.commit09911bf2008-07-26 23:55:29705 }
cpu@google.come73c01972008-08-13 00:18:24706
707 // This will be set to 'true' if we exit cleanly.
initial.commit09911bf2008-07-26 23:55:29708 pref->SetBoolean(prefs::kStabilityExitedCleanly, false);
709
cpu@google.come73c01972008-08-13 00:18:24710 if (!pref->GetBoolean(prefs::kStabilitySessionEndCompleted)) {
711 IncrementPrefValue(prefs::kStabilityIncompleteSessionEndCount);
jar@chromium.orgc9abf242009-07-18 06:00:38712 // This is marked false when we get a WM_ENDSESSION.
713 pref->SetBoolean(prefs::kStabilitySessionEndCompleted, true);
initial.commit09911bf2008-07-26 23:55:29714 }
initial.commit09911bf2008-07-26 23:55:29715
jar@chromium.org9165f742010-03-10 22:55:01716 // Initialize uptime counters.
717 int64 startup_uptime = MetricsLog::GetIncrementalUptime(pref);
mad@google.comae393ec702010-06-27 16:23:14718 DCHECK_EQ(0, startup_uptime);
jar@chromium.org9165f742010-03-10 22:55:01719 // For backwards compatibility, leave this intact in case Omaha is checking
720 // them. prefs::kStabilityLastTimestampSec may also be useless now.
721 // TODO(jar): Delete these if they have no uses.
robertshield@google.com0bb1a622009-03-04 03:22:32722 pref->SetInt64(prefs::kStabilityLaunchTimeSec, Time::Now().ToTimeT());
723
724 // Bookkeeping for the uninstall metrics.
725 IncrementLongPrefsValue(prefs::kUninstallLaunchCount);
initial.commit09911bf2008-07-26 23:55:29726
727 // Save profile metrics.
728 PrefService* prefs = g_browser_process->local_state();
729 if (prefs) {
730 // Remove the current dictionary and store it for use when sending data to
731 // server. By removing the value we prune potentially dead profiles
732 // (and keys). All valid values are added back once services startup.
733 const DictionaryValue* profile_dictionary =
734 prefs->GetDictionary(prefs::kProfileMetrics);
735 if (profile_dictionary) {
736 // Do a deep copy of profile_dictionary since ClearPref will delete it.
737 profile_dictionary_.reset(static_cast<DictionaryValue*>(
738 profile_dictionary->DeepCopy()));
739 prefs->ClearPref(prefs::kProfileMetrics);
740 }
741 }
742
jar@chromium.org92745242009-06-12 16:52:21743 // Get stats on use of command line.
744 const CommandLine* command_line(CommandLine::ForCurrentProcess());
745 size_t common_commands = 0;
746 if (command_line->HasSwitch(switches::kUserDataDir)) {
747 ++common_commands;
748 UMA_HISTOGRAM_COUNTS_100("Chrome.CommandLineDatDirCount", 1);
749 }
750
751 if (command_line->HasSwitch(switches::kApp)) {
752 ++common_commands;
753 UMA_HISTOGRAM_COUNTS_100("Chrome.CommandLineAppModeCount", 1);
754 }
755
756 UMA_HISTOGRAM_COUNTS_100("Chrome.CommandLineFlagCount",
757 command_line->GetSwitchCount());
758 UMA_HISTOGRAM_COUNTS_100("Chrome.CommandLineUncommonFlagCount",
759 command_line->GetSwitchCount() - common_commands);
760
initial.commit09911bf2008-07-26 23:55:29761 // Kick off the process of saving the state (so the uptime numbers keep
762 // getting updated) every n minutes.
763 ScheduleNextStateSave();
764}
765
zelidrag@chromium.org85ed9d42010-06-08 22:37:44766void MetricsService::OnInitTaskComplete(
767 const std::string& hardware_class,
jam@chromium.org35fa6a22009-08-15 00:04:01768 const std::vector<WebPluginInfo>& plugins) {
zelidrag@chromium.org85ed9d42010-06-08 22:37:44769 DCHECK(state_ == INIT_TASK_SCHEDULED);
770 hardware_class_ = hardware_class;
jam@chromium.org35fa6a22009-08-15 00:04:01771 plugins_ = plugins;
zelidrag@chromium.org85ed9d42010-06-08 22:37:44772 if (state_ == INIT_TASK_SCHEDULED)
773 state_ = INIT_TASK_DONE;
initial.commit09911bf2008-07-26 23:55:29774}
775
776std::string MetricsService::GenerateClientID() {
paul@chromium.orgdc6f4962009-02-13 01:25:50777#if defined(OS_WIN)
initial.commit09911bf2008-07-26 23:55:29778 const int kGUIDSize = 39;
779
780 GUID guid;
781 HRESULT guid_result = CoCreateGuid(&guid);
782 DCHECK(SUCCEEDED(guid_result));
783
784 std::wstring guid_string;
785 int result = StringFromGUID2(guid,
786 WriteInto(&guid_string, kGUIDSize), kGUIDSize);
787 DCHECK(result == kGUIDSize);
788
789 return WideToUTF8(guid_string.substr(1, guid_string.length() - 2));
evan@chromium.org271b24f2009-07-28 16:05:51790#else
sky@chromium.org06aaac22009-07-08 20:54:13791 uint64 sixteen_bytes[2] = { base::RandUint64(), base::RandUint64() };
792 return RandomBytesToGUIDString(sixteen_bytes);
paul@chromium.orgdc6f4962009-02-13 01:25:50793#endif
initial.commit09911bf2008-07-26 23:55:29794}
795
sky@chromium.org06aaac22009-07-08 20:54:13796#if defined(OS_POSIX)
797// TODO(cmasone): Once we're comfortable this works, migrate Windows code to
798// use this as well.
799std::string MetricsService::RandomBytesToGUIDString(const uint64 bytes[2]) {
evan@chromium.org34b2b002009-11-20 06:53:28800 return StringPrintf("%08X-%04X-%04X-%04X-%012llX",
801 static_cast<unsigned int>(bytes[0] >> 32),
802 static_cast<unsigned int>((bytes[0] >> 16) & 0x0000ffff),
803 static_cast<unsigned int>(bytes[0] & 0x0000ffff),
804 static_cast<unsigned int>(bytes[1] >> 48),
sky@chromium.org06aaac22009-07-08 20:54:13805 bytes[1] & 0x0000ffffffffffffULL);
806}
807#endif
initial.commit09911bf2008-07-26 23:55:29808
809//------------------------------------------------------------------------------
810// State save methods
811
812void MetricsService::ScheduleNextStateSave() {
813 state_saver_factory_.RevokeAll();
814
815 MessageLoop::current()->PostDelayedTask(FROM_HERE,
816 state_saver_factory_.NewRunnableMethod(&MetricsService::SaveLocalState),
817 kSaveStateInterval * 1000);
818}
819
820void MetricsService::SaveLocalState() {
821 PrefService* pref = g_browser_process->local_state();
822 if (!pref) {
jar@chromium.orgb42c5e42010-06-03 20:43:25823 LOG(DFATAL);
initial.commit09911bf2008-07-26 23:55:29824 return;
825 }
826
827 RecordCurrentState(pref);
phajdan.jr@chromium.org6faa0e0d2009-04-28 06:50:36828 pref->ScheduleSavePersistentPrefs();
initial.commit09911bf2008-07-26 23:55:29829
jar@chromium.org281d2882009-01-20 20:32:42830 // TODO(jar): Does this run down the batteries????
initial.commit09911bf2008-07-26 23:55:29831 ScheduleNextStateSave();
832}
833
834
835//------------------------------------------------------------------------------
836// Recording control methods
837
838void MetricsService::StartRecording() {
839 if (current_log_)
840 return;
841
842 current_log_ = new MetricsLog(client_id_, session_id_);
843 if (state_ == INITIALIZED) {
844 // We only need to schedule that run once.
zelidrag@chromium.org85ed9d42010-06-08 22:37:44845 state_ = INIT_TASK_SCHEDULED;
initial.commit09911bf2008-07-26 23:55:29846
zelidrag@chromium.org85ed9d42010-06-08 22:37:44847 // Schedules a task on the file thread for execution of slower
848 // initialization steps (such as plugin list generation) necessary
849 // for sending the initial log. This avoids blocking the main UI
850 // thread.
jamesr@chromium.org7f2e792e2009-11-30 23:18:29851 g_browser_process->file_thread()->message_loop()->PostDelayedTask(FROM_HERE,
zelidrag@chromium.org85ed9d42010-06-08 22:37:44852 new InitTask(MessageLoop::current()),
petersont@google.com252873ef2008-08-04 21:59:45853 kInitialInterlogDuration * 1000 / 2);
initial.commit09911bf2008-07-26 23:55:29854 }
855}
856
ananta@chromium.org1226abb2010-06-10 18:01:28857void MetricsService::StopRecording(MetricsLogBase** log) {
initial.commit09911bf2008-07-26 23:55:29858 if (!current_log_)
859 return;
860
ananta@chromium.org1226abb2010-06-10 18:01:28861 MetricsLog* current_log = current_log_->AsMetricsLog();
862 DCHECK(current_log);
863 current_log->set_hardware_class(hardware_class_); // Adds to ongoing logs.
zelidrag@chromium.org85ed9d42010-06-08 22:37:44864
jar@google.com68475e602008-08-22 03:21:15865 // TODO(jar): Integrate bounds on log recording more consistently, so that we
866 // can stop recording logs that are too big much sooner.
petersont@google.comd01b8732008-10-16 02:18:07867 if (current_log_->num_events() > log_event_limit_) {
dsh@google.com553dba62009-02-24 19:08:23868 UMA_HISTOGRAM_COUNTS("UMA.Discarded Log Events",
jar@google.com68475e602008-08-22 03:21:15869 current_log_->num_events());
870 current_log_->CloseLog();
871 delete current_log_;
jar@google.com294638782008-09-24 00:22:41872 current_log_ = NULL;
jar@google.com68475e602008-08-22 03:21:15873 StartRecording(); // Start trivial log to hold our histograms.
874 }
875
jar@google.com0b33f80b2008-12-17 21:34:36876 // Put incremental data (histogram deltas, and realtime stats deltas) at the
jar@google.com147bbc0b2009-01-06 19:37:40877 // end of all log transmissions (initial log handles this separately).
initial.commit09911bf2008-07-26 23:55:29878 // Don't bother if we're going to discard current_log_.
jar@google.com0b33f80b2008-12-17 21:34:36879 if (log) {
ananta@chromium.org1226abb2010-06-10 18:01:28880 current_log->RecordIncrementalStabilityElements();
initial.commit09911bf2008-07-26 23:55:29881 RecordCurrentHistograms();
jar@google.com0b33f80b2008-12-17 21:34:36882 }
initial.commit09911bf2008-07-26 23:55:29883
884 current_log_->CloseLog();
pkasting@chromium.orgcac78842008-11-27 01:02:20885 if (log)
ananta@chromium.org1226abb2010-06-10 18:01:28886 *log = current_log;
pkasting@chromium.orgcac78842008-11-27 01:02:20887 else
initial.commit09911bf2008-07-26 23:55:29888 delete current_log_;
initial.commit09911bf2008-07-26 23:55:29889 current_log_ = NULL;
890}
891
initial.commit09911bf2008-07-26 23:55:29892void MetricsService::PushPendingLogsToUnsentLists() {
893 if (state_ < INITIAL_LOG_READY)
avi@google.com28ab7f92009-01-06 21:39:04894 return; // We didn't and still don't have time to get plugin list etc.
initial.commit09911bf2008-07-26 23:55:29895
896 if (pending_log()) {
897 PreparePendingLogText();
898 if (state_ == INITIAL_LOG_READY) {
899 // We may race here, and send second copy of initial log later.
ziadh@chromium.org46f89e142010-07-19 08:00:42900 unsent_initial_logs_.push_back(compressed_log_);
petersont@google.comd01b8732008-10-16 02:18:07901 state_ = SEND_OLD_INITIAL_LOGS;
initial.commit09911bf2008-07-26 23:55:29902 } else {
jar@chromium.org281d2882009-01-20 20:32:42903 // TODO(jar): Verify correctness in other states, including sending unsent
jar@chromium.org541f77922009-02-23 21:14:38904 // initial logs.
jar@google.com68475e602008-08-22 03:21:15905 PushPendingLogTextToUnsentOngoingLogs();
initial.commit09911bf2008-07-26 23:55:29906 }
907 DiscardPendingLog();
908 }
909 DCHECK(!pending_log());
910 StopRecording(&pending_log_);
911 PreparePendingLogText();
jar@google.com68475e602008-08-22 03:21:15912 PushPendingLogTextToUnsentOngoingLogs();
initial.commit09911bf2008-07-26 23:55:29913 DiscardPendingLog();
914 StoreUnsentLogs();
915}
916
jar@google.com68475e602008-08-22 03:21:15917void MetricsService::PushPendingLogTextToUnsentOngoingLogs() {
petersont@google.comd01b8732008-10-16 02:18:07918 // If UMA response told us not to upload, there's no need to save the pending
919 // log. It wasn't supposed to be uploaded anyway.
920 if (!server_permits_upload_)
921 return;
ziadh@chromium.org46f89e142010-07-19 08:00:42922 if (compressed_log_.length() >
paul@chromium.orgdc6f4962009-02-13 01:25:50923 static_cast<size_t>(kUploadLogAvoidRetransmitSize)) {
dsh@google.com553dba62009-02-24 19:08:23924 UMA_HISTOGRAM_COUNTS("UMA.Large Accumulated Log Not Persisted",
ziadh@chromium.org46f89e142010-07-19 08:00:42925 static_cast<int>(compressed_log_.length()));
jar@google.com68475e602008-08-22 03:21:15926 return;
927 }
ziadh@chromium.org46f89e142010-07-19 08:00:42928 unsent_ongoing_logs_.push_back(compressed_log_);
jar@google.com68475e602008-08-22 03:21:15929}
930
initial.commit09911bf2008-07-26 23:55:29931//------------------------------------------------------------------------------
932// Transmission of logs methods
933
934void MetricsService::StartLogTransmissionTimer() {
petersont@google.comd01b8732008-10-16 02:18:07935 // If we're not reporting, there's no point in starting a log transmission
936 // timer.
937 if (!reporting_active())
938 return;
939
initial.commit09911bf2008-07-26 23:55:29940 if (!current_log_)
941 return; // Recorder is shutdown.
petersont@google.comd01b8732008-10-16 02:18:07942
943 // If there is already a timer running, we leave it running.
944 // If timer_pending is true because the fetch is waiting for a response,
945 // we return for now and let the response handler start the timer.
946 if (timer_pending_)
initial.commit09911bf2008-07-26 23:55:29947 return;
petersont@google.comd01b8732008-10-16 02:18:07948
petersont@google.comd01b8732008-10-16 02:18:07949 // Before starting the timer, set timer_pending_ to true.
initial.commit09911bf2008-07-26 23:55:29950 timer_pending_ = true;
petersont@google.comd01b8732008-10-16 02:18:07951
952 // Right before the UMA transmission gets started, there's one more thing we'd
953 // like to record: the histogram of memory usage, so we spawn a task to
jar@chromium.orgc9a3ef82009-05-28 22:02:46954 // collect the memory details and when that task is finished, it will call
955 // OnMemoryDetailCollectionDone, which will call HistogramSynchronization to
956 // collect histograms from all renderers and then we will call
957 // OnHistogramSynchronizationDone to continue processing.
initial.commit09911bf2008-07-26 23:55:29958 MessageLoop::current()->PostDelayedTask(FROM_HERE,
959 log_sender_factory_.
jar@chromium.orgc9a3ef82009-05-28 22:02:46960 NewRunnableMethod(&MetricsService::LogTransmissionTimerDone),
phajdan.jr@chromium.org743ace42009-06-17 17:23:51961 interlog_duration_.InMilliseconds());
initial.commit09911bf2008-07-26 23:55:29962}
963
jar@chromium.orgc9a3ef82009-05-28 22:02:46964void MetricsService::LogTransmissionTimerDone() {
965 Task* task = log_sender_factory_.
966 NewRunnableMethod(&MetricsService::OnMemoryDetailCollectionDone);
967
jam@chromium.orge9adedb2009-12-01 22:23:59968 scoped_refptr<MetricsMemoryDetails> details = new MetricsMemoryDetails(task);
jar@chromium.orgc9a3ef82009-05-28 22:02:46969 details->StartFetch();
970
971 // Collect WebCore cache information to put into a histogram.
pkasting@chromium.org019191a2009-10-02 20:37:27972 for (RenderProcessHost::iterator i(RenderProcessHost::AllHostsIterator());
973 !i.IsAtEnd(); i.Advance())
974 i.GetCurrentValue()->Send(new ViewMsg_GetCacheResourceStats());
jar@chromium.orgc9a3ef82009-05-28 22:02:46975}
976
977void MetricsService::OnMemoryDetailCollectionDone() {
978 DCHECK(IsSingleThreaded());
979
980 // HistogramSynchronizer will Collect histograms from all renderers and it
981 // will call OnHistogramSynchronizationDone (if wait time elapses before it
982 // heard from all renderers, then also it will call
983 // OnHistogramSynchronizationDone).
984
985 // Create a callback_task for OnHistogramSynchronizationDone.
986 Task* callback_task = log_sender_factory_.NewRunnableMethod(
987 &MetricsService::OnHistogramSynchronizationDone);
988
989 // Set up the callback to task to call after we receive histograms from all
990 // renderer processes. Wait time specifies how long to wait before absolutely
991 // calling us back on the task.
992 HistogramSynchronizer::FetchRendererHistogramsAsynchronously(
993 MessageLoop::current(), callback_task,
994 kMaxHistogramGatheringWaitDuration);
995}
996
997void MetricsService::OnHistogramSynchronizationDone() {
initial.commit09911bf2008-07-26 23:55:29998 DCHECK(IsSingleThreaded());
999
petersont@google.comd01b8732008-10-16 02:18:071000 // This function should only be called via timer, so timer_pending_
1001 // should be true.
1002 DCHECK(timer_pending_);
1003 timer_pending_ = false;
initial.commit09911bf2008-07-26 23:55:291004
1005 DCHECK(!current_fetch_.get());
initial.commit09911bf2008-07-26 23:55:291006
petersont@google.comd01b8732008-10-16 02:18:071007 // If we're getting no notifications, then the log won't have much in it, and
1008 // it's possible the computer is about to go to sleep, so don't upload and
1009 // don't restart the transmission timer.
1010 if (idle_since_last_transmission_)
1011 return;
1012
1013 // If somehow there is a fetch in progress, we return setting timer_pending_
1014 // to true and hope things work out.
1015 if (current_fetch_.get()) {
1016 timer_pending_ = true;
1017 return;
1018 }
1019
1020 // If uploads are forbidden by UMA response, there's no point in keeping
1021 // the current_log_, and the more often we delete it, the less likely it is
1022 // to expand forever.
1023 if (!server_permits_upload_ && current_log_) {
1024 StopRecording(NULL);
1025 StartRecording();
1026 }
initial.commit09911bf2008-07-26 23:55:291027
1028 if (!current_log_)
1029 return; // Logging was disabled.
petersont@google.comd01b8732008-10-16 02:18:071030 if (!reporting_active())
initial.commit09911bf2008-07-26 23:55:291031 return; // Don't do work if we're not going to send anything now.
1032
petersont@google.comd01b8732008-10-16 02:18:071033 MakePendingLog();
initial.commit09911bf2008-07-26 23:55:291034
petersont@google.comd01b8732008-10-16 02:18:071035 // MakePendingLog should have put something in the pending log, if it didn't,
1036 // we start the timer again, return and hope things work out.
1037 if (!pending_log()) {
1038 StartLogTransmissionTimer();
1039 return;
1040 }
initial.commit09911bf2008-07-26 23:55:291041
petersont@google.comd01b8732008-10-16 02:18:071042 // If we're not supposed to upload any UMA data because the response or the
1043 // user said so, cancel the upload at this point, but start the timer.
1044 if (!TransmissionPermitted()) {
1045 DiscardPendingLog();
1046 StartLogTransmissionTimer();
1047 return;
1048 }
initial.commit09911bf2008-07-26 23:55:291049
petersont@google.comd01b8732008-10-16 02:18:071050 PrepareFetchWithPendingLog();
1051
1052 if (!current_fetch_.get()) {
1053 // Compression failed, and log discarded :-/.
1054 DiscardPendingLog();
1055 StartLogTransmissionTimer(); // Maybe we'll do better next time
1056 // TODO(jar): If compression failed, we should have created a tiny log and
1057 // compressed that, so that we can signal that we're losing logs.
1058 return;
1059 }
1060
1061 DCHECK(!timer_pending_);
1062
1063 // The URL fetch is a like timer in that after a while we get called back
1064 // so we set timer_pending_ true just as we start the url fetch.
1065 timer_pending_ = true;
1066 current_fetch_->Start();
1067
1068 HandleIdleSinceLastTransmission(true);
1069}
1070
1071
1072void MetricsService::MakePendingLog() {
1073 if (pending_log())
1074 return;
1075
1076 switch (state_) {
1077 case INITIALIZED:
zelidrag@chromium.org85ed9d42010-06-08 22:37:441078 case INIT_TASK_SCHEDULED: // We should be further along by now.
petersont@google.comd01b8732008-10-16 02:18:071079 DCHECK(false);
1080 return;
1081
zelidrag@chromium.org85ed9d42010-06-08 22:37:441082 case INIT_TASK_DONE:
petersont@google.comd01b8732008-10-16 02:18:071083 // We need to wait for the initial log to be ready before sending
1084 // anything, because the server will tell us whether it wants to hear
1085 // from us.
1086 PrepareInitialLog();
zelidrag@chromium.org85ed9d42010-06-08 22:37:441087 DCHECK(state_ == INIT_TASK_DONE);
petersont@google.comd01b8732008-10-16 02:18:071088 RecallUnsentLogs();
1089 state_ = INITIAL_LOG_READY;
1090 break;
1091
1092 case SEND_OLD_INITIAL_LOGS:
pkasting@chromium.orgcac78842008-11-27 01:02:201093 if (!unsent_initial_logs_.empty()) {
ziadh@chromium.org46f89e142010-07-19 08:00:421094 compressed_log_ = unsent_initial_logs_.back();
pkasting@chromium.orgcac78842008-11-27 01:02:201095 break;
1096 }
petersont@google.comd01b8732008-10-16 02:18:071097 state_ = SENDING_OLD_LOGS;
1098 // Fall through.
initial.commit09911bf2008-07-26 23:55:291099
petersont@google.comd01b8732008-10-16 02:18:071100 case SENDING_OLD_LOGS:
1101 if (!unsent_ongoing_logs_.empty()) {
ziadh@chromium.org46f89e142010-07-19 08:00:421102 compressed_log_ = unsent_ongoing_logs_.back();
petersont@google.comd01b8732008-10-16 02:18:071103 break;
1104 }
1105 state_ = SENDING_CURRENT_LOGS;
1106 // Fall through.
1107
1108 case SENDING_CURRENT_LOGS:
1109 StopRecording(&pending_log_);
1110 StartRecording();
1111 break;
1112
1113 default:
jar@chromium.orgb42c5e42010-06-03 20:43:251114 LOG(DFATAL);
petersont@google.comd01b8732008-10-16 02:18:071115 return;
1116 }
1117
1118 DCHECK(pending_log());
1119}
1120
1121bool MetricsService::TransmissionPermitted() const {
1122 // If the user forbids uploading that's they're business, and we don't upload
1123 // anything. If the server forbids uploading, that's our business, so we take
1124 // that to mean it forbids current logs, but we still send up the inital logs
1125 // and any old logs.
petersont@google.comd01b8732008-10-16 02:18:071126 if (!user_permits_upload_)
1127 return false;
pkasting@chromium.orgcac78842008-11-27 01:02:201128 if (server_permits_upload_)
petersont@google.comd01b8732008-10-16 02:18:071129 return true;
initial.commit09911bf2008-07-26 23:55:291130
pkasting@chromium.orgcac78842008-11-27 01:02:201131 switch (state_) {
1132 case INITIAL_LOG_READY:
1133 case SEND_OLD_INITIAL_LOGS:
1134 case SENDING_OLD_LOGS:
1135 return true;
1136
1137 case SENDING_CURRENT_LOGS:
1138 default:
1139 return false;
nsylvain@chromium.org8c8824b2008-09-20 01:55:501140 }
initial.commit09911bf2008-07-26 23:55:291141}
1142
initial.commit09911bf2008-07-26 23:55:291143void MetricsService::PrepareInitialLog() {
zelidrag@chromium.org85ed9d42010-06-08 22:37:441144 DCHECK(state_ == INIT_TASK_DONE);
initial.commit09911bf2008-07-26 23:55:291145
1146 MetricsLog* log = new MetricsLog(client_id_, session_id_);
zelidrag@chromium.org85ed9d42010-06-08 22:37:441147 log->set_hardware_class(hardware_class_); // Adds to initial log.
jam@chromium.org35fa6a22009-08-15 00:04:011148 log->RecordEnvironment(plugins_, profile_dictionary_.get());
initial.commit09911bf2008-07-26 23:55:291149
1150 // Histograms only get written to current_log_, so setup for the write.
ananta@chromium.org1226abb2010-06-10 18:01:281151 MetricsLogBase* save_log = current_log_;
initial.commit09911bf2008-07-26 23:55:291152 current_log_ = log;
1153 RecordCurrentHistograms(); // Into current_log_... which is really log.
1154 current_log_ = save_log;
1155
1156 log->CloseLog();
1157 DCHECK(!pending_log());
1158 pending_log_ = log;
1159}
1160
ziadh@chromium.org46f89e142010-07-19 08:00:421161// static
1162MetricsService::LogRecallStatus MetricsService::RecallUnsentLogsHelper(
1163 const ListValue& list,
1164 std::vector<std::string>* local_list) {
1165 DCHECK(local_list->empty());
1166 if (list.GetSize() == 0)
1167 return MakeRecallStatusHistogram(LIST_EMPTY);
1168 if (list.GetSize() < 3)
1169 return MakeRecallStatusHistogram(LIST_SIZE_TOO_SMALL);
initial.commit09911bf2008-07-26 23:55:291170
ziadh@chromium.org46f89e142010-07-19 08:00:421171 // The size is stored at the beginning of the list.
1172 int size;
1173 bool valid = (*list.begin())->GetAsInteger(&size);
1174 if (!valid)
1175 return MakeRecallStatusHistogram(LIST_SIZE_MISSING);
1176
1177 // Account for checksum and size included in the list.
1178 if (static_cast<unsigned int>(size) !=
1179 list.GetSize() - kChecksumEntryCount)
1180 return MakeRecallStatusHistogram(LIST_SIZE_CORRUPTION);
1181
1182 MD5Context ctx;
1183 MD5Init(&ctx);
1184 std::string encoded_log;
1185 std::string decoded_log;
1186 for (ListValue::const_iterator it = list.begin() + 1;
1187 it != list.end() - 1; ++it) { // Last element is the checksum.
1188 valid = (*it)->GetAsString(&encoded_log);
1189 if (!valid) {
1190 local_list->clear();
1191 return MakeRecallStatusHistogram(LOG_STRING_CORRUPTION);
1192 }
1193
1194 MD5Update(&ctx, encoded_log.data(), encoded_log.length());
1195
1196 if (!base::Base64Decode(encoded_log, &decoded_log)) {
1197 local_list->clear();
1198 return MakeRecallStatusHistogram(DECODE_FAIL);
1199 }
1200 local_list->push_back(decoded_log);
1201 }
1202
1203 // Verify checksum.
1204 MD5Digest digest;
1205 MD5Final(&digest, &ctx);
1206 std::string recovered_md5;
1207 // We store the hash at the end of the list.
1208 valid = (*(list.end() - 1))->GetAsString(&recovered_md5);
1209 if (!valid) {
1210 local_list->clear();
1211 return MakeRecallStatusHistogram(CHECKSUM_STRING_CORRUPTION);
1212 }
1213 if (recovered_md5 != MD5DigestToBase16(digest)) {
1214 local_list->clear();
1215 return MakeRecallStatusHistogram(CHECKSUM_CORRUPTION);
1216 }
1217 return MakeRecallStatusHistogram(RECALL_SUCCESS);
1218}
1219void MetricsService::RecallUnsentLogs() {
initial.commit09911bf2008-07-26 23:55:291220 PrefService* local_state = g_browser_process->local_state();
1221 DCHECK(local_state);
1222
1223 ListValue* unsent_initial_logs = local_state->GetMutableList(
1224 prefs::kMetricsInitialLogs);
ziadh@chromium.org46f89e142010-07-19 08:00:421225 RecallUnsentLogsHelper(*unsent_initial_logs, &unsent_initial_logs_);
initial.commit09911bf2008-07-26 23:55:291226
1227 ListValue* unsent_ongoing_logs = local_state->GetMutableList(
1228 prefs::kMetricsOngoingLogs);
ziadh@chromium.org46f89e142010-07-19 08:00:421229 RecallUnsentLogsHelper(*unsent_ongoing_logs, &unsent_ongoing_logs_);
1230}
1231
1232// static
1233void MetricsService::StoreUnsentLogsHelper(
1234 const std::vector<std::string>& local_list,
1235 const size_t kMaxLocalListSize,
1236 ListValue* list) {
1237 list->Clear();
1238 size_t start = 0;
1239 if (local_list.size() > kMaxLocalListSize)
1240 start = local_list.size() - kMaxLocalListSize;
1241 DCHECK(start <= local_list.size());
1242 if (local_list.size() == start)
1243 return;
1244
1245 // Store size at the beginning of the list.
1246 list->Append(Value::CreateIntegerValue(local_list.size() - start));
1247
1248 MD5Context ctx;
1249 MD5Init(&ctx);
1250 std::string encoded_log;
1251 for (std::vector<std::string>::const_iterator it = local_list.begin() + start;
1252 it != local_list.end(); ++it) {
1253 // We encode the compressed log as Value::CreateStringValue() expects to
1254 // take a valid UTF8 string.
1255 if (!base::Base64Encode(*it, &encoded_log)) {
1256 MakeStoreStatusHistogram(ENCODE_FAIL);
1257 list->Clear();
1258 return;
1259 }
1260 MD5Update(&ctx, encoded_log.data(), encoded_log.length());
1261 list->Append(Value::CreateStringValue(encoded_log));
initial.commit09911bf2008-07-26 23:55:291262 }
ziadh@chromium.org46f89e142010-07-19 08:00:421263
1264 // Append hash to the end of the list.
1265 MD5Digest digest;
1266 MD5Final(&digest, &ctx);
1267 list->Append(Value::CreateStringValue(MD5DigestToBase16(digest)));
1268 DCHECK(list->GetSize() >= 3); // Minimum of 3 elements (size, data, hash).
initial.commit09911bf2008-07-26 23:55:291269}
1270
1271void MetricsService::StoreUnsentLogs() {
1272 if (state_ < INITIAL_LOG_READY)
1273 return; // We never Recalled the prior unsent logs.
1274
1275 PrefService* local_state = g_browser_process->local_state();
1276 DCHECK(local_state);
1277
1278 ListValue* unsent_initial_logs = local_state->GetMutableList(
1279 prefs::kMetricsInitialLogs);
ziadh@chromium.org46f89e142010-07-19 08:00:421280 StoreUnsentLogsHelper(unsent_initial_logs_, kMaxInitialLogsPersisted,
1281 unsent_initial_logs);
initial.commit09911bf2008-07-26 23:55:291282
1283 ListValue* unsent_ongoing_logs = local_state->GetMutableList(
1284 prefs::kMetricsOngoingLogs);
ziadh@chromium.org46f89e142010-07-19 08:00:421285 StoreUnsentLogsHelper(unsent_ongoing_logs_, kMaxOngoingLogsPersisted,
1286 unsent_ongoing_logs);
initial.commit09911bf2008-07-26 23:55:291287}
1288
1289void MetricsService::PreparePendingLogText() {
1290 DCHECK(pending_log());
ziadh@chromium.org46f89e142010-07-19 08:00:421291 if (!compressed_log_.empty())
initial.commit09911bf2008-07-26 23:55:291292 return;
mark@chromium.org9ffcccf42009-09-15 22:19:181293 int text_size = pending_log_->GetEncodedLogSize();
1294
ziadh@chromium.org46f89e142010-07-19 08:00:421295 std::string pending_log_text;
1296 // Leave room for the NULL terminator.
1297 pending_log_->GetEncodedLog(WriteInto(&pending_log_text, text_size + 1),
mark@chromium.org9ffcccf42009-09-15 22:19:181298 text_size);
ziadh@chromium.org46f89e142010-07-19 08:00:421299
1300 if (Bzip2Compress(pending_log_text, &compressed_log_)) {
1301 // Allow security conscious users to see all metrics logs that we send.
1302 LOG(INFO) << "COMPRESSED FOLLOWING METRICS LOG: " << pending_log_text;
1303 } else {
1304 LOG(DFATAL) << "Failed to compress log for transmission.";
1305 // We can't discard the logs as other caller functions expect that
1306 // |compressed_log_| not be empty. We can detect this failure at the server
1307 // after we transmit.
1308 compressed_log_ = "Unable to compress!";
1309 MakeStoreStatusHistogram(COMPRESS_FAIL);
1310 return;
1311 }
initial.commit09911bf2008-07-26 23:55:291312}
1313
petersont@google.comd01b8732008-10-16 02:18:071314void MetricsService::PrepareFetchWithPendingLog() {
initial.commit09911bf2008-07-26 23:55:291315 DCHECK(pending_log());
1316 DCHECK(!current_fetch_.get());
1317 PreparePendingLogText();
ziadh@chromium.org46f89e142010-07-19 08:00:421318 DCHECK(!compressed_log_.empty());
pkasting@chromium.orgcac78842008-11-27 01:02:201319
kuchhal@chromium.org79bf0b72009-04-27 21:30:551320 current_fetch_.reset(new URLFetcher(GURL(WideToUTF16(server_url_)),
1321 URLFetcher::POST,
initial.commit09911bf2008-07-26 23:55:291322 this));
1323 current_fetch_->set_request_context(Profile::GetDefaultRequestContext());
ziadh@chromium.org46f89e142010-07-19 08:00:421324 current_fetch_->set_upload_data(kMetricsType, compressed_log_);
initial.commit09911bf2008-07-26 23:55:291325}
1326
initial.commit09911bf2008-07-26 23:55:291327static const char* StatusToString(const URLRequestStatus& status) {
1328 switch (status.status()) {
1329 case URLRequestStatus::SUCCESS:
1330 return "SUCCESS";
1331
1332 case URLRequestStatus::IO_PENDING:
1333 return "IO_PENDING";
1334
1335 case URLRequestStatus::HANDLED_EXTERNALLY:
1336 return "HANDLED_EXTERNALLY";
1337
1338 case URLRequestStatus::CANCELED:
1339 return "CANCELED";
1340
1341 case URLRequestStatus::FAILED:
1342 return "FAILED";
1343
1344 default:
jar@chromium.orgb42c5e42010-06-03 20:43:251345 LOG(DFATAL);
initial.commit09911bf2008-07-26 23:55:291346 return "Unknown";
1347 }
1348}
1349
1350void MetricsService::OnURLFetchComplete(const URLFetcher* source,
1351 const GURL& url,
1352 const URLRequestStatus& status,
1353 int response_code,
1354 const ResponseCookies& cookies,
1355 const std::string& data) {
1356 DCHECK(timer_pending_);
1357 timer_pending_ = false;
1358 DCHECK(current_fetch_.get());
1359 current_fetch_.reset(NULL); // We're not allowed to re-use it.
1360
1361 // Confirm send so that we can move on.
jar@chromium.org281d2882009-01-20 20:32:421362 LOG(INFO) << "METRICS RESPONSE CODE: " << response_code << " status=" <<
pkasting@chromium.orgcac78842008-11-27 01:02:201363 StatusToString(status);
petersont@google.com252873ef2008-08-04 21:59:451364
jar@chromium.org0eb34fee2009-01-21 08:04:381365 // Provide boolean for error recovery (allow us to ignore response_code).
paul@chromium.orgdc6f4962009-02-13 01:25:501366 bool discard_log = false;
jar@chromium.org0eb34fee2009-01-21 08:04:381367
jar@google.com68475e602008-08-22 03:21:151368 if (response_code != 200 &&
ziadh@chromium.org46f89e142010-07-19 08:00:421369 (compressed_log_.length() >
1370 static_cast<size_t>(kUploadLogAvoidRetransmitSize))) {
dsh@google.com553dba62009-02-24 19:08:231371 UMA_HISTOGRAM_COUNTS("UMA.Large Rejected Log was Discarded",
ziadh@chromium.org46f89e142010-07-19 08:00:421372 static_cast<int>(compressed_log_.length()));
jar@chromium.org0eb34fee2009-01-21 08:04:381373 discard_log = true;
1374 } else if (response_code == 400) {
1375 // Bad syntax. Retransmission won't work.
dsh@google.com553dba62009-02-24 19:08:231376 UMA_HISTOGRAM_COUNTS("UMA.Unacceptable_Log_Discarded", state_);
jar@chromium.org0eb34fee2009-01-21 08:04:381377 discard_log = true;
jar@google.com68475e602008-08-22 03:21:151378 }
1379
jar@chromium.org0eb34fee2009-01-21 08:04:381380 if (response_code != 200 && !discard_log) {
jar@chromium.org281d2882009-01-20 20:32:421381 LOG(INFO) << "METRICS: transmission attempt returned a failure code: "
1382 << response_code << ". Verify network connectivity";
petersont@google.com252873ef2008-08-04 21:59:451383 HandleBadResponseCode();
jar@chromium.org0eb34fee2009-01-21 08:04:381384 } else { // Successful receipt (or we are discarding log).
jar@chromium.org281d2882009-01-20 20:32:421385 LOG(INFO) << "METRICS RESPONSE DATA: " << data;
initial.commit09911bf2008-07-26 23:55:291386 switch (state_) {
1387 case INITIAL_LOG_READY:
1388 state_ = SEND_OLD_INITIAL_LOGS;
1389 break;
1390
1391 case SEND_OLD_INITIAL_LOGS:
1392 DCHECK(!unsent_initial_logs_.empty());
1393 unsent_initial_logs_.pop_back();
1394 StoreUnsentLogs();
1395 break;
1396
1397 case SENDING_OLD_LOGS:
1398 DCHECK(!unsent_ongoing_logs_.empty());
1399 unsent_ongoing_logs_.pop_back();
1400 StoreUnsentLogs();
1401 break;
1402
1403 case SENDING_CURRENT_LOGS:
1404 break;
1405
1406 default:
jar@chromium.orgb42c5e42010-06-03 20:43:251407 LOG(DFATAL);
initial.commit09911bf2008-07-26 23:55:291408 break;
1409 }
petersont@google.comd01b8732008-10-16 02:18:071410
initial.commit09911bf2008-07-26 23:55:291411 DiscardPendingLog();
jar@google.com29be92552008-08-07 22:49:271412 // Since we sent a log, make sure our in-memory state is recorded to disk.
1413 PrefService* local_state = g_browser_process->local_state();
1414 DCHECK(local_state);
1415 if (local_state)
phajdan.jr@chromium.org6faa0e0d2009-04-28 06:50:361416 local_state->ScheduleSavePersistentPrefs();
petersont@google.com252873ef2008-08-04 21:59:451417
jar@google.com147bbc0b2009-01-06 19:37:401418 // Provide a default (free of exponetial backoff, other varances) in case
1419 // the server does not specify a value.
1420 interlog_duration_ = TimeDelta::FromSeconds(kMinSecondsPerLog);
1421
petersont@google.com252873ef2008-08-04 21:59:451422 GetSettingsFromResponseData(data);
petersont@google.com252873ef2008-08-04 21:59:451423 // Override server specified interlog delay if there are unsent logs to
jar@google.com29be92552008-08-07 22:49:271424 // transmit.
initial.commit09911bf2008-07-26 23:55:291425 if (unsent_logs()) {
1426 DCHECK(state_ < SENDING_CURRENT_LOGS);
1427 interlog_duration_ = TimeDelta::FromSeconds(kUnsentLogDelay);
initial.commit09911bf2008-07-26 23:55:291428 }
1429 }
petersont@google.com252873ef2008-08-04 21:59:451430
initial.commit09911bf2008-07-26 23:55:291431 StartLogTransmissionTimer();
1432}
1433
petersont@google.com252873ef2008-08-04 21:59:451434void MetricsService::HandleBadResponseCode() {
jar@chromium.org281d2882009-01-20 20:32:421435 LOG(INFO) << "Verify your metrics logs are formatted correctly. "
kuchhal@chromium.org79bf0b72009-04-27 21:30:551436 "Verify server is active at " << server_url_;
petersont@google.com252873ef2008-08-04 21:59:451437 if (!pending_log()) {
jar@chromium.org281d2882009-01-20 20:32:421438 LOG(INFO) << "METRICS: Recorder shutdown during log transmission.";
petersont@google.com252873ef2008-08-04 21:59:451439 } else {
1440 // Send progressively less frequently.
1441 DCHECK(kBackoff > 1.0);
1442 interlog_duration_ = TimeDelta::FromMicroseconds(
1443 static_cast<int64>(kBackoff * interlog_duration_.InMicroseconds()));
1444
1445 if (kMaxBackoff * TimeDelta::FromSeconds(kMinSecondsPerLog) <
pkasting@chromium.orgcac78842008-11-27 01:02:201446 interlog_duration_) {
petersont@google.com252873ef2008-08-04 21:59:451447 interlog_duration_ = kMaxBackoff *
1448 TimeDelta::FromSeconds(kMinSecondsPerLog);
pkasting@chromium.orgcac78842008-11-27 01:02:201449 }
petersont@google.com252873ef2008-08-04 21:59:451450
jar@chromium.org281d2882009-01-20 20:32:421451 LOG(INFO) << "METRICS: transmission retry being scheduled in " <<
petersont@google.com252873ef2008-08-04 21:59:451452 interlog_duration_.InSeconds() << " seconds for " <<
ziadh@chromium.org46f89e142010-07-19 08:00:421453 compressed_log_;
initial.commit09911bf2008-07-26 23:55:291454 }
initial.commit09911bf2008-07-26 23:55:291455}
1456
petersont@google.com252873ef2008-08-04 21:59:451457void MetricsService::GetSettingsFromResponseData(const std::string& data) {
1458 // We assume that the file is structured as a block opened by <response>
petersont@google.comd01b8732008-10-16 02:18:071459 // and that inside response, there is a block opened by tag <chrome_config>
1460 // other tags are ignored for now except the content of <chrome_config>.
jar@chromium.org281d2882009-01-20 20:32:421461 LOG(INFO) << "METRICS: getting settings from response data: " << data;
petersont@google.comd01b8732008-10-16 02:18:071462
petersont@google.com252873ef2008-08-04 21:59:451463 int data_size = static_cast<int>(data.size());
1464 if (data_size < 0) {
jar@chromium.org281d2882009-01-20 20:32:421465 LOG(INFO) << "METRICS: server response data bad size: " << data_size <<
pkasting@chromium.orgcac78842008-11-27 01:02:201466 "; aborting extraction of settings";
petersont@google.com252873ef2008-08-04 21:59:451467 return;
1468 }
pkasting@chromium.orgcac78842008-11-27 01:02:201469 xmlDocPtr doc = xmlReadMemory(data.c_str(), data_size, "", NULL, 0);
petersont@google.comd01b8732008-10-16 02:18:071470 // If the document is malformed, we just use the settings that were there.
1471 if (!doc) {
jar@chromium.org281d2882009-01-20 20:32:421472 LOG(INFO) << "METRICS: reading xml from server response data failed";
petersont@google.com252873ef2008-08-04 21:59:451473 return;
petersont@google.comd01b8732008-10-16 02:18:071474 }
petersont@google.com252873ef2008-08-04 21:59:451475
petersont@google.comd01b8732008-10-16 02:18:071476 xmlNodePtr top_node = xmlDocGetRootElement(doc), chrome_config_node = NULL;
1477 // Here, we find the chrome_config node by name.
petersont@google.com252873ef2008-08-04 21:59:451478 for (xmlNodePtr p = top_node->children; p; p = p->next) {
petersont@google.comd01b8732008-10-16 02:18:071479 if (xmlStrEqual(p->name, BAD_CAST "chrome_config")) {
1480 chrome_config_node = p;
petersont@google.com252873ef2008-08-04 21:59:451481 break;
1482 }
1483 }
1484 // If the server data is formatted wrong and there is no
1485 // config node where we expect, we just drop out.
petersont@google.comd01b8732008-10-16 02:18:071486 if (chrome_config_node != NULL)
1487 GetSettingsFromChromeConfigNode(chrome_config_node);
petersont@google.com252873ef2008-08-04 21:59:451488 xmlFreeDoc(doc);
1489}
1490
petersont@google.comd01b8732008-10-16 02:18:071491void MetricsService::GetSettingsFromChromeConfigNode(
1492 xmlNodePtr chrome_config_node) {
1493 // Iterate through all children of the config node.
1494 for (xmlNodePtr current_node = chrome_config_node->children;
1495 current_node;
1496 current_node = current_node->next) {
1497 // If we find the upload tag, we appeal to another function
1498 // GetSettingsFromUploadNode to read all the data in it.
petersont@google.com252873ef2008-08-04 21:59:451499 if (xmlStrEqual(current_node->name, BAD_CAST "upload")) {
petersont@google.comd01b8732008-10-16 02:18:071500 GetSettingsFromUploadNode(current_node);
petersont@google.com252873ef2008-08-04 21:59:451501 continue;
1502 }
1503 }
1504}
initial.commit09911bf2008-07-26 23:55:291505
petersont@google.comd01b8732008-10-16 02:18:071506void MetricsService::InheritedProperties::OverwriteWhereNeeded(
1507 xmlNodePtr node) {
1508 xmlChar* salt_value = xmlGetProp(node, BAD_CAST "salt");
1509 if (salt_value) // If the property isn't there, xmlGetProp returns NULL.
1510 salt = atoi(reinterpret_cast<char*>(salt_value));
1511 // If the property isn't there, we keep the value the property had before
1512
1513 xmlChar* denominator_value = xmlGetProp(node, BAD_CAST "denominator");
1514 if (denominator_value)
1515 denominator = atoi(reinterpret_cast<char*>(denominator_value));
1516}
1517
1518void MetricsService::GetSettingsFromUploadNode(xmlNodePtr upload_node) {
1519 InheritedProperties props;
1520 GetSettingsFromUploadNodeRecursive(upload_node, props, "", true);
1521}
1522
pkasting@chromium.orgcac78842008-11-27 01:02:201523void MetricsService::GetSettingsFromUploadNodeRecursive(
1524 xmlNodePtr node,
1525 InheritedProperties props,
1526 std::string path_prefix,
1527 bool uploadOn) {
petersont@google.comd01b8732008-10-16 02:18:071528 props.OverwriteWhereNeeded(node);
1529
1530 // The bool uploadOn is set to true if the data represented by current
1531 // node should be uploaded. This gets inherited in the tree; the children
1532 // of a node that has already been rejected for upload get rejected for
1533 // upload.
1534 uploadOn = uploadOn && NodeProbabilityTest(node, props);
1535
1536 // The path is a / separated list of the node names ancestral to the current
1537 // one. So, if you want to check if the current node has a certain name,
1538 // compare to name. If you want to check if it is a certan tag at a certain
1539 // place in the tree, compare to the whole path.
1540 std::string name = std::string(reinterpret_cast<const char*>(node->name));
1541 std::string path = path_prefix + "/" + name;
1542
1543 if (path == "/upload") {
1544 xmlChar* upload_interval_val = xmlGetProp(node, BAD_CAST "interval");
1545 if (upload_interval_val) {
1546 interlog_duration_ = TimeDelta::FromSeconds(
1547 atoi(reinterpret_cast<char*>(upload_interval_val)));
1548 }
1549
1550 server_permits_upload_ = uploadOn;
ziadh@chromium.org24d07e32010-07-10 00:31:271551 } else if (path == "/upload/logs") {
petersont@google.comd01b8732008-10-16 02:18:071552 xmlChar* log_event_limit_val = xmlGetProp(node, BAD_CAST "event_limit");
1553 if (log_event_limit_val)
1554 log_event_limit_ = atoi(reinterpret_cast<char*>(log_event_limit_val));
1555 }
petersont@google.comd01b8732008-10-16 02:18:071556
1557 // Recursive call. If the node is a leaf i.e. if it ends in a "/>", then it
1558 // doesn't have children, so node->children is NULL, and this loop doesn't
1559 // call (that's how the recursion ends).
1560 for (xmlNodePtr child_node = node->children;
pkasting@chromium.orgcac78842008-11-27 01:02:201561 child_node;
1562 child_node = child_node->next) {
petersont@google.comd01b8732008-10-16 02:18:071563 GetSettingsFromUploadNodeRecursive(child_node, props, path, uploadOn);
1564 }
1565}
1566
1567bool MetricsService::NodeProbabilityTest(xmlNodePtr node,
pkasting@chromium.orgcac78842008-11-27 01:02:201568 InheritedProperties props) const {
petersont@google.comd01b8732008-10-16 02:18:071569 // Default value of probability on any node is 1, but recall that
1570 // its parents can already have been rejected for upload.
1571 double probability = 1;
1572
1573 // If a probability is specified in the node, we use it instead.
1574 xmlChar* probability_value = xmlGetProp(node, BAD_CAST "probability");
1575 if (probability_value)
jar@google.com0b33f80b2008-12-17 21:34:361576 probability = atoi(reinterpret_cast<char*>(probability_value));
petersont@google.comd01b8732008-10-16 02:18:071577
1578 return ProbabilityTest(probability, props.salt, props.denominator);
1579}
1580
1581bool MetricsService::ProbabilityTest(double probability,
1582 int salt,
1583 int denominator) const {
1584 // Okay, first we figure out how many of the digits of the
1585 // client_id_ we need in order to make a nice pseudorandomish
1586 // number in the range [0,denominator). Too many digits is
1587 // fine.
petersont@google.comd01b8732008-10-16 02:18:071588
1589 // n is the length of the client_id_ string
1590 size_t n = client_id_.size();
1591
1592 // idnumber is a positive integer generated from the client_id_.
1593 // It plus salt is going to give us our pseudorandom number.
1594 int idnumber = 0;
1595 const char* client_id_c_str = client_id_.c_str();
1596
1597 // Here we hash the relevant digits of the client_id_
1598 // string somehow to get a big integer idnumber (could be negative
1599 // from wraparound)
1600 int big = 1;
robertshield@google.com5ed73342009-03-18 17:39:431601 int last_pos = n - 1;
1602 for (size_t j = 0; j < n; ++j) {
1603 idnumber += static_cast<int>(client_id_c_str[last_pos - j]) * big;
petersont@google.comd01b8732008-10-16 02:18:071604 big *= 10;
1605 }
1606
1607 // Mod id number by denominator making sure to get a non-negative
1608 // answer.
pkasting@chromium.orgcac78842008-11-27 01:02:201609 idnumber = ((idnumber % denominator) + denominator) % denominator;
petersont@google.comd01b8732008-10-16 02:18:071610
pkasting@chromium.orgcac78842008-11-27 01:02:201611 // ((idnumber + salt) % denominator) / denominator is in the range [0,1]
petersont@google.comd01b8732008-10-16 02:18:071612 // if it's less than probability we call that an affirmative coin
1613 // toss.
pkasting@chromium.orgcac78842008-11-27 01:02:201614 return static_cast<double>((idnumber + salt) % denominator) <
1615 probability * denominator;
petersont@google.comd01b8732008-10-16 02:18:071616}
1617
initial.commit09911bf2008-07-26 23:55:291618void MetricsService::LogWindowChange(NotificationType type,
1619 const NotificationSource& source,
1620 const NotificationDetails& details) {
brettw@google.com534e54b2008-08-13 15:40:091621 int controller_id = -1;
1622 uintptr_t window_or_tab = source.map_key();
initial.commit09911bf2008-07-26 23:55:291623 MetricsLog::WindowEventType window_type;
1624
1625 // Note: since we stop all logging when a single OTR session is active, it is
1626 // possible that we start getting notifications about a window that we don't
1627 // know about.
brettw@google.com534e54b2008-08-13 15:40:091628 if (window_map_.find(window_or_tab) == window_map_.end()) {
1629 controller_id = next_window_id_++;
1630 window_map_[window_or_tab] = controller_id;
initial.commit09911bf2008-07-26 23:55:291631 } else {
brettw@google.com534e54b2008-08-13 15:40:091632 controller_id = window_map_[window_or_tab];
initial.commit09911bf2008-07-26 23:55:291633 }
jar@chromium.org92745242009-06-12 16:52:211634 DCHECK_NE(controller_id, -1);
initial.commit09911bf2008-07-26 23:55:291635
brettw@chromium.orgbfd04a62009-02-01 18:16:561636 switch (type.value) {
1637 case NotificationType::TAB_PARENTED:
1638 case NotificationType::BROWSER_OPENED:
initial.commit09911bf2008-07-26 23:55:291639 window_type = MetricsLog::WINDOW_CREATE;
1640 break;
1641
brettw@chromium.orgbfd04a62009-02-01 18:16:561642 case NotificationType::TAB_CLOSING:
1643 case NotificationType::BROWSER_CLOSED:
brettw@google.com534e54b2008-08-13 15:40:091644 window_map_.erase(window_map_.find(window_or_tab));
initial.commit09911bf2008-07-26 23:55:291645 window_type = MetricsLog::WINDOW_DESTROY;
1646 break;
1647
1648 default:
jar@chromium.orgb42c5e42010-06-03 20:43:251649 LOG(DFATAL);
paul@chromium.org68d74f02009-02-13 01:36:501650 return;
initial.commit09911bf2008-07-26 23:55:291651 }
1652
brettw@google.com534e54b2008-08-13 15:40:091653 // TODO(brettw) we should have some kind of ID for the parent.
1654 current_log_->RecordWindowEvent(window_type, controller_id, 0);
initial.commit09911bf2008-07-26 23:55:291655}
1656
1657void MetricsService::LogLoadComplete(NotificationType type,
1658 const NotificationSource& source,
1659 const NotificationDetails& details) {
1660 if (details == NotificationService::NoDetails())
1661 return;
1662
jar@google.com68475e602008-08-22 03:21:151663 // TODO(jar): There is a bug causing this to be called too many times, and
1664 // the log overflows. For now, we won't record these events.
dsh@google.com553dba62009-02-24 19:08:231665 UMA_HISTOGRAM_COUNTS("UMA.LogLoadComplete called", 1);
jar@google.com68475e602008-08-22 03:21:151666 return;
1667
initial.commit09911bf2008-07-26 23:55:291668 const Details<LoadNotificationDetails> load_details(details);
brettw@google.com534e54b2008-08-13 15:40:091669 int controller_id = window_map_[details.map_key()];
1670 current_log_->RecordLoadEvent(controller_id,
initial.commit09911bf2008-07-26 23:55:291671 load_details->url(),
1672 load_details->origin(),
1673 load_details->session_index(),
1674 load_details->load_time());
1675}
1676
cpu@google.come73c01972008-08-13 00:18:241677void MetricsService::IncrementPrefValue(const wchar_t* path) {
1678 PrefService* pref = g_browser_process->local_state();
1679 DCHECK(pref);
1680 int value = pref->GetInteger(path);
1681 pref->SetInteger(path, value + 1);
1682}
1683
robertshield@google.com0bb1a622009-03-04 03:22:321684void MetricsService::IncrementLongPrefsValue(const wchar_t* path) {
1685 PrefService* pref = g_browser_process->local_state();
1686 DCHECK(pref);
1687 int64 value = pref->GetInt64(path);
jar@chromium.orgb42c5e42010-06-03 20:43:251688 pref->SetInt64(path, value + 1);
robertshield@google.com0bb1a622009-03-04 03:22:321689}
1690
initial.commit09911bf2008-07-26 23:55:291691void MetricsService::LogLoadStarted() {
cpu@google.come73c01972008-08-13 00:18:241692 IncrementPrefValue(prefs::kStabilityPageLoadCount);
robertshield@google.com0bb1a622009-03-04 03:22:321693 IncrementLongPrefsValue(prefs::kUninstallMetricsPageLoadCount);
jar@google.com0b33f80b2008-12-17 21:34:361694 // We need to save the prefs, as page load count is a critical stat, and it
1695 // might be lost due to a crash :-(.
initial.commit09911bf2008-07-26 23:55:291696}
1697
initial.commit09911bf2008-07-26 23:55:291698void MetricsService::LogRendererCrash() {
cpu@google.come73c01972008-08-13 00:18:241699 IncrementPrefValue(prefs::kStabilityRendererCrashCount);
initial.commit09911bf2008-07-26 23:55:291700}
1701
asargent@chromium.org1f085622009-12-04 05:33:451702void MetricsService::LogExtensionRendererCrash() {
1703 IncrementPrefValue(prefs::kStabilityExtensionRendererCrashCount);
1704}
1705
initial.commit09911bf2008-07-26 23:55:291706void MetricsService::LogRendererHang() {
cpu@google.come73c01972008-08-13 00:18:241707 IncrementPrefValue(prefs::kStabilityRendererHangCount);
initial.commit09911bf2008-07-26 23:55:291708}
1709
jam@chromium.orga27a9382009-02-11 23:55:101710void MetricsService::LogChildProcessChange(
1711 NotificationType type,
1712 const NotificationSource& source,
1713 const NotificationDetails& details) {
gregoryd@google.com0d84c5d2009-10-09 01:10:421714 Details<ChildProcessInfo> child_details(details);
1715 const std::wstring& child_name = child_details->name();
1716
jam@chromium.orga27a9382009-02-11 23:55:101717 if (child_process_stats_buffer_.find(child_name) ==
1718 child_process_stats_buffer_.end()) {
gregoryd@google.com0d84c5d2009-10-09 01:10:421719 child_process_stats_buffer_[child_name] =
1720 ChildProcessStats(child_details->type());
initial.commit09911bf2008-07-26 23:55:291721 }
1722
jam@chromium.orga27a9382009-02-11 23:55:101723 ChildProcessStats& stats = child_process_stats_buffer_[child_name];
brettw@chromium.orgbfd04a62009-02-01 18:16:561724 switch (type.value) {
jam@chromium.orga27a9382009-02-11 23:55:101725 case NotificationType::CHILD_PROCESS_HOST_CONNECTED:
initial.commit09911bf2008-07-26 23:55:291726 stats.process_launches++;
1727 break;
1728
jam@chromium.orga27a9382009-02-11 23:55:101729 case NotificationType::CHILD_INSTANCE_CREATED:
initial.commit09911bf2008-07-26 23:55:291730 stats.instances++;
1731 break;
1732
jam@chromium.orga27a9382009-02-11 23:55:101733 case NotificationType::CHILD_PROCESS_CRASHED:
initial.commit09911bf2008-07-26 23:55:291734 stats.process_crashes++;
asargent@chromium.org1f085622009-12-04 05:33:451735 // Exclude plugin crashes from the count below because we report them via
1736 // a separate UMA metric.
1737 if (child_details->type() != ChildProcessInfo::PLUGIN_PROCESS) {
1738 IncrementPrefValue(prefs::kStabilityChildProcessCrashCount);
1739 }
initial.commit09911bf2008-07-26 23:55:291740 break;
1741
1742 default:
jar@chromium.orgb42c5e42010-06-03 20:43:251743 LOG(DFATAL) << "Unexpected notification type " << type.value;
initial.commit09911bf2008-07-26 23:55:291744 return;
1745 }
1746}
1747
1748// Recursively counts the number of bookmarks and folders in node.
munjal@chromium.orgb3c33d462009-06-26 22:29:201749static void CountBookmarks(const BookmarkNode* node,
1750 int* bookmarks,
1751 int* folders) {
sky@chromium.org037db002009-10-19 20:06:081752 if (node->type() == BookmarkNode::URL)
initial.commit09911bf2008-07-26 23:55:291753 (*bookmarks)++;
1754 else
1755 (*folders)++;
1756 for (int i = 0; i < node->GetChildCount(); ++i)
1757 CountBookmarks(node->GetChild(i), bookmarks, folders);
1758}
1759
munjal@chromium.orgb3c33d462009-06-26 22:29:201760void MetricsService::LogBookmarks(const BookmarkNode* node,
initial.commit09911bf2008-07-26 23:55:291761 const wchar_t* num_bookmarks_key,
1762 const wchar_t* num_folders_key) {
1763 DCHECK(node);
1764 int num_bookmarks = 0;
1765 int num_folders = 0;
1766 CountBookmarks(node, &num_bookmarks, &num_folders);
1767 num_folders--; // Don't include the root folder in the count.
1768
1769 PrefService* pref = g_browser_process->local_state();
1770 DCHECK(pref);
1771 pref->SetInteger(num_bookmarks_key, num_bookmarks);
1772 pref->SetInteger(num_folders_key, num_folders);
1773}
1774
sky@google.comd8e41ed2008-09-11 15:22:321775void MetricsService::LogBookmarks(BookmarkModel* model) {
initial.commit09911bf2008-07-26 23:55:291776 DCHECK(model);
1777 LogBookmarks(model->GetBookmarkBarNode(),
1778 prefs::kNumBookmarksOnBookmarkBar,
1779 prefs::kNumFoldersOnBookmarkBar);
1780 LogBookmarks(model->other_node(),
1781 prefs::kNumBookmarksInOtherBookmarkFolder,
1782 prefs::kNumFoldersInOtherBookmarkFolder);
1783 ScheduleNextStateSave();
1784}
1785
1786void MetricsService::LogKeywords(const TemplateURLModel* url_model) {
1787 DCHECK(url_model);
1788
1789 PrefService* pref = g_browser_process->local_state();
1790 DCHECK(pref);
1791 pref->SetInteger(prefs::kNumKeywords,
1792 static_cast<int>(url_model->GetTemplateURLs().size()));
1793 ScheduleNextStateSave();
1794}
1795
1796void MetricsService::RecordPluginChanges(PrefService* pref) {
1797 ListValue* plugins = pref->GetMutableList(prefs::kStabilityPluginStats);
1798 DCHECK(plugins);
1799
1800 for (ListValue::iterator value_iter = plugins->begin();
1801 value_iter != plugins->end(); ++value_iter) {
1802 if (!(*value_iter)->IsType(Value::TYPE_DICTIONARY)) {
jar@chromium.orgb42c5e42010-06-03 20:43:251803 LOG(DFATAL);
initial.commit09911bf2008-07-26 23:55:291804 continue;
1805 }
1806
1807 DictionaryValue* plugin_dict = static_cast<DictionaryValue*>(*value_iter);
nsylvain@chromium.org8e50b602009-03-03 22:59:431808 std::wstring plugin_name;
1809 plugin_dict->GetString(prefs::kStabilityPluginName, &plugin_name);
nsylvain@chromium.org6470ee8f2009-03-03 20:46:401810 if (plugin_name.empty()) {
jar@chromium.orgb42c5e42010-06-03 20:43:251811 LOG(DFATAL);
initial.commit09911bf2008-07-26 23:55:291812 continue;
1813 }
1814
nsylvain@chromium.org8e50b602009-03-03 22:59:431815 if (child_process_stats_buffer_.find(plugin_name) ==
jam@chromium.orga27a9382009-02-11 23:55:101816 child_process_stats_buffer_.end())
initial.commit09911bf2008-07-26 23:55:291817 continue;
1818
nsylvain@chromium.org8e50b602009-03-03 22:59:431819 ChildProcessStats stats = child_process_stats_buffer_[plugin_name];
initial.commit09911bf2008-07-26 23:55:291820 if (stats.process_launches) {
1821 int launches = 0;
nsylvain@chromium.org8e50b602009-03-03 22:59:431822 plugin_dict->GetInteger(prefs::kStabilityPluginLaunches, &launches);
initial.commit09911bf2008-07-26 23:55:291823 launches += stats.process_launches;
nsylvain@chromium.org8e50b602009-03-03 22:59:431824 plugin_dict->SetInteger(prefs::kStabilityPluginLaunches, launches);
initial.commit09911bf2008-07-26 23:55:291825 }
1826 if (stats.process_crashes) {
1827 int crashes = 0;
nsylvain@chromium.org8e50b602009-03-03 22:59:431828 plugin_dict->GetInteger(prefs::kStabilityPluginCrashes, &crashes);
initial.commit09911bf2008-07-26 23:55:291829 crashes += stats.process_crashes;
nsylvain@chromium.org8e50b602009-03-03 22:59:431830 plugin_dict->SetInteger(prefs::kStabilityPluginCrashes, crashes);
initial.commit09911bf2008-07-26 23:55:291831 }
1832 if (stats.instances) {
1833 int instances = 0;
nsylvain@chromium.org8e50b602009-03-03 22:59:431834 plugin_dict->GetInteger(prefs::kStabilityPluginInstances, &instances);
initial.commit09911bf2008-07-26 23:55:291835 instances += stats.instances;
nsylvain@chromium.org8e50b602009-03-03 22:59:431836 plugin_dict->SetInteger(prefs::kStabilityPluginInstances, instances);
initial.commit09911bf2008-07-26 23:55:291837 }
1838
nsylvain@chromium.org8e50b602009-03-03 22:59:431839 child_process_stats_buffer_.erase(plugin_name);
initial.commit09911bf2008-07-26 23:55:291840 }
1841
1842 // Now go through and add dictionaries for plugins that didn't already have
1843 // reports in Local State.
jam@chromium.orga27a9382009-02-11 23:55:101844 for (std::map<std::wstring, ChildProcessStats>::iterator cache_iter =
1845 child_process_stats_buffer_.begin();
1846 cache_iter != child_process_stats_buffer_.end(); ++cache_iter) {
jam@chromium.orga27a9382009-02-11 23:55:101847 ChildProcessStats stats = cache_iter->second;
gregoryd@google.com0d84c5d2009-10-09 01:10:421848
1849 // Insert only plugins information into the plugins list.
1850 if (ChildProcessInfo::PLUGIN_PROCESS != stats.process_type)
1851 continue;
1852
1853 std::wstring plugin_name = cache_iter->first;
1854
initial.commit09911bf2008-07-26 23:55:291855 DictionaryValue* plugin_dict = new DictionaryValue;
1856
nsylvain@chromium.org8e50b602009-03-03 22:59:431857 plugin_dict->SetString(prefs::kStabilityPluginName, plugin_name);
1858 plugin_dict->SetInteger(prefs::kStabilityPluginLaunches,
initial.commit09911bf2008-07-26 23:55:291859 stats.process_launches);
nsylvain@chromium.org8e50b602009-03-03 22:59:431860 plugin_dict->SetInteger(prefs::kStabilityPluginCrashes,
initial.commit09911bf2008-07-26 23:55:291861 stats.process_crashes);
nsylvain@chromium.org8e50b602009-03-03 22:59:431862 plugin_dict->SetInteger(prefs::kStabilityPluginInstances,
initial.commit09911bf2008-07-26 23:55:291863 stats.instances);
1864 plugins->Append(plugin_dict);
1865 }
jam@chromium.orga27a9382009-02-11 23:55:101866 child_process_stats_buffer_.clear();
initial.commit09911bf2008-07-26 23:55:291867}
1868
1869bool MetricsService::CanLogNotification(NotificationType type,
1870 const NotificationSource& source,
1871 const NotificationDetails& details) {
1872 // We simply don't log anything to UMA if there is a single off the record
1873 // session visible. The problem is that we always notify using the orginal
1874 // profile in order to simplify notification processing.
1875 return !BrowserList::IsOffTheRecordSessionActive();
1876}
1877
1878void MetricsService::RecordBooleanPrefValue(const wchar_t* path, bool value) {
1879 DCHECK(IsSingleThreaded());
1880
1881 PrefService* pref = g_browser_process->local_state();
1882 DCHECK(pref);
1883
1884 pref->SetBoolean(path, value);
1885 RecordCurrentState(pref);
1886}
1887
1888void MetricsService::RecordCurrentState(PrefService* pref) {
robertshield@google.com0bb1a622009-03-04 03:22:321889 pref->SetInt64(prefs::kStabilityLastTimestampSec, Time::Now().ToTimeT());
initial.commit09911bf2008-07-26 23:55:291890
1891 RecordPluginChanges(pref);
1892}
1893
initial.commit09911bf2008-07-26 23:55:291894static bool IsSingleThreaded() {
paul@chromium.orgdc6f4962009-02-13 01:25:501895 static PlatformThreadId thread_id = 0;
initial.commit09911bf2008-07-26 23:55:291896 if (!thread_id)
paul@chromium.orgdc6f4962009-02-13 01:25:501897 thread_id = PlatformThread::CurrentId();
1898 return PlatformThread::CurrentId() == thread_id;
initial.commit09911bf2008-07-26 23:55:291899}
rvargas@google.com5ccaa412009-11-13 22:00:161900
1901#if defined(OS_CHROMEOS)
zelidrag@chromium.org85ed9d42010-06-08 22:37:441902// static
1903std::string MetricsService::GetHardwareClass() {
1904 DCHECK(!ChromeThread::CurrentlyOn(ChromeThread::UI));
1905 std::string hardware_class;
1906 FilePath tool(kHardwareClassTool);
1907 CommandLine command(tool);
1908 if (base::GetAppOutput(command, &hardware_class)) {
1909 TrimWhitespaceASCII(hardware_class, TRIM_ALL, &hardware_class);
1910 } else {
1911 hardware_class = kUnknownHardwareClass;
1912 }
1913 return hardware_class;
1914}
1915
sky@chromium.org29cf16772010-04-21 15:13:471916void MetricsService::StartExternalMetrics() {
rvargas@google.com5ccaa412009-11-13 22:00:161917 external_metrics_ = new chromeos::ExternalMetrics;
sky@chromium.org29cf16772010-04-21 15:13:471918 external_metrics_->Start();
rvargas@google.com5ccaa412009-11-13 22:00:161919}
1920#endif