blob: 44a41b8ad6c15e0f8c3d3a0c5117a710863f1c0c [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"
erg@google.com5d91c9e2010-07-28 17:25:28167#include "base/command_line.h"
erg@google.com679082052010-07-21 21:30:13168#include "base/histogram.h"
ziadh@chromium.org46f89e142010-07-19 08:00:42169#include "base/md5.h"
pkasting@chromium.org4d022ff2009-10-23 18:47:09170#include "base/thread.h"
erg@google.com679082052010-07-21 21:30:13171#include "base/values.h"
sky@google.comd8e41ed2008-09-11 15:22:32172#include "chrome/browser/bookmarks/bookmark_model.h"
initial.commit09911bf2008-07-26 23:55:29173#include "chrome/browser/browser_list.h"
174#include "chrome/browser/browser_process.h"
175#include "chrome/browser/load_notification_details.h"
176#include "chrome/browser/memory_details.h"
phajdan.jr@chromium.org7c927b62010-02-24 09:54:13177#include "chrome/browser/metrics/histogram_synchronizer.h"
erg@google.com679082052010-07-21 21:30:13178#include "chrome/browser/metrics/metrics_log.h"
phajdan.jr@chromium.org052313b2010-02-19 09:43:08179#include "chrome/browser/pref_service.h"
initial.commit09911bf2008-07-26 23:55:29180#include "chrome/browser/profile.h"
brettw@chromium.org8c8657d62009-01-16 18:31:26181#include "chrome/browser/renderer_host/render_process_host.h"
ben@chromium.orgd54e03a52009-01-16 00:31:04182#include "chrome/browser/search_engines/template_url_model.h"
erg@google.com679082052010-07-21 21:30:13183#include "chrome/common/child_process_info.h"
kuchhal@chromium.org157d5472009-11-05 22:31:03184#include "chrome/common/child_process_logging.h"
jar@chromium.org92745242009-06-12 16:52:21185#include "chrome/common/chrome_switches.h"
brettw@chromium.orgbfd04a62009-02-01 18:16:56186#include "chrome/common/notification_service.h"
initial.commit09911bf2008-07-26 23:55:29187#include "chrome/common/pref_names.h"
jam@chromium.orge09ba552009-02-05 03:26:29188#include "chrome/common/render_messages.h"
jam@chromium.org35fa6a22009-08-15 00:04:01189#include "webkit/glue/plugins/plugin_list.h"
erg@google.com679082052010-07-21 21:30:13190#include "webkit/glue/plugins/webplugininfo.h"
mad@google.comae393ec702010-06-27 16:23:14191#include "libxml/xmlwriter.h"
initial.commit09911bf2008-07-26 23:55:29192
pkasting@chromium.org4d022ff2009-10-23 18:47:09193#if !defined(OS_WIN)
194#include "base/rand_util.h"
195#endif
196
phajdan.jr@chromium.orge06131d2010-02-10 18:40:33197// TODO(port): port browser_distribution.h.
198#if !defined(OS_POSIX)
kuchhal@chromium.org79bf0b72009-04-27 21:30:55199#include "chrome/installer/util/browser_distribution.h"
paul@chromium.orgdc6f4962009-02-13 01:25:50200#endif
201
rvargas@google.com5ccaa412009-11-13 22:00:16202#if defined(OS_CHROMEOS)
203#include "chrome/browser/chromeos/external_metrics.h"
zelidrag@chromium.org85ed9d42010-06-08 22:37:44204
205static const char kHardwareClassTool[] = "/usr/bin/hardware_class";
206static const char kUnknownHardwareClass[] = "unknown";
rvargas@google.com5ccaa412009-11-13 22:00:16207#endif
208
ziadh@chromium.org46f89e142010-07-19 08:00:42209namespace {
210MetricsService::LogRecallStatus MakeRecallStatusHistogram(
211 MetricsService::LogRecallStatus status) {
212 UMA_HISTOGRAM_ENUMERATION("PrefService.PersistentLogRecall", status,
213 MetricsService::END_RECALL_STATUS);
214 return status;
215}
216
217// TODO(ziadh): Remove this when done with experiment.
218void MakeStoreStatusHistogram(MetricsService::LogStoreStatus status) {
ziadh@chromium.org4e95d202010-07-24 01:47:56219 UMA_HISTOGRAM_ENUMERATION("PrefService.PersistentLogStore2", status,
ziadh@chromium.org46f89e142010-07-19 08:00:42220 MetricsService::END_STORE_STATUS);
221}
222} // namespace
223
dsh@google.come1acf6f2008-10-27 20:43:33224using base::Time;
225using base::TimeDelta;
226
initial.commit09911bf2008-07-26 23:55:29227// Check to see that we're being called on only one thread.
228static bool IsSingleThreaded();
229
initial.commit09911bf2008-07-26 23:55:29230static const char kMetricsType[] = "application/vnd.mozilla.metrics.bz2";
231
232// The delay, in seconds, after startup before sending the first log message.
petersont@google.com252873ef2008-08-04 21:59:45233static const int kInitialInterlogDuration = 60; // one minute
234
jar@chromium.orgc9a3ef82009-05-28 22:02:46235// This specifies the amount of time to wait for all renderers to send their
236// data.
237static const int kMaxHistogramGatheringWaitDuration = 60000; // 60 seconds.
238
petersont@google.com252873ef2008-08-04 21:59:45239// The default maximum number of events in a log uploaded to the UMA server.
jar@google.com0b33f80b2008-12-17 21:34:36240static const int kInitialEventLimit = 2400;
jar@google.com68475e602008-08-22 03:21:15241
242// If an upload fails, and the transmission was over this byte count, then we
243// will discard the log, and not try to retransmit it. We also don't persist
244// the log to the prefs for transmission during the next chrome session if this
245// limit is exceeded.
246static const int kUploadLogAvoidRetransmitSize = 50000;
initial.commit09911bf2008-07-26 23:55:29247
248// When we have logs from previous Chrome sessions to send, how long should we
249// delay (in seconds) between each log transmission.
250static const int kUnsentLogDelay = 15; // 15 seconds
251
252// Minimum time a log typically exists before sending, in seconds.
253// This number is supplied by the server, but until we parse it out of a server
254// response, we use this duration to specify how long we should wait before
255// sending the next log. If the channel is busy, such as when there is a
256// failure during an attempt to transmit a previous log, then a log may wait
jar@chromium.org2fe42fe2010-05-07 19:22:39257// (and continue to accrue new log entries) for a much greater period of time.
258static const int kMinSecondsPerLog = 30 * 60; // Thirty minutes.
initial.commit09911bf2008-07-26 23:55:29259
initial.commit09911bf2008-07-26 23:55:29260// When we don't succeed at transmitting a log to a server, we progressively
261// wait longer and longer before sending the next log. This backoff process
262// help reduce load on the server, and makes the amount of backoff vary between
263// clients so that a collision (server overload?) on retransmit is less likely.
264// The following is the constant we use to expand that inter-log duration.
265static const double kBackoff = 1.1;
266// We limit the maximum backoff to be no greater than some multiple of the
267// default kMinSecondsPerLog. The following is that maximum ratio.
268static const int kMaxBackoff = 10;
269
270// Interval, in seconds, between state saves.
271static const int kSaveStateInterval = 5 * 60; // five minutes
272
273// The number of "initial" logs we're willing to save, and hope to send during
274// a future Chrome session. Initial logs contain crash stats, and are pretty
275// small.
276static const size_t kMaxInitialLogsPersisted = 20;
277
278// The number of ongoing logs we're willing to save persistently, and hope to
jar@chromium.org281d2882009-01-20 20:32:42279// send during a this or future sessions. Note that each log may be pretty
initial.commit09911bf2008-07-26 23:55:29280// large, as presumably the related "initial" log wasn't sent (probably nothing
281// was, as the user was probably off-line). As a result, the log probably kept
282// accumulating while the "initial" log was stalled (pending_), and couldn't be
283// sent. As a result, we don't want to save too many of these mega-logs.
284// A "standard shutdown" will create a small log, including just the data that
285// was not yet been transmitted, and that is normal (to have exactly one
286// ongoing_log_ at startup).
jar@chromium.org281d2882009-01-20 20:32:42287static const size_t kMaxOngoingLogsPersisted = 8;
initial.commit09911bf2008-07-26 23:55:29288
ziadh@chromium.org46f89e142010-07-19 08:00:42289// We append (2) more elements to persisted lists: the size of the list and a
290// checksum of the elements.
291static const size_t kChecksumEntryCount = 2;
292
erg@google.com679082052010-07-21 21:30:13293// This is used to quickly log stats from child process related notifications in
294// MetricsService::child_stats_buffer_. The buffer's contents are transferred
295// out when Local State is periodically saved. The information is then
296// reported to the UMA server on next launch.
297struct MetricsService::ChildProcessStats {
298 public:
299 explicit ChildProcessStats(ChildProcessInfo::ProcessType type)
300 : process_launches(0),
301 process_crashes(0),
302 instances(0),
303 process_type(type) {}
304
305 // This constructor is only used by the map to return some default value for
306 // an index for which no value has been assigned.
307 ChildProcessStats()
308 : process_launches(0),
309 process_crashes(0),
310 instances(0),
311 process_type(ChildProcessInfo::UNKNOWN_PROCESS) {}
312
313 // The number of times that the given child process has been launched
314 int process_launches;
315
316 // The number of times that the given child process has crashed
317 int process_crashes;
318
319 // The number of instances of this child process that have been created.
320 // An instance is a DOM object rendered by this child process during a page
321 // load.
322 int instances;
323
324 ChildProcessInfo::ProcessType process_type;
325};
initial.commit09911bf2008-07-26 23:55:29326
327// Handles asynchronous fetching of memory details.
328// Will run the provided task after finished.
329class MetricsMemoryDetails : public MemoryDetails {
330 public:
331 explicit MetricsMemoryDetails(Task* completion) : completion_(completion) {}
332
333 virtual void OnDetailsAvailable() {
334 MessageLoop::current()->PostTask(FROM_HERE, completion_);
335 }
336
337 private:
jam@chromium.orge6e6ba42009-11-07 01:56:19338 ~MetricsMemoryDetails() {}
339
initial.commit09911bf2008-07-26 23:55:29340 Task* completion_;
tfarina@chromium.org4d818fee2010-06-06 13:32:27341 DISALLOW_COPY_AND_ASSIGN(MetricsMemoryDetails);
initial.commit09911bf2008-07-26 23:55:29342};
343
zelidrag@chromium.org85ed9d42010-06-08 22:37:44344class MetricsService::InitTaskComplete : public Task {
jam@chromium.org35fa6a22009-08-15 00:04:01345 public:
zelidrag@chromium.org85ed9d42010-06-08 22:37:44346 explicit InitTaskComplete(const std::string& hardware_class,
347 const std::vector<WebPluginInfo>& plugins)
348 : hardware_class_(hardware_class), plugins_(plugins) {}
349
jamesr@chromium.org7f2e792e2009-11-30 23:18:29350 virtual void Run() {
zelidrag@chromium.org85ed9d42010-06-08 22:37:44351 g_browser_process->metrics_service()->OnInitTaskComplete(
352 hardware_class_, plugins_);
initial.commit09911bf2008-07-26 23:55:29353 }
jam@chromium.org35fa6a22009-08-15 00:04:01354
jamesr@chromium.org7f2e792e2009-11-30 23:18:29355 private:
zelidrag@chromium.org85ed9d42010-06-08 22:37:44356 std::string hardware_class_;
jamesr@chromium.org7f2e792e2009-11-30 23:18:29357 std::vector<WebPluginInfo> plugins_;
initial.commit09911bf2008-07-26 23:55:29358};
359
zelidrag@chromium.org85ed9d42010-06-08 22:37:44360class MetricsService::InitTask : public Task {
jamesr@chromium.org7f2e792e2009-11-30 23:18:29361 public:
zelidrag@chromium.org85ed9d42010-06-08 22:37:44362 explicit InitTask(MessageLoop* callback_loop)
jamesr@chromium.org7f2e792e2009-11-30 23:18:29363 : callback_loop_(callback_loop) {}
364
365 virtual void Run() {
366 std::vector<WebPluginInfo> plugins;
367 NPAPI::PluginList::Singleton()->GetPlugins(false, &plugins);
zelidrag@chromium.org85ed9d42010-06-08 22:37:44368 std::string hardware_class; // Empty string by default.
369#if defined(OS_CHROMEOS)
370 hardware_class = MetricsService::GetHardwareClass();
371#endif // OS_CHROMEOS
372 callback_loop_->PostTask(FROM_HERE, new InitTaskComplete(
373 hardware_class, plugins));
jamesr@chromium.org7f2e792e2009-11-30 23:18:29374 }
375
376 private:
377 MessageLoop* callback_loop_;
378};
evan@chromium.org90d41372009-11-30 21:52:32379
initial.commit09911bf2008-07-26 23:55:29380// static
381void MetricsService::RegisterPrefs(PrefService* local_state) {
382 DCHECK(IsSingleThreaded());
estade@chromium.org20ce516d2010-06-18 02:20:04383 local_state->RegisterStringPref(prefs::kMetricsClientID, "");
robertshield@google.com0bb1a622009-03-04 03:22:32384 local_state->RegisterInt64Pref(prefs::kMetricsClientIDTimestamp, 0);
385 local_state->RegisterInt64Pref(prefs::kStabilityLaunchTimeSec, 0);
386 local_state->RegisterInt64Pref(prefs::kStabilityLastTimestampSec, 0);
estade@chromium.org20ce516d2010-06-18 02:20:04387 local_state->RegisterStringPref(prefs::kStabilityStatsVersion, "");
jar@chromium.org225c50842010-01-19 21:19:13388 local_state->RegisterInt64Pref(prefs::kStabilityStatsBuildTime, 0);
initial.commit09911bf2008-07-26 23:55:29389 local_state->RegisterBooleanPref(prefs::kStabilityExitedCleanly, true);
390 local_state->RegisterBooleanPref(prefs::kStabilitySessionEndCompleted, true);
391 local_state->RegisterIntegerPref(prefs::kMetricsSessionID, -1);
392 local_state->RegisterIntegerPref(prefs::kStabilityLaunchCount, 0);
393 local_state->RegisterIntegerPref(prefs::kStabilityCrashCount, 0);
394 local_state->RegisterIntegerPref(prefs::kStabilityIncompleteSessionEndCount,
395 0);
396 local_state->RegisterIntegerPref(prefs::kStabilityPageLoadCount, 0);
initial.commit09911bf2008-07-26 23:55:29397 local_state->RegisterIntegerPref(prefs::kStabilityRendererCrashCount, 0);
asargent@chromium.org1f085622009-12-04 05:33:45398 local_state->RegisterIntegerPref(prefs::kStabilityExtensionRendererCrashCount,
399 0);
initial.commit09911bf2008-07-26 23:55:29400 local_state->RegisterIntegerPref(prefs::kStabilityRendererHangCount, 0);
asargent@chromium.org1f085622009-12-04 05:33:45401 local_state->RegisterIntegerPref(prefs::kStabilityChildProcessCrashCount, 0);
cpu@google.come73c01972008-08-13 00:18:24402 local_state->RegisterIntegerPref(prefs::kStabilityBreakpadRegistrationFail,
403 0);
404 local_state->RegisterIntegerPref(prefs::kStabilityBreakpadRegistrationSuccess,
405 0);
406 local_state->RegisterIntegerPref(prefs::kStabilityDebuggerPresent, 0);
407 local_state->RegisterIntegerPref(prefs::kStabilityDebuggerNotPresent, 0);
408
initial.commit09911bf2008-07-26 23:55:29409 local_state->RegisterDictionaryPref(prefs::kProfileMetrics);
410 local_state->RegisterIntegerPref(prefs::kNumBookmarksOnBookmarkBar, 0);
411 local_state->RegisterIntegerPref(prefs::kNumFoldersOnBookmarkBar, 0);
412 local_state->RegisterIntegerPref(prefs::kNumBookmarksInOtherBookmarkFolder,
413 0);
414 local_state->RegisterIntegerPref(prefs::kNumFoldersInOtherBookmarkFolder, 0);
415 local_state->RegisterIntegerPref(prefs::kNumKeywords, 0);
416 local_state->RegisterListPref(prefs::kMetricsInitialLogs);
417 local_state->RegisterListPref(prefs::kMetricsOngoingLogs);
robertshield@google.com0bb1a622009-03-04 03:22:32418
419 local_state->RegisterInt64Pref(prefs::kUninstallMetricsPageLoadCount, 0);
420 local_state->RegisterInt64Pref(prefs::kUninstallLaunchCount, 0);
robertshield@google.com6b5f21d2009-04-13 17:01:35421 local_state->RegisterInt64Pref(prefs::kUninstallMetricsInstallDate, 0);
robertshield@google.com0bb1a622009-03-04 03:22:32422 local_state->RegisterInt64Pref(prefs::kUninstallMetricsUptimeSec, 0);
423 local_state->RegisterInt64Pref(prefs::kUninstallLastLaunchTimeSec, 0);
424 local_state->RegisterInt64Pref(prefs::kUninstallLastObservedRunTimeSec, 0);
initial.commit09911bf2008-07-26 23:55:29425}
426
jar@chromium.org541f77922009-02-23 21:14:38427// static
428void MetricsService::DiscardOldStabilityStats(PrefService* local_state) {
429 local_state->SetBoolean(prefs::kStabilityExitedCleanly, true);
jar@chromium.orgc9abf242009-07-18 06:00:38430 local_state->SetBoolean(prefs::kStabilitySessionEndCompleted, true);
jar@chromium.org541f77922009-02-23 21:14:38431
432 local_state->SetInteger(prefs::kStabilityIncompleteSessionEndCount, 0);
433 local_state->SetInteger(prefs::kStabilityBreakpadRegistrationSuccess, 0);
434 local_state->SetInteger(prefs::kStabilityBreakpadRegistrationFail, 0);
435 local_state->SetInteger(prefs::kStabilityDebuggerPresent, 0);
436 local_state->SetInteger(prefs::kStabilityDebuggerNotPresent, 0);
437
438 local_state->SetInteger(prefs::kStabilityLaunchCount, 0);
439 local_state->SetInteger(prefs::kStabilityCrashCount, 0);
440
441 local_state->SetInteger(prefs::kStabilityPageLoadCount, 0);
442 local_state->SetInteger(prefs::kStabilityRendererCrashCount, 0);
443 local_state->SetInteger(prefs::kStabilityRendererHangCount, 0);
444
jar@chromium.org9165f742010-03-10 22:55:01445 local_state->SetInt64(prefs::kStabilityLaunchTimeSec, 0);
446 local_state->SetInt64(prefs::kStabilityLastTimestampSec, 0);
jar@chromium.org541f77922009-02-23 21:14:38447
448 local_state->ClearPref(prefs::kStabilityPluginStats);
jar@chromium.orgae155cb92009-06-19 06:10:37449
450 ListValue* unsent_initial_logs = local_state->GetMutableList(
451 prefs::kMetricsInitialLogs);
452 unsent_initial_logs->Clear();
453
454 ListValue* unsent_ongoing_logs = local_state->GetMutableList(
455 prefs::kMetricsOngoingLogs);
456 unsent_ongoing_logs->Clear();
jar@chromium.org541f77922009-02-23 21:14:38457}
458
initial.commit09911bf2008-07-26 23:55:29459MetricsService::MetricsService()
petersont@google.comd01b8732008-10-16 02:18:07460 : recording_active_(false),
461 reporting_active_(false),
462 user_permits_upload_(false),
463 server_permits_upload_(true),
464 state_(INITIALIZED),
initial.commit09911bf2008-07-26 23:55:29465 current_fetch_(NULL),
petersont@google.comd01b8732008-10-16 02:18:07466 idle_since_last_transmission_(false),
initial.commit09911bf2008-07-26 23:55:29467 next_window_id_(0),
maruel@chromium.org40bcc302009-03-02 20:50:39468 ALLOW_THIS_IN_INITIALIZER_LIST(log_sender_factory_(this)),
469 ALLOW_THIS_IN_INITIALIZER_LIST(state_saver_factory_(this)),
petersont@google.com252873ef2008-08-04 21:59:45470 interlog_duration_(TimeDelta::FromSeconds(kInitialInterlogDuration)),
petersont@google.comd01b8732008-10-16 02:18:07471 log_event_limit_(kInitialEventLimit),
initial.commit09911bf2008-07-26 23:55:29472 timer_pending_(false) {
473 DCHECK(IsSingleThreaded());
474 InitializeMetricsState();
475}
476
477MetricsService::~MetricsService() {
478 SetRecording(false);
479}
480
petersont@google.comd01b8732008-10-16 02:18:07481void MetricsService::SetUserPermitsUpload(bool enabled) {
482 HandleIdleSinceLastTransmission(false);
483 user_permits_upload_ = enabled;
484}
485
486void MetricsService::Start() {
487 SetRecording(true);
488 SetReporting(true);
489}
490
491void MetricsService::StartRecordingOnly() {
492 SetRecording(true);
493 SetReporting(false);
494}
495
496void MetricsService::Stop() {
497 SetReporting(false);
498 SetRecording(false);
499}
500
initial.commit09911bf2008-07-26 23:55:29501void MetricsService::SetRecording(bool enabled) {
502 DCHECK(IsSingleThreaded());
503
petersont@google.comd01b8732008-10-16 02:18:07504 if (enabled == recording_active_)
initial.commit09911bf2008-07-26 23:55:29505 return;
506
507 if (enabled) {
jar@chromium.orgb0c819f2009-03-08 04:52:15508 if (client_id_.empty()) {
509 PrefService* pref = g_browser_process->local_state();
510 DCHECK(pref);
estade@chromium.orgddd231e2010-06-29 20:35:19511 client_id_ = pref->GetString(prefs::kMetricsClientID);
jar@chromium.orgb0c819f2009-03-08 04:52:15512 if (client_id_.empty()) {
513 client_id_ = GenerateClientID();
estade@chromium.orgddd231e2010-06-29 20:35:19514 pref->SetString(prefs::kMetricsClientID, client_id_);
jar@chromium.orgb0c819f2009-03-08 04:52:15515
516 // Might as well make a note of how long this ID has existed
517 pref->SetString(prefs::kMetricsClientIDTimestamp,
estade@chromium.orgddd231e2010-06-29 20:35:19518 Int64ToString(Time::Now().ToTimeT()));
jar@chromium.orgb0c819f2009-03-08 04:52:15519 }
520 }
kuchhal@chromium.org157d5472009-11-05 22:31:03521 child_process_logging::SetClientId(client_id_);
initial.commit09911bf2008-07-26 23:55:29522 StartRecording();
pkasting@chromium.org005ef3e2009-05-22 20:55:46523
524 registrar_.Add(this, NotificationType::BROWSER_OPENED,
525 NotificationService::AllSources());
526 registrar_.Add(this, NotificationType::BROWSER_CLOSED,
527 NotificationService::AllSources());
528 registrar_.Add(this, NotificationType::USER_ACTION,
529 NotificationService::AllSources());
530 registrar_.Add(this, NotificationType::TAB_PARENTED,
531 NotificationService::AllSources());
532 registrar_.Add(this, NotificationType::TAB_CLOSING,
533 NotificationService::AllSources());
534 registrar_.Add(this, NotificationType::LOAD_START,
535 NotificationService::AllSources());
536 registrar_.Add(this, NotificationType::LOAD_STOP,
537 NotificationService::AllSources());
kkania@chromium.orgcd69619b2010-05-05 02:41:38538 registrar_.Add(this, NotificationType::RENDERER_PROCESS_CLOSED,
pkasting@chromium.org005ef3e2009-05-22 20:55:46539 NotificationService::AllSources());
540 registrar_.Add(this, NotificationType::RENDERER_PROCESS_HANG,
541 NotificationService::AllSources());
542 registrar_.Add(this, NotificationType::CHILD_PROCESS_HOST_CONNECTED,
543 NotificationService::AllSources());
544 registrar_.Add(this, NotificationType::CHILD_INSTANCE_CREATED,
545 NotificationService::AllSources());
546 registrar_.Add(this, NotificationType::CHILD_PROCESS_CRASHED,
547 NotificationService::AllSources());
548 registrar_.Add(this, NotificationType::TEMPLATE_URL_MODEL_LOADED,
549 NotificationService::AllSources());
550 registrar_.Add(this, NotificationType::OMNIBOX_OPENED_URL,
551 NotificationService::AllSources());
552 registrar_.Add(this, NotificationType::BOOKMARK_MODEL_LOADED,
553 NotificationService::AllSources());
initial.commit09911bf2008-07-26 23:55:29554 } else {
pkasting@chromium.org005ef3e2009-05-22 20:55:46555 registrar_.RemoveAll();
initial.commit09911bf2008-07-26 23:55:29556 PushPendingLogsToUnsentLists();
557 DCHECK(!pending_log());
558 if (state_ > INITIAL_LOG_READY && unsent_logs())
559 state_ = SEND_OLD_INITIAL_LOGS;
560 }
petersont@google.comd01b8732008-10-16 02:18:07561 recording_active_ = enabled;
initial.commit09911bf2008-07-26 23:55:29562}
563
petersont@google.comd01b8732008-10-16 02:18:07564bool MetricsService::recording_active() const {
initial.commit09911bf2008-07-26 23:55:29565 DCHECK(IsSingleThreaded());
petersont@google.comd01b8732008-10-16 02:18:07566 return recording_active_;
initial.commit09911bf2008-07-26 23:55:29567}
568
petersont@google.comd01b8732008-10-16 02:18:07569void MetricsService::SetReporting(bool enable) {
570 if (reporting_active_ != enable) {
571 reporting_active_ = enable;
572 if (reporting_active_)
initial.commit09911bf2008-07-26 23:55:29573 StartLogTransmissionTimer();
574 }
petersont@google.comd01b8732008-10-16 02:18:07575}
576
577bool MetricsService::reporting_active() const {
578 DCHECK(IsSingleThreaded());
579 return reporting_active_;
initial.commit09911bf2008-07-26 23:55:29580}
581
582void MetricsService::Observe(NotificationType type,
583 const NotificationSource& source,
584 const NotificationDetails& details) {
585 DCHECK(current_log_);
586 DCHECK(IsSingleThreaded());
587
588 if (!CanLogNotification(type, source, details))
589 return;
590
brettw@chromium.orgbfd04a62009-02-01 18:16:56591 switch (type.value) {
592 case NotificationType::USER_ACTION:
evan@chromium.orgafe3a1672009-11-17 19:04:12593 current_log_->RecordUserAction(*Details<const char*>(details).ptr());
initial.commit09911bf2008-07-26 23:55:29594 break;
595
brettw@chromium.orgbfd04a62009-02-01 18:16:56596 case NotificationType::BROWSER_OPENED:
597 case NotificationType::BROWSER_CLOSED:
initial.commit09911bf2008-07-26 23:55:29598 LogWindowChange(type, source, details);
599 break;
600
brettw@chromium.orgbfd04a62009-02-01 18:16:56601 case NotificationType::TAB_PARENTED:
602 case NotificationType::TAB_CLOSING:
initial.commit09911bf2008-07-26 23:55:29603 LogWindowChange(type, source, details);
604 break;
605
brettw@chromium.orgbfd04a62009-02-01 18:16:56606 case NotificationType::LOAD_STOP:
initial.commit09911bf2008-07-26 23:55:29607 LogLoadComplete(type, source, details);
608 break;
609
brettw@chromium.orgbfd04a62009-02-01 18:16:56610 case NotificationType::LOAD_START:
initial.commit09911bf2008-07-26 23:55:29611 LogLoadStarted();
612 break;
613
kkania@chromium.orgcd69619b2010-05-05 02:41:38614 case NotificationType::RENDERER_PROCESS_CLOSED:
asargent@chromium.org1f085622009-12-04 05:33:45615 {
kkania@chromium.orgcd69619b2010-05-05 02:41:38616 RenderProcessHost::RendererClosedDetails* process_details =
617 Details<RenderProcessHost::RendererClosedDetails>(details).ptr();
618 if (process_details->did_crash) {
619 if (process_details->was_extension_renderer) {
620 LogExtensionRendererCrash();
621 } else {
622 LogRendererCrash();
623 }
624 }
asargent@chromium.org1f085622009-12-04 05:33:45625 }
initial.commit09911bf2008-07-26 23:55:29626 break;
627
brettw@chromium.orgbfd04a62009-02-01 18:16:56628 case NotificationType::RENDERER_PROCESS_HANG:
initial.commit09911bf2008-07-26 23:55:29629 LogRendererHang();
630 break;
631
jam@chromium.orga27a9382009-02-11 23:55:10632 case NotificationType::CHILD_PROCESS_HOST_CONNECTED:
633 case NotificationType::CHILD_PROCESS_CRASHED:
634 case NotificationType::CHILD_INSTANCE_CREATED:
635 LogChildProcessChange(type, source, details);
initial.commit09911bf2008-07-26 23:55:29636 break;
637
brettw@chromium.orgbfd04a62009-02-01 18:16:56638 case NotificationType::TEMPLATE_URL_MODEL_LOADED:
initial.commit09911bf2008-07-26 23:55:29639 LogKeywords(Source<TemplateURLModel>(source).ptr());
640 break;
641
ananta@chromium.org1226abb2010-06-10 18:01:28642 case NotificationType::OMNIBOX_OPENED_URL: {
643 MetricsLog* current_log = current_log_->AsMetricsLog();
644 DCHECK(current_log);
645 current_log->RecordOmniboxOpenedURL(
initial.commit09911bf2008-07-26 23:55:29646 *Details<AutocompleteLog>(details).ptr());
647 break;
ananta@chromium.org1226abb2010-06-10 18:01:28648 }
initial.commit09911bf2008-07-26 23:55:29649
tim@chromium.orgb61236c62009-04-09 22:43:55650 case NotificationType::BOOKMARK_MODEL_LOADED: {
651 Profile* p = Source<Profile>(source).ptr();
652 if (p)
653 LogBookmarks(p->GetBookmarkModel());
initial.commit09911bf2008-07-26 23:55:29654 break;
tim@chromium.orgb61236c62009-04-09 22:43:55655 }
initial.commit09911bf2008-07-26 23:55:29656 default:
jar@chromium.orga063c102010-07-22 22:20:19657 NOTREACHED();
initial.commit09911bf2008-07-26 23:55:29658 break;
659 }
petersont@google.comd01b8732008-10-16 02:18:07660
661 HandleIdleSinceLastTransmission(false);
662
663 if (current_log_)
jar@chromium.org281d2882009-01-20 20:32:42664 DLOG(INFO) << "METRICS: NUMBER OF EVENTS = " << current_log_->num_events();
petersont@google.comd01b8732008-10-16 02:18:07665}
666
667void MetricsService::HandleIdleSinceLastTransmission(bool in_idle) {
668 // If there wasn't a lot of action, maybe the computer was asleep, in which
669 // case, the log transmissions should have stopped. Here we start them up
670 // again.
pkasting@chromium.orgcac78842008-11-27 01:02:20671 if (!in_idle && idle_since_last_transmission_)
672 StartLogTransmissionTimer();
673 idle_since_last_transmission_ = in_idle;
initial.commit09911bf2008-07-26 23:55:29674}
675
676void MetricsService::RecordCleanShutdown() {
677 RecordBooleanPrefValue(prefs::kStabilityExitedCleanly, true);
678}
679
680void MetricsService::RecordStartOfSessionEnd() {
681 RecordBooleanPrefValue(prefs::kStabilitySessionEndCompleted, false);
682}
683
684void MetricsService::RecordCompletedSessionEnd() {
685 RecordBooleanPrefValue(prefs::kStabilitySessionEndCompleted, true);
686}
687
cpu@google.come73c01972008-08-13 00:18:24688void MetricsService:: RecordBreakpadRegistration(bool success) {
jar@google.com68475e602008-08-22 03:21:15689 if (!success)
cpu@google.come73c01972008-08-13 00:18:24690 IncrementPrefValue(prefs::kStabilityBreakpadRegistrationFail);
691 else
692 IncrementPrefValue(prefs::kStabilityBreakpadRegistrationSuccess);
693}
694
695void MetricsService::RecordBreakpadHasDebugger(bool has_debugger) {
696 if (!has_debugger)
697 IncrementPrefValue(prefs::kStabilityDebuggerNotPresent);
698 else
jar@google.com68475e602008-08-22 03:21:15699 IncrementPrefValue(prefs::kStabilityDebuggerPresent);
cpu@google.come73c01972008-08-13 00:18:24700}
701
initial.commit09911bf2008-07-26 23:55:29702//------------------------------------------------------------------------------
703// private methods
704//------------------------------------------------------------------------------
705
706
707//------------------------------------------------------------------------------
708// Initialization methods
709
710void MetricsService::InitializeMetricsState() {
kuchhal@chromium.org79bf0b72009-04-27 21:30:55711#if defined(OS_POSIX)
712 server_url_ = L"https://clients4.google.com/firefox/metrics/collect";
713#else
714 BrowserDistribution* dist = BrowserDistribution::GetDistribution();
715 server_url_ = dist->GetStatsServerURL();
716#endif
717
initial.commit09911bf2008-07-26 23:55:29718 PrefService* pref = g_browser_process->local_state();
719 DCHECK(pref);
720
jar@chromium.org225c50842010-01-19 21:19:13721 if ((pref->GetInt64(prefs::kStabilityStatsBuildTime)
722 != MetricsLog::GetBuildTime()) ||
estade@chromium.orgddd231e2010-06-29 20:35:19723 (pref->GetString(prefs::kStabilityStatsVersion)
jar@chromium.org225c50842010-01-19 21:19:13724 != MetricsLog::GetVersionString())) {
jar@chromium.org541f77922009-02-23 21:14:38725 // This is a new version, so we don't want to confuse the stats about the
726 // old version with info that we upload.
727 DiscardOldStabilityStats(pref);
728 pref->SetString(prefs::kStabilityStatsVersion,
estade@chromium.orgddd231e2010-06-29 20:35:19729 MetricsLog::GetVersionString());
jar@chromium.org225c50842010-01-19 21:19:13730 pref->SetInt64(prefs::kStabilityStatsBuildTime,
731 MetricsLog::GetBuildTime());
jar@chromium.org541f77922009-02-23 21:14:38732 }
733
initial.commit09911bf2008-07-26 23:55:29734 // Update session ID
735 session_id_ = pref->GetInteger(prefs::kMetricsSessionID);
736 ++session_id_;
737 pref->SetInteger(prefs::kMetricsSessionID, session_id_);
738
initial.commit09911bf2008-07-26 23:55:29739 // Stability bookkeeping
cpu@google.come73c01972008-08-13 00:18:24740 IncrementPrefValue(prefs::kStabilityLaunchCount);
initial.commit09911bf2008-07-26 23:55:29741
cpu@google.come73c01972008-08-13 00:18:24742 if (!pref->GetBoolean(prefs::kStabilityExitedCleanly)) {
743 IncrementPrefValue(prefs::kStabilityCrashCount);
initial.commit09911bf2008-07-26 23:55:29744 }
cpu@google.come73c01972008-08-13 00:18:24745
746 // This will be set to 'true' if we exit cleanly.
initial.commit09911bf2008-07-26 23:55:29747 pref->SetBoolean(prefs::kStabilityExitedCleanly, false);
748
cpu@google.come73c01972008-08-13 00:18:24749 if (!pref->GetBoolean(prefs::kStabilitySessionEndCompleted)) {
750 IncrementPrefValue(prefs::kStabilityIncompleteSessionEndCount);
jar@chromium.orgc9abf242009-07-18 06:00:38751 // This is marked false when we get a WM_ENDSESSION.
752 pref->SetBoolean(prefs::kStabilitySessionEndCompleted, true);
initial.commit09911bf2008-07-26 23:55:29753 }
initial.commit09911bf2008-07-26 23:55:29754
jar@chromium.org9165f742010-03-10 22:55:01755 // Initialize uptime counters.
756 int64 startup_uptime = MetricsLog::GetIncrementalUptime(pref);
mad@google.comae393ec702010-06-27 16:23:14757 DCHECK_EQ(0, startup_uptime);
jar@chromium.org9165f742010-03-10 22:55:01758 // For backwards compatibility, leave this intact in case Omaha is checking
759 // them. prefs::kStabilityLastTimestampSec may also be useless now.
760 // TODO(jar): Delete these if they have no uses.
robertshield@google.com0bb1a622009-03-04 03:22:32761 pref->SetInt64(prefs::kStabilityLaunchTimeSec, Time::Now().ToTimeT());
762
763 // Bookkeeping for the uninstall metrics.
764 IncrementLongPrefsValue(prefs::kUninstallLaunchCount);
initial.commit09911bf2008-07-26 23:55:29765
766 // Save profile metrics.
767 PrefService* prefs = g_browser_process->local_state();
768 if (prefs) {
769 // Remove the current dictionary and store it for use when sending data to
770 // server. By removing the value we prune potentially dead profiles
771 // (and keys). All valid values are added back once services startup.
772 const DictionaryValue* profile_dictionary =
773 prefs->GetDictionary(prefs::kProfileMetrics);
774 if (profile_dictionary) {
775 // Do a deep copy of profile_dictionary since ClearPref will delete it.
776 profile_dictionary_.reset(static_cast<DictionaryValue*>(
777 profile_dictionary->DeepCopy()));
778 prefs->ClearPref(prefs::kProfileMetrics);
779 }
780 }
781
jar@chromium.org92745242009-06-12 16:52:21782 // Get stats on use of command line.
783 const CommandLine* command_line(CommandLine::ForCurrentProcess());
784 size_t common_commands = 0;
785 if (command_line->HasSwitch(switches::kUserDataDir)) {
786 ++common_commands;
787 UMA_HISTOGRAM_COUNTS_100("Chrome.CommandLineDatDirCount", 1);
788 }
789
790 if (command_line->HasSwitch(switches::kApp)) {
791 ++common_commands;
792 UMA_HISTOGRAM_COUNTS_100("Chrome.CommandLineAppModeCount", 1);
793 }
794
795 UMA_HISTOGRAM_COUNTS_100("Chrome.CommandLineFlagCount",
796 command_line->GetSwitchCount());
797 UMA_HISTOGRAM_COUNTS_100("Chrome.CommandLineUncommonFlagCount",
798 command_line->GetSwitchCount() - common_commands);
799
initial.commit09911bf2008-07-26 23:55:29800 // Kick off the process of saving the state (so the uptime numbers keep
801 // getting updated) every n minutes.
802 ScheduleNextStateSave();
803}
804
zelidrag@chromium.org85ed9d42010-06-08 22:37:44805void MetricsService::OnInitTaskComplete(
806 const std::string& hardware_class,
jam@chromium.org35fa6a22009-08-15 00:04:01807 const std::vector<WebPluginInfo>& plugins) {
zelidrag@chromium.org85ed9d42010-06-08 22:37:44808 DCHECK(state_ == INIT_TASK_SCHEDULED);
809 hardware_class_ = hardware_class;
jam@chromium.org35fa6a22009-08-15 00:04:01810 plugins_ = plugins;
zelidrag@chromium.org85ed9d42010-06-08 22:37:44811 if (state_ == INIT_TASK_SCHEDULED)
812 state_ = INIT_TASK_DONE;
initial.commit09911bf2008-07-26 23:55:29813}
814
815std::string MetricsService::GenerateClientID() {
paul@chromium.orgdc6f4962009-02-13 01:25:50816#if defined(OS_WIN)
initial.commit09911bf2008-07-26 23:55:29817 const int kGUIDSize = 39;
818
819 GUID guid;
820 HRESULT guid_result = CoCreateGuid(&guid);
821 DCHECK(SUCCEEDED(guid_result));
822
823 std::wstring guid_string;
824 int result = StringFromGUID2(guid,
825 WriteInto(&guid_string, kGUIDSize), kGUIDSize);
826 DCHECK(result == kGUIDSize);
827
828 return WideToUTF8(guid_string.substr(1, guid_string.length() - 2));
evan@chromium.org271b24f2009-07-28 16:05:51829#else
sky@chromium.org06aaac22009-07-08 20:54:13830 uint64 sixteen_bytes[2] = { base::RandUint64(), base::RandUint64() };
831 return RandomBytesToGUIDString(sixteen_bytes);
paul@chromium.orgdc6f4962009-02-13 01:25:50832#endif
initial.commit09911bf2008-07-26 23:55:29833}
834
sky@chromium.org06aaac22009-07-08 20:54:13835#if defined(OS_POSIX)
836// TODO(cmasone): Once we're comfortable this works, migrate Windows code to
837// use this as well.
838std::string MetricsService::RandomBytesToGUIDString(const uint64 bytes[2]) {
evan@chromium.org34b2b002009-11-20 06:53:28839 return StringPrintf("%08X-%04X-%04X-%04X-%012llX",
840 static_cast<unsigned int>(bytes[0] >> 32),
841 static_cast<unsigned int>((bytes[0] >> 16) & 0x0000ffff),
842 static_cast<unsigned int>(bytes[0] & 0x0000ffff),
843 static_cast<unsigned int>(bytes[1] >> 48),
sky@chromium.org06aaac22009-07-08 20:54:13844 bytes[1] & 0x0000ffffffffffffULL);
845}
846#endif
initial.commit09911bf2008-07-26 23:55:29847
848//------------------------------------------------------------------------------
849// State save methods
850
851void MetricsService::ScheduleNextStateSave() {
852 state_saver_factory_.RevokeAll();
853
854 MessageLoop::current()->PostDelayedTask(FROM_HERE,
855 state_saver_factory_.NewRunnableMethod(&MetricsService::SaveLocalState),
856 kSaveStateInterval * 1000);
857}
858
859void MetricsService::SaveLocalState() {
860 PrefService* pref = g_browser_process->local_state();
861 if (!pref) {
jar@chromium.orga063c102010-07-22 22:20:19862 NOTREACHED();
initial.commit09911bf2008-07-26 23:55:29863 return;
864 }
865
866 RecordCurrentState(pref);
phajdan.jr@chromium.org6faa0e0d2009-04-28 06:50:36867 pref->ScheduleSavePersistentPrefs();
initial.commit09911bf2008-07-26 23:55:29868
jar@chromium.org281d2882009-01-20 20:32:42869 // TODO(jar): Does this run down the batteries????
initial.commit09911bf2008-07-26 23:55:29870 ScheduleNextStateSave();
871}
872
873
874//------------------------------------------------------------------------------
875// Recording control methods
876
877void MetricsService::StartRecording() {
878 if (current_log_)
879 return;
880
881 current_log_ = new MetricsLog(client_id_, session_id_);
882 if (state_ == INITIALIZED) {
883 // We only need to schedule that run once.
zelidrag@chromium.org85ed9d42010-06-08 22:37:44884 state_ = INIT_TASK_SCHEDULED;
initial.commit09911bf2008-07-26 23:55:29885
zelidrag@chromium.org85ed9d42010-06-08 22:37:44886 // Schedules a task on the file thread for execution of slower
887 // initialization steps (such as plugin list generation) necessary
888 // for sending the initial log. This avoids blocking the main UI
889 // thread.
jamesr@chromium.org7f2e792e2009-11-30 23:18:29890 g_browser_process->file_thread()->message_loop()->PostDelayedTask(FROM_HERE,
zelidrag@chromium.org85ed9d42010-06-08 22:37:44891 new InitTask(MessageLoop::current()),
petersont@google.com252873ef2008-08-04 21:59:45892 kInitialInterlogDuration * 1000 / 2);
initial.commit09911bf2008-07-26 23:55:29893 }
894}
895
ananta@chromium.org1226abb2010-06-10 18:01:28896void MetricsService::StopRecording(MetricsLogBase** log) {
initial.commit09911bf2008-07-26 23:55:29897 if (!current_log_)
898 return;
899
ananta@chromium.org1226abb2010-06-10 18:01:28900 MetricsLog* current_log = current_log_->AsMetricsLog();
901 DCHECK(current_log);
902 current_log->set_hardware_class(hardware_class_); // Adds to ongoing logs.
zelidrag@chromium.org85ed9d42010-06-08 22:37:44903
jar@google.com68475e602008-08-22 03:21:15904 // TODO(jar): Integrate bounds on log recording more consistently, so that we
905 // can stop recording logs that are too big much sooner.
petersont@google.comd01b8732008-10-16 02:18:07906 if (current_log_->num_events() > log_event_limit_) {
dsh@google.com553dba62009-02-24 19:08:23907 UMA_HISTOGRAM_COUNTS("UMA.Discarded Log Events",
jar@google.com68475e602008-08-22 03:21:15908 current_log_->num_events());
909 current_log_->CloseLog();
910 delete current_log_;
jar@google.com294638782008-09-24 00:22:41911 current_log_ = NULL;
jar@google.com68475e602008-08-22 03:21:15912 StartRecording(); // Start trivial log to hold our histograms.
913 }
914
jar@google.com0b33f80b2008-12-17 21:34:36915 // Put incremental data (histogram deltas, and realtime stats deltas) at the
jar@google.com147bbc0b2009-01-06 19:37:40916 // end of all log transmissions (initial log handles this separately).
initial.commit09911bf2008-07-26 23:55:29917 // Don't bother if we're going to discard current_log_.
jar@google.com0b33f80b2008-12-17 21:34:36918 if (log) {
ananta@chromium.org1226abb2010-06-10 18:01:28919 current_log->RecordIncrementalStabilityElements();
initial.commit09911bf2008-07-26 23:55:29920 RecordCurrentHistograms();
jar@google.com0b33f80b2008-12-17 21:34:36921 }
initial.commit09911bf2008-07-26 23:55:29922
923 current_log_->CloseLog();
pkasting@chromium.orgcac78842008-11-27 01:02:20924 if (log)
ananta@chromium.org1226abb2010-06-10 18:01:28925 *log = current_log;
pkasting@chromium.orgcac78842008-11-27 01:02:20926 else
initial.commit09911bf2008-07-26 23:55:29927 delete current_log_;
initial.commit09911bf2008-07-26 23:55:29928 current_log_ = NULL;
929}
930
initial.commit09911bf2008-07-26 23:55:29931void MetricsService::PushPendingLogsToUnsentLists() {
932 if (state_ < INITIAL_LOG_READY)
avi@google.com28ab7f92009-01-06 21:39:04933 return; // We didn't and still don't have time to get plugin list etc.
initial.commit09911bf2008-07-26 23:55:29934
935 if (pending_log()) {
936 PreparePendingLogText();
937 if (state_ == INITIAL_LOG_READY) {
938 // We may race here, and send second copy of initial log later.
ziadh@chromium.org46f89e142010-07-19 08:00:42939 unsent_initial_logs_.push_back(compressed_log_);
petersont@google.comd01b8732008-10-16 02:18:07940 state_ = SEND_OLD_INITIAL_LOGS;
initial.commit09911bf2008-07-26 23:55:29941 } else {
jar@chromium.org281d2882009-01-20 20:32:42942 // TODO(jar): Verify correctness in other states, including sending unsent
jar@chromium.org541f77922009-02-23 21:14:38943 // initial logs.
jar@google.com68475e602008-08-22 03:21:15944 PushPendingLogTextToUnsentOngoingLogs();
initial.commit09911bf2008-07-26 23:55:29945 }
946 DiscardPendingLog();
947 }
948 DCHECK(!pending_log());
949 StopRecording(&pending_log_);
950 PreparePendingLogText();
jar@google.com68475e602008-08-22 03:21:15951 PushPendingLogTextToUnsentOngoingLogs();
initial.commit09911bf2008-07-26 23:55:29952 DiscardPendingLog();
953 StoreUnsentLogs();
954}
955
jar@google.com68475e602008-08-22 03:21:15956void MetricsService::PushPendingLogTextToUnsentOngoingLogs() {
petersont@google.comd01b8732008-10-16 02:18:07957 // If UMA response told us not to upload, there's no need to save the pending
958 // log. It wasn't supposed to be uploaded anyway.
959 if (!server_permits_upload_)
960 return;
ziadh@chromium.org46f89e142010-07-19 08:00:42961 if (compressed_log_.length() >
paul@chromium.orgdc6f4962009-02-13 01:25:50962 static_cast<size_t>(kUploadLogAvoidRetransmitSize)) {
dsh@google.com553dba62009-02-24 19:08:23963 UMA_HISTOGRAM_COUNTS("UMA.Large Accumulated Log Not Persisted",
ziadh@chromium.org46f89e142010-07-19 08:00:42964 static_cast<int>(compressed_log_.length()));
jar@google.com68475e602008-08-22 03:21:15965 return;
966 }
ziadh@chromium.org46f89e142010-07-19 08:00:42967 unsent_ongoing_logs_.push_back(compressed_log_);
jar@google.com68475e602008-08-22 03:21:15968}
969
initial.commit09911bf2008-07-26 23:55:29970//------------------------------------------------------------------------------
971// Transmission of logs methods
972
973void MetricsService::StartLogTransmissionTimer() {
petersont@google.comd01b8732008-10-16 02:18:07974 // If we're not reporting, there's no point in starting a log transmission
975 // timer.
976 if (!reporting_active())
977 return;
978
initial.commit09911bf2008-07-26 23:55:29979 if (!current_log_)
980 return; // Recorder is shutdown.
petersont@google.comd01b8732008-10-16 02:18:07981
982 // If there is already a timer running, we leave it running.
983 // If timer_pending is true because the fetch is waiting for a response,
984 // we return for now and let the response handler start the timer.
985 if (timer_pending_)
initial.commit09911bf2008-07-26 23:55:29986 return;
petersont@google.comd01b8732008-10-16 02:18:07987
petersont@google.comd01b8732008-10-16 02:18:07988 // Before starting the timer, set timer_pending_ to true.
initial.commit09911bf2008-07-26 23:55:29989 timer_pending_ = true;
petersont@google.comd01b8732008-10-16 02:18:07990
991 // Right before the UMA transmission gets started, there's one more thing we'd
992 // like to record: the histogram of memory usage, so we spawn a task to
jar@chromium.orgc9a3ef82009-05-28 22:02:46993 // collect the memory details and when that task is finished, it will call
994 // OnMemoryDetailCollectionDone, which will call HistogramSynchronization to
995 // collect histograms from all renderers and then we will call
996 // OnHistogramSynchronizationDone to continue processing.
initial.commit09911bf2008-07-26 23:55:29997 MessageLoop::current()->PostDelayedTask(FROM_HERE,
998 log_sender_factory_.
jar@chromium.orgc9a3ef82009-05-28 22:02:46999 NewRunnableMethod(&MetricsService::LogTransmissionTimerDone),
phajdan.jr@chromium.org743ace42009-06-17 17:23:511000 interlog_duration_.InMilliseconds());
initial.commit09911bf2008-07-26 23:55:291001}
1002
jar@chromium.orgc9a3ef82009-05-28 22:02:461003void MetricsService::LogTransmissionTimerDone() {
1004 Task* task = log_sender_factory_.
1005 NewRunnableMethod(&MetricsService::OnMemoryDetailCollectionDone);
1006
jam@chromium.orge9adedb2009-12-01 22:23:591007 scoped_refptr<MetricsMemoryDetails> details = new MetricsMemoryDetails(task);
jar@chromium.orgc9a3ef82009-05-28 22:02:461008 details->StartFetch();
1009
1010 // Collect WebCore cache information to put into a histogram.
pkasting@chromium.org019191a2009-10-02 20:37:271011 for (RenderProcessHost::iterator i(RenderProcessHost::AllHostsIterator());
1012 !i.IsAtEnd(); i.Advance())
1013 i.GetCurrentValue()->Send(new ViewMsg_GetCacheResourceStats());
jar@chromium.orgc9a3ef82009-05-28 22:02:461014}
1015
1016void MetricsService::OnMemoryDetailCollectionDone() {
1017 DCHECK(IsSingleThreaded());
1018
1019 // HistogramSynchronizer will Collect histograms from all renderers and it
1020 // will call OnHistogramSynchronizationDone (if wait time elapses before it
1021 // heard from all renderers, then also it will call
1022 // OnHistogramSynchronizationDone).
1023
1024 // Create a callback_task for OnHistogramSynchronizationDone.
1025 Task* callback_task = log_sender_factory_.NewRunnableMethod(
1026 &MetricsService::OnHistogramSynchronizationDone);
1027
1028 // Set up the callback to task to call after we receive histograms from all
1029 // renderer processes. Wait time specifies how long to wait before absolutely
1030 // calling us back on the task.
1031 HistogramSynchronizer::FetchRendererHistogramsAsynchronously(
1032 MessageLoop::current(), callback_task,
1033 kMaxHistogramGatheringWaitDuration);
1034}
1035
1036void MetricsService::OnHistogramSynchronizationDone() {
initial.commit09911bf2008-07-26 23:55:291037 DCHECK(IsSingleThreaded());
1038
petersont@google.comd01b8732008-10-16 02:18:071039 // This function should only be called via timer, so timer_pending_
1040 // should be true.
1041 DCHECK(timer_pending_);
1042 timer_pending_ = false;
initial.commit09911bf2008-07-26 23:55:291043
1044 DCHECK(!current_fetch_.get());
initial.commit09911bf2008-07-26 23:55:291045
petersont@google.comd01b8732008-10-16 02:18:071046 // If we're getting no notifications, then the log won't have much in it, and
1047 // it's possible the computer is about to go to sleep, so don't upload and
1048 // don't restart the transmission timer.
1049 if (idle_since_last_transmission_)
1050 return;
1051
1052 // If somehow there is a fetch in progress, we return setting timer_pending_
1053 // to true and hope things work out.
1054 if (current_fetch_.get()) {
1055 timer_pending_ = true;
1056 return;
1057 }
1058
1059 // If uploads are forbidden by UMA response, there's no point in keeping
1060 // the current_log_, and the more often we delete it, the less likely it is
1061 // to expand forever.
1062 if (!server_permits_upload_ && current_log_) {
1063 StopRecording(NULL);
1064 StartRecording();
1065 }
initial.commit09911bf2008-07-26 23:55:291066
1067 if (!current_log_)
1068 return; // Logging was disabled.
petersont@google.comd01b8732008-10-16 02:18:071069 if (!reporting_active())
initial.commit09911bf2008-07-26 23:55:291070 return; // Don't do work if we're not going to send anything now.
1071
petersont@google.comd01b8732008-10-16 02:18:071072 MakePendingLog();
initial.commit09911bf2008-07-26 23:55:291073
petersont@google.comd01b8732008-10-16 02:18:071074 // MakePendingLog should have put something in the pending log, if it didn't,
1075 // we start the timer again, return and hope things work out.
1076 if (!pending_log()) {
1077 StartLogTransmissionTimer();
1078 return;
1079 }
initial.commit09911bf2008-07-26 23:55:291080
petersont@google.comd01b8732008-10-16 02:18:071081 // If we're not supposed to upload any UMA data because the response or the
1082 // user said so, cancel the upload at this point, but start the timer.
1083 if (!TransmissionPermitted()) {
1084 DiscardPendingLog();
1085 StartLogTransmissionTimer();
1086 return;
1087 }
initial.commit09911bf2008-07-26 23:55:291088
petersont@google.comd01b8732008-10-16 02:18:071089 PrepareFetchWithPendingLog();
1090
1091 if (!current_fetch_.get()) {
1092 // Compression failed, and log discarded :-/.
1093 DiscardPendingLog();
1094 StartLogTransmissionTimer(); // Maybe we'll do better next time
1095 // TODO(jar): If compression failed, we should have created a tiny log and
1096 // compressed that, so that we can signal that we're losing logs.
1097 return;
1098 }
1099
1100 DCHECK(!timer_pending_);
1101
1102 // The URL fetch is a like timer in that after a while we get called back
1103 // so we set timer_pending_ true just as we start the url fetch.
1104 timer_pending_ = true;
1105 current_fetch_->Start();
1106
1107 HandleIdleSinceLastTransmission(true);
1108}
1109
1110
1111void MetricsService::MakePendingLog() {
1112 if (pending_log())
1113 return;
1114
1115 switch (state_) {
1116 case INITIALIZED:
zelidrag@chromium.org85ed9d42010-06-08 22:37:441117 case INIT_TASK_SCHEDULED: // We should be further along by now.
petersont@google.comd01b8732008-10-16 02:18:071118 DCHECK(false);
1119 return;
1120
zelidrag@chromium.org85ed9d42010-06-08 22:37:441121 case INIT_TASK_DONE:
petersont@google.comd01b8732008-10-16 02:18:071122 // We need to wait for the initial log to be ready before sending
1123 // anything, because the server will tell us whether it wants to hear
1124 // from us.
1125 PrepareInitialLog();
zelidrag@chromium.org85ed9d42010-06-08 22:37:441126 DCHECK(state_ == INIT_TASK_DONE);
petersont@google.comd01b8732008-10-16 02:18:071127 RecallUnsentLogs();
1128 state_ = INITIAL_LOG_READY;
1129 break;
1130
1131 case SEND_OLD_INITIAL_LOGS:
pkasting@chromium.orgcac78842008-11-27 01:02:201132 if (!unsent_initial_logs_.empty()) {
ziadh@chromium.org46f89e142010-07-19 08:00:421133 compressed_log_ = unsent_initial_logs_.back();
pkasting@chromium.orgcac78842008-11-27 01:02:201134 break;
1135 }
petersont@google.comd01b8732008-10-16 02:18:071136 state_ = SENDING_OLD_LOGS;
1137 // Fall through.
initial.commit09911bf2008-07-26 23:55:291138
petersont@google.comd01b8732008-10-16 02:18:071139 case SENDING_OLD_LOGS:
1140 if (!unsent_ongoing_logs_.empty()) {
ziadh@chromium.org46f89e142010-07-19 08:00:421141 compressed_log_ = unsent_ongoing_logs_.back();
petersont@google.comd01b8732008-10-16 02:18:071142 break;
1143 }
1144 state_ = SENDING_CURRENT_LOGS;
1145 // Fall through.
1146
1147 case SENDING_CURRENT_LOGS:
1148 StopRecording(&pending_log_);
1149 StartRecording();
1150 break;
1151
1152 default:
jar@chromium.orga063c102010-07-22 22:20:191153 NOTREACHED();
petersont@google.comd01b8732008-10-16 02:18:071154 return;
1155 }
1156
1157 DCHECK(pending_log());
1158}
1159
1160bool MetricsService::TransmissionPermitted() const {
1161 // If the user forbids uploading that's they're business, and we don't upload
1162 // anything. If the server forbids uploading, that's our business, so we take
1163 // that to mean it forbids current logs, but we still send up the inital logs
1164 // and any old logs.
petersont@google.comd01b8732008-10-16 02:18:071165 if (!user_permits_upload_)
1166 return false;
pkasting@chromium.orgcac78842008-11-27 01:02:201167 if (server_permits_upload_)
petersont@google.comd01b8732008-10-16 02:18:071168 return true;
initial.commit09911bf2008-07-26 23:55:291169
pkasting@chromium.orgcac78842008-11-27 01:02:201170 switch (state_) {
1171 case INITIAL_LOG_READY:
1172 case SEND_OLD_INITIAL_LOGS:
1173 case SENDING_OLD_LOGS:
1174 return true;
1175
1176 case SENDING_CURRENT_LOGS:
1177 default:
1178 return false;
nsylvain@chromium.org8c8824b2008-09-20 01:55:501179 }
initial.commit09911bf2008-07-26 23:55:291180}
1181
initial.commit09911bf2008-07-26 23:55:291182void MetricsService::PrepareInitialLog() {
zelidrag@chromium.org85ed9d42010-06-08 22:37:441183 DCHECK(state_ == INIT_TASK_DONE);
initial.commit09911bf2008-07-26 23:55:291184
1185 MetricsLog* log = new MetricsLog(client_id_, session_id_);
zelidrag@chromium.org85ed9d42010-06-08 22:37:441186 log->set_hardware_class(hardware_class_); // Adds to initial log.
jam@chromium.org35fa6a22009-08-15 00:04:011187 log->RecordEnvironment(plugins_, profile_dictionary_.get());
initial.commit09911bf2008-07-26 23:55:291188
1189 // Histograms only get written to current_log_, so setup for the write.
ananta@chromium.org1226abb2010-06-10 18:01:281190 MetricsLogBase* save_log = current_log_;
initial.commit09911bf2008-07-26 23:55:291191 current_log_ = log;
1192 RecordCurrentHistograms(); // Into current_log_... which is really log.
1193 current_log_ = save_log;
1194
1195 log->CloseLog();
1196 DCHECK(!pending_log());
1197 pending_log_ = log;
1198}
1199
ziadh@chromium.org46f89e142010-07-19 08:00:421200// static
1201MetricsService::LogRecallStatus MetricsService::RecallUnsentLogsHelper(
1202 const ListValue& list,
1203 std::vector<std::string>* local_list) {
1204 DCHECK(local_list->empty());
1205 if (list.GetSize() == 0)
1206 return MakeRecallStatusHistogram(LIST_EMPTY);
1207 if (list.GetSize() < 3)
1208 return MakeRecallStatusHistogram(LIST_SIZE_TOO_SMALL);
initial.commit09911bf2008-07-26 23:55:291209
ziadh@chromium.org46f89e142010-07-19 08:00:421210 // The size is stored at the beginning of the list.
1211 int size;
1212 bool valid = (*list.begin())->GetAsInteger(&size);
1213 if (!valid)
1214 return MakeRecallStatusHistogram(LIST_SIZE_MISSING);
1215
1216 // Account for checksum and size included in the list.
1217 if (static_cast<unsigned int>(size) !=
1218 list.GetSize() - kChecksumEntryCount)
1219 return MakeRecallStatusHistogram(LIST_SIZE_CORRUPTION);
1220
1221 MD5Context ctx;
1222 MD5Init(&ctx);
1223 std::string encoded_log;
1224 std::string decoded_log;
1225 for (ListValue::const_iterator it = list.begin() + 1;
1226 it != list.end() - 1; ++it) { // Last element is the checksum.
1227 valid = (*it)->GetAsString(&encoded_log);
1228 if (!valid) {
1229 local_list->clear();
1230 return MakeRecallStatusHistogram(LOG_STRING_CORRUPTION);
1231 }
1232
1233 MD5Update(&ctx, encoded_log.data(), encoded_log.length());
1234
1235 if (!base::Base64Decode(encoded_log, &decoded_log)) {
1236 local_list->clear();
1237 return MakeRecallStatusHistogram(DECODE_FAIL);
1238 }
1239 local_list->push_back(decoded_log);
1240 }
1241
1242 // Verify checksum.
1243 MD5Digest digest;
1244 MD5Final(&digest, &ctx);
1245 std::string recovered_md5;
1246 // We store the hash at the end of the list.
1247 valid = (*(list.end() - 1))->GetAsString(&recovered_md5);
1248 if (!valid) {
1249 local_list->clear();
1250 return MakeRecallStatusHistogram(CHECKSUM_STRING_CORRUPTION);
1251 }
1252 if (recovered_md5 != MD5DigestToBase16(digest)) {
1253 local_list->clear();
1254 return MakeRecallStatusHistogram(CHECKSUM_CORRUPTION);
1255 }
1256 return MakeRecallStatusHistogram(RECALL_SUCCESS);
1257}
1258void MetricsService::RecallUnsentLogs() {
initial.commit09911bf2008-07-26 23:55:291259 PrefService* local_state = g_browser_process->local_state();
1260 DCHECK(local_state);
1261
1262 ListValue* unsent_initial_logs = local_state->GetMutableList(
1263 prefs::kMetricsInitialLogs);
ziadh@chromium.org46f89e142010-07-19 08:00:421264 RecallUnsentLogsHelper(*unsent_initial_logs, &unsent_initial_logs_);
initial.commit09911bf2008-07-26 23:55:291265
1266 ListValue* unsent_ongoing_logs = local_state->GetMutableList(
1267 prefs::kMetricsOngoingLogs);
ziadh@chromium.org46f89e142010-07-19 08:00:421268 RecallUnsentLogsHelper(*unsent_ongoing_logs, &unsent_ongoing_logs_);
1269}
1270
1271// static
1272void MetricsService::StoreUnsentLogsHelper(
1273 const std::vector<std::string>& local_list,
1274 const size_t kMaxLocalListSize,
1275 ListValue* list) {
1276 list->Clear();
1277 size_t start = 0;
1278 if (local_list.size() > kMaxLocalListSize)
1279 start = local_list.size() - kMaxLocalListSize;
1280 DCHECK(start <= local_list.size());
1281 if (local_list.size() == start)
1282 return;
1283
1284 // Store size at the beginning of the list.
1285 list->Append(Value::CreateIntegerValue(local_list.size() - start));
1286
1287 MD5Context ctx;
1288 MD5Init(&ctx);
1289 std::string encoded_log;
1290 for (std::vector<std::string>::const_iterator it = local_list.begin() + start;
1291 it != local_list.end(); ++it) {
1292 // We encode the compressed log as Value::CreateStringValue() expects to
1293 // take a valid UTF8 string.
1294 if (!base::Base64Encode(*it, &encoded_log)) {
1295 MakeStoreStatusHistogram(ENCODE_FAIL);
1296 list->Clear();
1297 return;
1298 }
1299 MD5Update(&ctx, encoded_log.data(), encoded_log.length());
1300 list->Append(Value::CreateStringValue(encoded_log));
initial.commit09911bf2008-07-26 23:55:291301 }
ziadh@chromium.org46f89e142010-07-19 08:00:421302
1303 // Append hash to the end of the list.
1304 MD5Digest digest;
1305 MD5Final(&digest, &ctx);
1306 list->Append(Value::CreateStringValue(MD5DigestToBase16(digest)));
1307 DCHECK(list->GetSize() >= 3); // Minimum of 3 elements (size, data, hash).
ziadh@chromium.org4e95d202010-07-24 01:47:561308 MakeStoreStatusHistogram(STORE_SUCCESS);
initial.commit09911bf2008-07-26 23:55:291309}
1310
1311void MetricsService::StoreUnsentLogs() {
1312 if (state_ < INITIAL_LOG_READY)
1313 return; // We never Recalled the prior unsent logs.
1314
1315 PrefService* local_state = g_browser_process->local_state();
1316 DCHECK(local_state);
1317
1318 ListValue* unsent_initial_logs = local_state->GetMutableList(
1319 prefs::kMetricsInitialLogs);
ziadh@chromium.org46f89e142010-07-19 08:00:421320 StoreUnsentLogsHelper(unsent_initial_logs_, kMaxInitialLogsPersisted,
1321 unsent_initial_logs);
initial.commit09911bf2008-07-26 23:55:291322
1323 ListValue* unsent_ongoing_logs = local_state->GetMutableList(
1324 prefs::kMetricsOngoingLogs);
ziadh@chromium.org46f89e142010-07-19 08:00:421325 StoreUnsentLogsHelper(unsent_ongoing_logs_, kMaxOngoingLogsPersisted,
1326 unsent_ongoing_logs);
initial.commit09911bf2008-07-26 23:55:291327}
1328
1329void MetricsService::PreparePendingLogText() {
1330 DCHECK(pending_log());
ziadh@chromium.org46f89e142010-07-19 08:00:421331 if (!compressed_log_.empty())
initial.commit09911bf2008-07-26 23:55:291332 return;
mark@chromium.org9ffcccf42009-09-15 22:19:181333 int text_size = pending_log_->GetEncodedLogSize();
1334
ziadh@chromium.org46f89e142010-07-19 08:00:421335 std::string pending_log_text;
1336 // Leave room for the NULL terminator.
1337 pending_log_->GetEncodedLog(WriteInto(&pending_log_text, text_size + 1),
mark@chromium.org9ffcccf42009-09-15 22:19:181338 text_size);
ziadh@chromium.org46f89e142010-07-19 08:00:421339
1340 if (Bzip2Compress(pending_log_text, &compressed_log_)) {
1341 // Allow security conscious users to see all metrics logs that we send.
1342 LOG(INFO) << "COMPRESSED FOLLOWING METRICS LOG: " << pending_log_text;
1343 } else {
1344 LOG(DFATAL) << "Failed to compress log for transmission.";
1345 // We can't discard the logs as other caller functions expect that
1346 // |compressed_log_| not be empty. We can detect this failure at the server
1347 // after we transmit.
1348 compressed_log_ = "Unable to compress!";
1349 MakeStoreStatusHistogram(COMPRESS_FAIL);
1350 return;
1351 }
initial.commit09911bf2008-07-26 23:55:291352}
1353
petersont@google.comd01b8732008-10-16 02:18:071354void MetricsService::PrepareFetchWithPendingLog() {
initial.commit09911bf2008-07-26 23:55:291355 DCHECK(pending_log());
1356 DCHECK(!current_fetch_.get());
1357 PreparePendingLogText();
ziadh@chromium.org46f89e142010-07-19 08:00:421358 DCHECK(!compressed_log_.empty());
pkasting@chromium.orgcac78842008-11-27 01:02:201359
kuchhal@chromium.org79bf0b72009-04-27 21:30:551360 current_fetch_.reset(new URLFetcher(GURL(WideToUTF16(server_url_)),
1361 URLFetcher::POST,
initial.commit09911bf2008-07-26 23:55:291362 this));
1363 current_fetch_->set_request_context(Profile::GetDefaultRequestContext());
ziadh@chromium.org46f89e142010-07-19 08:00:421364 current_fetch_->set_upload_data(kMetricsType, compressed_log_);
initial.commit09911bf2008-07-26 23:55:291365}
1366
initial.commit09911bf2008-07-26 23:55:291367static const char* StatusToString(const URLRequestStatus& status) {
1368 switch (status.status()) {
1369 case URLRequestStatus::SUCCESS:
1370 return "SUCCESS";
1371
1372 case URLRequestStatus::IO_PENDING:
1373 return "IO_PENDING";
1374
1375 case URLRequestStatus::HANDLED_EXTERNALLY:
1376 return "HANDLED_EXTERNALLY";
1377
1378 case URLRequestStatus::CANCELED:
1379 return "CANCELED";
1380
1381 case URLRequestStatus::FAILED:
1382 return "FAILED";
1383
1384 default:
jar@chromium.orga063c102010-07-22 22:20:191385 NOTREACHED();
initial.commit09911bf2008-07-26 23:55:291386 return "Unknown";
1387 }
1388}
1389
1390void MetricsService::OnURLFetchComplete(const URLFetcher* source,
1391 const GURL& url,
1392 const URLRequestStatus& status,
1393 int response_code,
1394 const ResponseCookies& cookies,
1395 const std::string& data) {
1396 DCHECK(timer_pending_);
1397 timer_pending_ = false;
1398 DCHECK(current_fetch_.get());
1399 current_fetch_.reset(NULL); // We're not allowed to re-use it.
1400
1401 // Confirm send so that we can move on.
jar@chromium.org281d2882009-01-20 20:32:421402 LOG(INFO) << "METRICS RESPONSE CODE: " << response_code << " status=" <<
pkasting@chromium.orgcac78842008-11-27 01:02:201403 StatusToString(status);
petersont@google.com252873ef2008-08-04 21:59:451404
jar@chromium.org0eb34fee2009-01-21 08:04:381405 // Provide boolean for error recovery (allow us to ignore response_code).
paul@chromium.orgdc6f4962009-02-13 01:25:501406 bool discard_log = false;
jar@chromium.org0eb34fee2009-01-21 08:04:381407
jar@google.com68475e602008-08-22 03:21:151408 if (response_code != 200 &&
ziadh@chromium.org46f89e142010-07-19 08:00:421409 (compressed_log_.length() >
1410 static_cast<size_t>(kUploadLogAvoidRetransmitSize))) {
dsh@google.com553dba62009-02-24 19:08:231411 UMA_HISTOGRAM_COUNTS("UMA.Large Rejected Log was Discarded",
ziadh@chromium.org46f89e142010-07-19 08:00:421412 static_cast<int>(compressed_log_.length()));
jar@chromium.org0eb34fee2009-01-21 08:04:381413 discard_log = true;
1414 } else if (response_code == 400) {
1415 // Bad syntax. Retransmission won't work.
dsh@google.com553dba62009-02-24 19:08:231416 UMA_HISTOGRAM_COUNTS("UMA.Unacceptable_Log_Discarded", state_);
jar@chromium.org0eb34fee2009-01-21 08:04:381417 discard_log = true;
jar@google.com68475e602008-08-22 03:21:151418 }
1419
jar@chromium.org0eb34fee2009-01-21 08:04:381420 if (response_code != 200 && !discard_log) {
jar@chromium.org281d2882009-01-20 20:32:421421 LOG(INFO) << "METRICS: transmission attempt returned a failure code: "
1422 << response_code << ". Verify network connectivity";
petersont@google.com252873ef2008-08-04 21:59:451423 HandleBadResponseCode();
jar@chromium.org0eb34fee2009-01-21 08:04:381424 } else { // Successful receipt (or we are discarding log).
jar@chromium.org281d2882009-01-20 20:32:421425 LOG(INFO) << "METRICS RESPONSE DATA: " << data;
initial.commit09911bf2008-07-26 23:55:291426 switch (state_) {
1427 case INITIAL_LOG_READY:
1428 state_ = SEND_OLD_INITIAL_LOGS;
1429 break;
1430
1431 case SEND_OLD_INITIAL_LOGS:
1432 DCHECK(!unsent_initial_logs_.empty());
1433 unsent_initial_logs_.pop_back();
1434 StoreUnsentLogs();
1435 break;
1436
1437 case SENDING_OLD_LOGS:
1438 DCHECK(!unsent_ongoing_logs_.empty());
1439 unsent_ongoing_logs_.pop_back();
1440 StoreUnsentLogs();
1441 break;
1442
1443 case SENDING_CURRENT_LOGS:
1444 break;
1445
1446 default:
jar@chromium.orga063c102010-07-22 22:20:191447 NOTREACHED();
initial.commit09911bf2008-07-26 23:55:291448 break;
1449 }
petersont@google.comd01b8732008-10-16 02:18:071450
initial.commit09911bf2008-07-26 23:55:291451 DiscardPendingLog();
jar@google.com29be92552008-08-07 22:49:271452 // Since we sent a log, make sure our in-memory state is recorded to disk.
1453 PrefService* local_state = g_browser_process->local_state();
1454 DCHECK(local_state);
1455 if (local_state)
phajdan.jr@chromium.org6faa0e0d2009-04-28 06:50:361456 local_state->ScheduleSavePersistentPrefs();
petersont@google.com252873ef2008-08-04 21:59:451457
jar@google.com147bbc0b2009-01-06 19:37:401458 // Provide a default (free of exponetial backoff, other varances) in case
1459 // the server does not specify a value.
1460 interlog_duration_ = TimeDelta::FromSeconds(kMinSecondsPerLog);
1461
petersont@google.com252873ef2008-08-04 21:59:451462 GetSettingsFromResponseData(data);
petersont@google.com252873ef2008-08-04 21:59:451463 // Override server specified interlog delay if there are unsent logs to
jar@google.com29be92552008-08-07 22:49:271464 // transmit.
initial.commit09911bf2008-07-26 23:55:291465 if (unsent_logs()) {
1466 DCHECK(state_ < SENDING_CURRENT_LOGS);
1467 interlog_duration_ = TimeDelta::FromSeconds(kUnsentLogDelay);
initial.commit09911bf2008-07-26 23:55:291468 }
1469 }
petersont@google.com252873ef2008-08-04 21:59:451470
initial.commit09911bf2008-07-26 23:55:291471 StartLogTransmissionTimer();
1472}
1473
petersont@google.com252873ef2008-08-04 21:59:451474void MetricsService::HandleBadResponseCode() {
jar@chromium.org281d2882009-01-20 20:32:421475 LOG(INFO) << "Verify your metrics logs are formatted correctly. "
kuchhal@chromium.org79bf0b72009-04-27 21:30:551476 "Verify server is active at " << server_url_;
petersont@google.com252873ef2008-08-04 21:59:451477 if (!pending_log()) {
jar@chromium.org281d2882009-01-20 20:32:421478 LOG(INFO) << "METRICS: Recorder shutdown during log transmission.";
petersont@google.com252873ef2008-08-04 21:59:451479 } else {
1480 // Send progressively less frequently.
1481 DCHECK(kBackoff > 1.0);
1482 interlog_duration_ = TimeDelta::FromMicroseconds(
1483 static_cast<int64>(kBackoff * interlog_duration_.InMicroseconds()));
1484
1485 if (kMaxBackoff * TimeDelta::FromSeconds(kMinSecondsPerLog) <
pkasting@chromium.orgcac78842008-11-27 01:02:201486 interlog_duration_) {
petersont@google.com252873ef2008-08-04 21:59:451487 interlog_duration_ = kMaxBackoff *
1488 TimeDelta::FromSeconds(kMinSecondsPerLog);
pkasting@chromium.orgcac78842008-11-27 01:02:201489 }
petersont@google.com252873ef2008-08-04 21:59:451490
jar@chromium.org281d2882009-01-20 20:32:421491 LOG(INFO) << "METRICS: transmission retry being scheduled in " <<
petersont@google.com252873ef2008-08-04 21:59:451492 interlog_duration_.InSeconds() << " seconds for " <<
ziadh@chromium.org46f89e142010-07-19 08:00:421493 compressed_log_;
initial.commit09911bf2008-07-26 23:55:291494 }
initial.commit09911bf2008-07-26 23:55:291495}
1496
petersont@google.com252873ef2008-08-04 21:59:451497void MetricsService::GetSettingsFromResponseData(const std::string& data) {
1498 // We assume that the file is structured as a block opened by <response>
petersont@google.comd01b8732008-10-16 02:18:071499 // and that inside response, there is a block opened by tag <chrome_config>
1500 // other tags are ignored for now except the content of <chrome_config>.
jar@chromium.org281d2882009-01-20 20:32:421501 LOG(INFO) << "METRICS: getting settings from response data: " << data;
petersont@google.comd01b8732008-10-16 02:18:071502
petersont@google.com252873ef2008-08-04 21:59:451503 int data_size = static_cast<int>(data.size());
1504 if (data_size < 0) {
jar@chromium.org281d2882009-01-20 20:32:421505 LOG(INFO) << "METRICS: server response data bad size: " << data_size <<
pkasting@chromium.orgcac78842008-11-27 01:02:201506 "; aborting extraction of settings";
petersont@google.com252873ef2008-08-04 21:59:451507 return;
1508 }
pkasting@chromium.orgcac78842008-11-27 01:02:201509 xmlDocPtr doc = xmlReadMemory(data.c_str(), data_size, "", NULL, 0);
petersont@google.comd01b8732008-10-16 02:18:071510 // If the document is malformed, we just use the settings that were there.
1511 if (!doc) {
jar@chromium.org281d2882009-01-20 20:32:421512 LOG(INFO) << "METRICS: reading xml from server response data failed";
petersont@google.com252873ef2008-08-04 21:59:451513 return;
petersont@google.comd01b8732008-10-16 02:18:071514 }
petersont@google.com252873ef2008-08-04 21:59:451515
petersont@google.comd01b8732008-10-16 02:18:071516 xmlNodePtr top_node = xmlDocGetRootElement(doc), chrome_config_node = NULL;
1517 // Here, we find the chrome_config node by name.
petersont@google.com252873ef2008-08-04 21:59:451518 for (xmlNodePtr p = top_node->children; p; p = p->next) {
petersont@google.comd01b8732008-10-16 02:18:071519 if (xmlStrEqual(p->name, BAD_CAST "chrome_config")) {
1520 chrome_config_node = p;
petersont@google.com252873ef2008-08-04 21:59:451521 break;
1522 }
1523 }
1524 // If the server data is formatted wrong and there is no
1525 // config node where we expect, we just drop out.
petersont@google.comd01b8732008-10-16 02:18:071526 if (chrome_config_node != NULL)
1527 GetSettingsFromChromeConfigNode(chrome_config_node);
petersont@google.com252873ef2008-08-04 21:59:451528 xmlFreeDoc(doc);
1529}
1530
petersont@google.comd01b8732008-10-16 02:18:071531void MetricsService::GetSettingsFromChromeConfigNode(
1532 xmlNodePtr chrome_config_node) {
1533 // Iterate through all children of the config node.
1534 for (xmlNodePtr current_node = chrome_config_node->children;
1535 current_node;
1536 current_node = current_node->next) {
1537 // If we find the upload tag, we appeal to another function
1538 // GetSettingsFromUploadNode to read all the data in it.
petersont@google.com252873ef2008-08-04 21:59:451539 if (xmlStrEqual(current_node->name, BAD_CAST "upload")) {
petersont@google.comd01b8732008-10-16 02:18:071540 GetSettingsFromUploadNode(current_node);
petersont@google.com252873ef2008-08-04 21:59:451541 continue;
1542 }
1543 }
1544}
initial.commit09911bf2008-07-26 23:55:291545
petersont@google.comd01b8732008-10-16 02:18:071546void MetricsService::InheritedProperties::OverwriteWhereNeeded(
1547 xmlNodePtr node) {
1548 xmlChar* salt_value = xmlGetProp(node, BAD_CAST "salt");
1549 if (salt_value) // If the property isn't there, xmlGetProp returns NULL.
1550 salt = atoi(reinterpret_cast<char*>(salt_value));
1551 // If the property isn't there, we keep the value the property had before
1552
1553 xmlChar* denominator_value = xmlGetProp(node, BAD_CAST "denominator");
1554 if (denominator_value)
1555 denominator = atoi(reinterpret_cast<char*>(denominator_value));
1556}
1557
1558void MetricsService::GetSettingsFromUploadNode(xmlNodePtr upload_node) {
1559 InheritedProperties props;
1560 GetSettingsFromUploadNodeRecursive(upload_node, props, "", true);
1561}
1562
pkasting@chromium.orgcac78842008-11-27 01:02:201563void MetricsService::GetSettingsFromUploadNodeRecursive(
1564 xmlNodePtr node,
1565 InheritedProperties props,
1566 std::string path_prefix,
1567 bool uploadOn) {
petersont@google.comd01b8732008-10-16 02:18:071568 props.OverwriteWhereNeeded(node);
1569
1570 // The bool uploadOn is set to true if the data represented by current
1571 // node should be uploaded. This gets inherited in the tree; the children
1572 // of a node that has already been rejected for upload get rejected for
1573 // upload.
1574 uploadOn = uploadOn && NodeProbabilityTest(node, props);
1575
1576 // The path is a / separated list of the node names ancestral to the current
1577 // one. So, if you want to check if the current node has a certain name,
1578 // compare to name. If you want to check if it is a certan tag at a certain
1579 // place in the tree, compare to the whole path.
1580 std::string name = std::string(reinterpret_cast<const char*>(node->name));
1581 std::string path = path_prefix + "/" + name;
1582
1583 if (path == "/upload") {
1584 xmlChar* upload_interval_val = xmlGetProp(node, BAD_CAST "interval");
1585 if (upload_interval_val) {
1586 interlog_duration_ = TimeDelta::FromSeconds(
1587 atoi(reinterpret_cast<char*>(upload_interval_val)));
1588 }
1589
1590 server_permits_upload_ = uploadOn;
ziadh@chromium.org24d07e32010-07-10 00:31:271591 } else if (path == "/upload/logs") {
petersont@google.comd01b8732008-10-16 02:18:071592 xmlChar* log_event_limit_val = xmlGetProp(node, BAD_CAST "event_limit");
1593 if (log_event_limit_val)
1594 log_event_limit_ = atoi(reinterpret_cast<char*>(log_event_limit_val));
1595 }
petersont@google.comd01b8732008-10-16 02:18:071596
1597 // Recursive call. If the node is a leaf i.e. if it ends in a "/>", then it
1598 // doesn't have children, so node->children is NULL, and this loop doesn't
1599 // call (that's how the recursion ends).
1600 for (xmlNodePtr child_node = node->children;
pkasting@chromium.orgcac78842008-11-27 01:02:201601 child_node;
1602 child_node = child_node->next) {
petersont@google.comd01b8732008-10-16 02:18:071603 GetSettingsFromUploadNodeRecursive(child_node, props, path, uploadOn);
1604 }
1605}
1606
1607bool MetricsService::NodeProbabilityTest(xmlNodePtr node,
pkasting@chromium.orgcac78842008-11-27 01:02:201608 InheritedProperties props) const {
petersont@google.comd01b8732008-10-16 02:18:071609 // Default value of probability on any node is 1, but recall that
1610 // its parents can already have been rejected for upload.
1611 double probability = 1;
1612
1613 // If a probability is specified in the node, we use it instead.
1614 xmlChar* probability_value = xmlGetProp(node, BAD_CAST "probability");
1615 if (probability_value)
jar@google.com0b33f80b2008-12-17 21:34:361616 probability = atoi(reinterpret_cast<char*>(probability_value));
petersont@google.comd01b8732008-10-16 02:18:071617
1618 return ProbabilityTest(probability, props.salt, props.denominator);
1619}
1620
1621bool MetricsService::ProbabilityTest(double probability,
1622 int salt,
1623 int denominator) const {
1624 // Okay, first we figure out how many of the digits of the
1625 // client_id_ we need in order to make a nice pseudorandomish
1626 // number in the range [0,denominator). Too many digits is
1627 // fine.
petersont@google.comd01b8732008-10-16 02:18:071628
1629 // n is the length of the client_id_ string
1630 size_t n = client_id_.size();
1631
1632 // idnumber is a positive integer generated from the client_id_.
1633 // It plus salt is going to give us our pseudorandom number.
1634 int idnumber = 0;
1635 const char* client_id_c_str = client_id_.c_str();
1636
1637 // Here we hash the relevant digits of the client_id_
1638 // string somehow to get a big integer idnumber (could be negative
1639 // from wraparound)
1640 int big = 1;
robertshield@google.com5ed73342009-03-18 17:39:431641 int last_pos = n - 1;
1642 for (size_t j = 0; j < n; ++j) {
1643 idnumber += static_cast<int>(client_id_c_str[last_pos - j]) * big;
petersont@google.comd01b8732008-10-16 02:18:071644 big *= 10;
1645 }
1646
1647 // Mod id number by denominator making sure to get a non-negative
1648 // answer.
pkasting@chromium.orgcac78842008-11-27 01:02:201649 idnumber = ((idnumber % denominator) + denominator) % denominator;
petersont@google.comd01b8732008-10-16 02:18:071650
pkasting@chromium.orgcac78842008-11-27 01:02:201651 // ((idnumber + salt) % denominator) / denominator is in the range [0,1]
petersont@google.comd01b8732008-10-16 02:18:071652 // if it's less than probability we call that an affirmative coin
1653 // toss.
pkasting@chromium.orgcac78842008-11-27 01:02:201654 return static_cast<double>((idnumber + salt) % denominator) <
1655 probability * denominator;
petersont@google.comd01b8732008-10-16 02:18:071656}
1657
initial.commit09911bf2008-07-26 23:55:291658void MetricsService::LogWindowChange(NotificationType type,
1659 const NotificationSource& source,
1660 const NotificationDetails& details) {
brettw@google.com534e54b2008-08-13 15:40:091661 int controller_id = -1;
1662 uintptr_t window_or_tab = source.map_key();
initial.commit09911bf2008-07-26 23:55:291663 MetricsLog::WindowEventType window_type;
1664
1665 // Note: since we stop all logging when a single OTR session is active, it is
1666 // possible that we start getting notifications about a window that we don't
1667 // know about.
brettw@google.com534e54b2008-08-13 15:40:091668 if (window_map_.find(window_or_tab) == window_map_.end()) {
1669 controller_id = next_window_id_++;
1670 window_map_[window_or_tab] = controller_id;
initial.commit09911bf2008-07-26 23:55:291671 } else {
brettw@google.com534e54b2008-08-13 15:40:091672 controller_id = window_map_[window_or_tab];
initial.commit09911bf2008-07-26 23:55:291673 }
jar@chromium.org92745242009-06-12 16:52:211674 DCHECK_NE(controller_id, -1);
initial.commit09911bf2008-07-26 23:55:291675
brettw@chromium.orgbfd04a62009-02-01 18:16:561676 switch (type.value) {
1677 case NotificationType::TAB_PARENTED:
1678 case NotificationType::BROWSER_OPENED:
initial.commit09911bf2008-07-26 23:55:291679 window_type = MetricsLog::WINDOW_CREATE;
1680 break;
1681
brettw@chromium.orgbfd04a62009-02-01 18:16:561682 case NotificationType::TAB_CLOSING:
1683 case NotificationType::BROWSER_CLOSED:
brettw@google.com534e54b2008-08-13 15:40:091684 window_map_.erase(window_map_.find(window_or_tab));
initial.commit09911bf2008-07-26 23:55:291685 window_type = MetricsLog::WINDOW_DESTROY;
1686 break;
1687
1688 default:
jar@chromium.orga063c102010-07-22 22:20:191689 NOTREACHED();
paul@chromium.org68d74f02009-02-13 01:36:501690 return;
initial.commit09911bf2008-07-26 23:55:291691 }
1692
brettw@google.com534e54b2008-08-13 15:40:091693 // TODO(brettw) we should have some kind of ID for the parent.
1694 current_log_->RecordWindowEvent(window_type, controller_id, 0);
initial.commit09911bf2008-07-26 23:55:291695}
1696
1697void MetricsService::LogLoadComplete(NotificationType type,
1698 const NotificationSource& source,
1699 const NotificationDetails& details) {
1700 if (details == NotificationService::NoDetails())
1701 return;
1702
jar@google.com68475e602008-08-22 03:21:151703 // TODO(jar): There is a bug causing this to be called too many times, and
1704 // the log overflows. For now, we won't record these events.
dsh@google.com553dba62009-02-24 19:08:231705 UMA_HISTOGRAM_COUNTS("UMA.LogLoadComplete called", 1);
jar@google.com68475e602008-08-22 03:21:151706 return;
1707
initial.commit09911bf2008-07-26 23:55:291708 const Details<LoadNotificationDetails> load_details(details);
brettw@google.com534e54b2008-08-13 15:40:091709 int controller_id = window_map_[details.map_key()];
1710 current_log_->RecordLoadEvent(controller_id,
initial.commit09911bf2008-07-26 23:55:291711 load_details->url(),
1712 load_details->origin(),
1713 load_details->session_index(),
1714 load_details->load_time());
1715}
1716
cpu@google.come73c01972008-08-13 00:18:241717void MetricsService::IncrementPrefValue(const wchar_t* path) {
1718 PrefService* pref = g_browser_process->local_state();
1719 DCHECK(pref);
1720 int value = pref->GetInteger(path);
1721 pref->SetInteger(path, value + 1);
1722}
1723
robertshield@google.com0bb1a622009-03-04 03:22:321724void MetricsService::IncrementLongPrefsValue(const wchar_t* path) {
1725 PrefService* pref = g_browser_process->local_state();
1726 DCHECK(pref);
1727 int64 value = pref->GetInt64(path);
jar@chromium.orgb42c5e42010-06-03 20:43:251728 pref->SetInt64(path, value + 1);
robertshield@google.com0bb1a622009-03-04 03:22:321729}
1730
initial.commit09911bf2008-07-26 23:55:291731void MetricsService::LogLoadStarted() {
cpu@google.come73c01972008-08-13 00:18:241732 IncrementPrefValue(prefs::kStabilityPageLoadCount);
robertshield@google.com0bb1a622009-03-04 03:22:321733 IncrementLongPrefsValue(prefs::kUninstallMetricsPageLoadCount);
jar@google.com0b33f80b2008-12-17 21:34:361734 // We need to save the prefs, as page load count is a critical stat, and it
1735 // might be lost due to a crash :-(.
initial.commit09911bf2008-07-26 23:55:291736}
1737
initial.commit09911bf2008-07-26 23:55:291738void MetricsService::LogRendererCrash() {
cpu@google.come73c01972008-08-13 00:18:241739 IncrementPrefValue(prefs::kStabilityRendererCrashCount);
initial.commit09911bf2008-07-26 23:55:291740}
1741
asargent@chromium.org1f085622009-12-04 05:33:451742void MetricsService::LogExtensionRendererCrash() {
1743 IncrementPrefValue(prefs::kStabilityExtensionRendererCrashCount);
1744}
1745
initial.commit09911bf2008-07-26 23:55:291746void MetricsService::LogRendererHang() {
cpu@google.come73c01972008-08-13 00:18:241747 IncrementPrefValue(prefs::kStabilityRendererHangCount);
initial.commit09911bf2008-07-26 23:55:291748}
1749
jam@chromium.orga27a9382009-02-11 23:55:101750void MetricsService::LogChildProcessChange(
1751 NotificationType type,
1752 const NotificationSource& source,
1753 const NotificationDetails& details) {
gregoryd@google.com0d84c5d2009-10-09 01:10:421754 Details<ChildProcessInfo> child_details(details);
1755 const std::wstring& child_name = child_details->name();
1756
jam@chromium.orga27a9382009-02-11 23:55:101757 if (child_process_stats_buffer_.find(child_name) ==
1758 child_process_stats_buffer_.end()) {
gregoryd@google.com0d84c5d2009-10-09 01:10:421759 child_process_stats_buffer_[child_name] =
1760 ChildProcessStats(child_details->type());
initial.commit09911bf2008-07-26 23:55:291761 }
1762
jam@chromium.orga27a9382009-02-11 23:55:101763 ChildProcessStats& stats = child_process_stats_buffer_[child_name];
brettw@chromium.orgbfd04a62009-02-01 18:16:561764 switch (type.value) {
jam@chromium.orga27a9382009-02-11 23:55:101765 case NotificationType::CHILD_PROCESS_HOST_CONNECTED:
initial.commit09911bf2008-07-26 23:55:291766 stats.process_launches++;
1767 break;
1768
jam@chromium.orga27a9382009-02-11 23:55:101769 case NotificationType::CHILD_INSTANCE_CREATED:
initial.commit09911bf2008-07-26 23:55:291770 stats.instances++;
1771 break;
1772
jam@chromium.orga27a9382009-02-11 23:55:101773 case NotificationType::CHILD_PROCESS_CRASHED:
initial.commit09911bf2008-07-26 23:55:291774 stats.process_crashes++;
asargent@chromium.org1f085622009-12-04 05:33:451775 // Exclude plugin crashes from the count below because we report them via
1776 // a separate UMA metric.
1777 if (child_details->type() != ChildProcessInfo::PLUGIN_PROCESS) {
1778 IncrementPrefValue(prefs::kStabilityChildProcessCrashCount);
1779 }
initial.commit09911bf2008-07-26 23:55:291780 break;
1781
1782 default:
jar@chromium.orga063c102010-07-22 22:20:191783 NOTREACHED() << "Unexpected notification type " << type.value;
initial.commit09911bf2008-07-26 23:55:291784 return;
1785 }
1786}
1787
1788// Recursively counts the number of bookmarks and folders in node.
munjal@chromium.orgb3c33d462009-06-26 22:29:201789static void CountBookmarks(const BookmarkNode* node,
1790 int* bookmarks,
1791 int* folders) {
sky@chromium.org037db002009-10-19 20:06:081792 if (node->type() == BookmarkNode::URL)
initial.commit09911bf2008-07-26 23:55:291793 (*bookmarks)++;
1794 else
1795 (*folders)++;
1796 for (int i = 0; i < node->GetChildCount(); ++i)
1797 CountBookmarks(node->GetChild(i), bookmarks, folders);
1798}
1799
munjal@chromium.orgb3c33d462009-06-26 22:29:201800void MetricsService::LogBookmarks(const BookmarkNode* node,
initial.commit09911bf2008-07-26 23:55:291801 const wchar_t* num_bookmarks_key,
1802 const wchar_t* num_folders_key) {
1803 DCHECK(node);
1804 int num_bookmarks = 0;
1805 int num_folders = 0;
1806 CountBookmarks(node, &num_bookmarks, &num_folders);
1807 num_folders--; // Don't include the root folder in the count.
1808
1809 PrefService* pref = g_browser_process->local_state();
1810 DCHECK(pref);
1811 pref->SetInteger(num_bookmarks_key, num_bookmarks);
1812 pref->SetInteger(num_folders_key, num_folders);
1813}
1814
sky@google.comd8e41ed2008-09-11 15:22:321815void MetricsService::LogBookmarks(BookmarkModel* model) {
initial.commit09911bf2008-07-26 23:55:291816 DCHECK(model);
1817 LogBookmarks(model->GetBookmarkBarNode(),
1818 prefs::kNumBookmarksOnBookmarkBar,
1819 prefs::kNumFoldersOnBookmarkBar);
1820 LogBookmarks(model->other_node(),
1821 prefs::kNumBookmarksInOtherBookmarkFolder,
1822 prefs::kNumFoldersInOtherBookmarkFolder);
1823 ScheduleNextStateSave();
1824}
1825
1826void MetricsService::LogKeywords(const TemplateURLModel* url_model) {
1827 DCHECK(url_model);
1828
1829 PrefService* pref = g_browser_process->local_state();
1830 DCHECK(pref);
1831 pref->SetInteger(prefs::kNumKeywords,
1832 static_cast<int>(url_model->GetTemplateURLs().size()));
1833 ScheduleNextStateSave();
1834}
1835
1836void MetricsService::RecordPluginChanges(PrefService* pref) {
1837 ListValue* plugins = pref->GetMutableList(prefs::kStabilityPluginStats);
1838 DCHECK(plugins);
1839
1840 for (ListValue::iterator value_iter = plugins->begin();
1841 value_iter != plugins->end(); ++value_iter) {
1842 if (!(*value_iter)->IsType(Value::TYPE_DICTIONARY)) {
jar@chromium.orga063c102010-07-22 22:20:191843 NOTREACHED();
initial.commit09911bf2008-07-26 23:55:291844 continue;
1845 }
1846
1847 DictionaryValue* plugin_dict = static_cast<DictionaryValue*>(*value_iter);
nsylvain@chromium.org8e50b602009-03-03 22:59:431848 std::wstring plugin_name;
1849 plugin_dict->GetString(prefs::kStabilityPluginName, &plugin_name);
nsylvain@chromium.org6470ee8f2009-03-03 20:46:401850 if (plugin_name.empty()) {
jar@chromium.orga063c102010-07-22 22:20:191851 NOTREACHED();
initial.commit09911bf2008-07-26 23:55:291852 continue;
1853 }
1854
nsylvain@chromium.org8e50b602009-03-03 22:59:431855 if (child_process_stats_buffer_.find(plugin_name) ==
jam@chromium.orga27a9382009-02-11 23:55:101856 child_process_stats_buffer_.end())
initial.commit09911bf2008-07-26 23:55:291857 continue;
1858
nsylvain@chromium.org8e50b602009-03-03 22:59:431859 ChildProcessStats stats = child_process_stats_buffer_[plugin_name];
initial.commit09911bf2008-07-26 23:55:291860 if (stats.process_launches) {
1861 int launches = 0;
nsylvain@chromium.org8e50b602009-03-03 22:59:431862 plugin_dict->GetInteger(prefs::kStabilityPluginLaunches, &launches);
initial.commit09911bf2008-07-26 23:55:291863 launches += stats.process_launches;
nsylvain@chromium.org8e50b602009-03-03 22:59:431864 plugin_dict->SetInteger(prefs::kStabilityPluginLaunches, launches);
initial.commit09911bf2008-07-26 23:55:291865 }
1866 if (stats.process_crashes) {
1867 int crashes = 0;
nsylvain@chromium.org8e50b602009-03-03 22:59:431868 plugin_dict->GetInteger(prefs::kStabilityPluginCrashes, &crashes);
initial.commit09911bf2008-07-26 23:55:291869 crashes += stats.process_crashes;
nsylvain@chromium.org8e50b602009-03-03 22:59:431870 plugin_dict->SetInteger(prefs::kStabilityPluginCrashes, crashes);
initial.commit09911bf2008-07-26 23:55:291871 }
1872 if (stats.instances) {
1873 int instances = 0;
nsylvain@chromium.org8e50b602009-03-03 22:59:431874 plugin_dict->GetInteger(prefs::kStabilityPluginInstances, &instances);
initial.commit09911bf2008-07-26 23:55:291875 instances += stats.instances;
nsylvain@chromium.org8e50b602009-03-03 22:59:431876 plugin_dict->SetInteger(prefs::kStabilityPluginInstances, instances);
initial.commit09911bf2008-07-26 23:55:291877 }
1878
nsylvain@chromium.org8e50b602009-03-03 22:59:431879 child_process_stats_buffer_.erase(plugin_name);
initial.commit09911bf2008-07-26 23:55:291880 }
1881
1882 // Now go through and add dictionaries for plugins that didn't already have
1883 // reports in Local State.
jam@chromium.orga27a9382009-02-11 23:55:101884 for (std::map<std::wstring, ChildProcessStats>::iterator cache_iter =
1885 child_process_stats_buffer_.begin();
1886 cache_iter != child_process_stats_buffer_.end(); ++cache_iter) {
jam@chromium.orga27a9382009-02-11 23:55:101887 ChildProcessStats stats = cache_iter->second;
gregoryd@google.com0d84c5d2009-10-09 01:10:421888
1889 // Insert only plugins information into the plugins list.
1890 if (ChildProcessInfo::PLUGIN_PROCESS != stats.process_type)
1891 continue;
1892
1893 std::wstring plugin_name = cache_iter->first;
1894
initial.commit09911bf2008-07-26 23:55:291895 DictionaryValue* plugin_dict = new DictionaryValue;
1896
nsylvain@chromium.org8e50b602009-03-03 22:59:431897 plugin_dict->SetString(prefs::kStabilityPluginName, plugin_name);
1898 plugin_dict->SetInteger(prefs::kStabilityPluginLaunches,
initial.commit09911bf2008-07-26 23:55:291899 stats.process_launches);
nsylvain@chromium.org8e50b602009-03-03 22:59:431900 plugin_dict->SetInteger(prefs::kStabilityPluginCrashes,
initial.commit09911bf2008-07-26 23:55:291901 stats.process_crashes);
nsylvain@chromium.org8e50b602009-03-03 22:59:431902 plugin_dict->SetInteger(prefs::kStabilityPluginInstances,
initial.commit09911bf2008-07-26 23:55:291903 stats.instances);
1904 plugins->Append(plugin_dict);
1905 }
jam@chromium.orga27a9382009-02-11 23:55:101906 child_process_stats_buffer_.clear();
initial.commit09911bf2008-07-26 23:55:291907}
1908
1909bool MetricsService::CanLogNotification(NotificationType type,
1910 const NotificationSource& source,
1911 const NotificationDetails& details) {
1912 // We simply don't log anything to UMA if there is a single off the record
1913 // session visible. The problem is that we always notify using the orginal
1914 // profile in order to simplify notification processing.
1915 return !BrowserList::IsOffTheRecordSessionActive();
1916}
1917
1918void MetricsService::RecordBooleanPrefValue(const wchar_t* path, bool value) {
1919 DCHECK(IsSingleThreaded());
1920
1921 PrefService* pref = g_browser_process->local_state();
1922 DCHECK(pref);
1923
1924 pref->SetBoolean(path, value);
1925 RecordCurrentState(pref);
1926}
1927
1928void MetricsService::RecordCurrentState(PrefService* pref) {
robertshield@google.com0bb1a622009-03-04 03:22:321929 pref->SetInt64(prefs::kStabilityLastTimestampSec, Time::Now().ToTimeT());
initial.commit09911bf2008-07-26 23:55:291930
1931 RecordPluginChanges(pref);
1932}
1933
initial.commit09911bf2008-07-26 23:55:291934static bool IsSingleThreaded() {
paul@chromium.orgdc6f4962009-02-13 01:25:501935 static PlatformThreadId thread_id = 0;
initial.commit09911bf2008-07-26 23:55:291936 if (!thread_id)
paul@chromium.orgdc6f4962009-02-13 01:25:501937 thread_id = PlatformThread::CurrentId();
1938 return PlatformThread::CurrentId() == thread_id;
initial.commit09911bf2008-07-26 23:55:291939}
rvargas@google.com5ccaa412009-11-13 22:00:161940
1941#if defined(OS_CHROMEOS)
zelidrag@chromium.org85ed9d42010-06-08 22:37:441942// static
1943std::string MetricsService::GetHardwareClass() {
1944 DCHECK(!ChromeThread::CurrentlyOn(ChromeThread::UI));
1945 std::string hardware_class;
1946 FilePath tool(kHardwareClassTool);
1947 CommandLine command(tool);
1948 if (base::GetAppOutput(command, &hardware_class)) {
1949 TrimWhitespaceASCII(hardware_class, TRIM_ALL, &hardware_class);
1950 } else {
1951 hardware_class = kUnknownHardwareClass;
1952 }
1953 return hardware_class;
1954}
1955
sky@chromium.org29cf16772010-04-21 15:13:471956void MetricsService::StartExternalMetrics() {
rvargas@google.com5ccaa412009-11-13 22:00:161957 external_metrics_ = new chromeos::ExternalMetrics;
sky@chromium.org29cf16772010-04-21 15:13:471958 external_metrics_->Start();
rvargas@google.com5ccaa412009-11-13 22:00:161959}
1960#endif