blob: b11a44b1fad332fce1948d47ea3854adb8b0073d [file] [log] [blame]
[email protected]2e4cd1a2012-01-12 08:51:031// Copyright (c) 2012 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
initial.commit09911bf2008-07-26 23:55:295//------------------------------------------------------------------------------
6// Description of the life cycle of a instance of MetricsService.
7//
8// OVERVIEW
9//
10// A MetricsService instance is typically created at application startup. It
11// is the central controller for the acquisition of log data, and the automatic
12// transmission of that log data to an external server. Its major job is to
13// manage logs, grouping them for transmission, and transmitting them. As part
14// of its grouping, MS finalizes logs by including some just-in-time gathered
15// memory statistics, snapshotting the current stats of numerous histograms,
16// closing the logs, translating to XML text, and compressing the results for
17// transmission. Transmission includes submitting a compressed log as data in a
[email protected]281d2882009-01-20 20:32:4218// URL-post, and retransmitting (or retaining at process termination) if the
initial.commit09911bf2008-07-26 23:55:2919// attempted transmission failed. Retention across process terminations is done
[email protected]46f89e142010-07-19 08:00:4220// using the the PrefServices facilities. The retained logs (the ones that never
21// got transmitted) are compressed and base64-encoded before being persisted.
initial.commit09911bf2008-07-26 23:55:2922//
[email protected]281d2882009-01-20 20:32:4223// Logs fall into one of two categories: "initial logs," and "ongoing logs."
24// There is at most one initial log sent for each complete run of the chromium
initial.commit09911bf2008-07-26 23:55:2925// product (from startup, to browser shutdown). An initial log is generally
26// transmitted some short time (1 minute?) after startup, and includes stats
27// such as recent crash info, the number and types of plugins, etc. The
[email protected]281d2882009-01-20 20:32:4228// external server's response to the initial log conceptually tells this MS if
29// it should continue transmitting logs (during this session). The server
30// response can actually be much more detailed, and always includes (at a
31// minimum) how often additional ongoing logs should be sent.
initial.commit09911bf2008-07-26 23:55:2932//
33// After the above initial log, a series of ongoing logs will be transmitted.
34// The first ongoing log actually begins to accumulate information stating when
35// the MS was first constructed. Note that even though the initial log is
36// commonly sent a full minute after startup, the initial log does not include
37// much in the way of user stats. The most common interlog period (delay)
[email protected]0b33f80b2008-12-17 21:34:3638// is 20 minutes. That time period starts when the first user action causes a
initial.commit09911bf2008-07-26 23:55:2939// logging event. This means that if there is no user action, there may be long
[email protected]281d2882009-01-20 20:32:4240// periods without any (ongoing) log transmissions. Ongoing logs typically
initial.commit09911bf2008-07-26 23:55:2941// contain very detailed records of user activities (ex: opened tab, closed
42// tab, fetched URL, maximized window, etc.) In addition, just before an
43// ongoing log is closed out, a call is made to gather memory statistics. Those
44// memory statistics are deposited into a histogram, and the log finalization
45// code is then called. In the finalization, a call to a Histogram server
46// acquires a list of all local histograms that have been flagged for upload
[email protected]281d2882009-01-20 20:32:4247// to the UMA server. The finalization also acquires a the most recent number
48// of page loads, along with any counts of renderer or plugin crashes.
initial.commit09911bf2008-07-26 23:55:2949//
50// When the browser shuts down, there will typically be a fragment of an ongoing
51// log that has not yet been transmitted. At shutdown time, that fragment
[email protected]cac267c2011-09-29 15:18:1052// is closed (including snapshotting histograms), and persisted, for
initial.commit09911bf2008-07-26 23:55:2953// potential transmission during a future run of the product.
54//
55// There are two slightly abnormal shutdown conditions. There is a
56// "disconnected scenario," and a "really fast startup and shutdown" scenario.
57// In the "never connected" situation, the user has (during the running of the
58// process) never established an internet connection. As a result, attempts to
59// transmit the initial log have failed, and a lot(?) of data has accumulated in
60// the ongoing log (which didn't yet get closed, because there was never even a
61// contemplation of sending it). There is also a kindred "lost connection"
62// situation, where a loss of connection prevented an ongoing log from being
63// transmitted, and a (still open) log was stuck accumulating a lot(?) of data,
64// while the earlier log retried its transmission. In both of these
65// disconnected situations, two logs need to be, and are, persistently stored
66// for future transmission.
67//
68// The other unusual shutdown condition, termed "really fast startup and
69// shutdown," involves the deliberate user termination of the process before
70// the initial log is even formed or transmitted. In that situation, no logging
71// is done, but the historical crash statistics remain (unlogged) for inclusion
72// in a future run's initial log. (i.e., we don't lose crash stats).
73//
74// With the above overview, we can now describe the state machine's various
75// stats, based on the State enum specified in the state_ member. Those states
76// are:
77//
78// INITIALIZED, // Constructor was called.
[email protected]85ed9d42010-06-08 22:37:4479// INIT_TASK_SCHEDULED, // Waiting for deferred init tasks to complete.
80// INIT_TASK_DONE, // Waiting for timer to send initial log.
initial.commit09911bf2008-07-26 23:55:2981// INITIAL_LOG_READY, // Initial log generated, and waiting for reply.
initial.commit09911bf2008-07-26 23:55:2982// SENDING_OLD_LOGS, // Sending unsent logs from previous session.
83// SENDING_CURRENT_LOGS, // Sending standard current logs as they accrue.
84//
85// In more detail, we have:
86//
87// INITIALIZED, // Constructor was called.
88// The MS has been constructed, but has taken no actions to compose the
89// initial log.
90//
[email protected]85ed9d42010-06-08 22:37:4491// INIT_TASK_SCHEDULED, // Waiting for deferred init tasks to complete.
initial.commit09911bf2008-07-26 23:55:2992// Typically about 30 seconds after startup, a task is sent to a second thread
[email protected]85ed9d42010-06-08 22:37:4493// (the file thread) to perform deferred (lower priority and slower)
94// initialization steps such as getting the list of plugins. That task will
95// (when complete) make an async callback (via a Task) to indicate the
96// completion.
initial.commit09911bf2008-07-26 23:55:2997//
[email protected]85ed9d42010-06-08 22:37:4498// INIT_TASK_DONE, // Waiting for timer to send initial log.
initial.commit09911bf2008-07-26 23:55:2999// The callback has arrived, and it is now possible for an initial log to be
100// created. This callback typically arrives back less than one second after
[email protected]85ed9d42010-06-08 22:37:44101// the deferred init task is dispatched.
initial.commit09911bf2008-07-26 23:55:29102//
103// INITIAL_LOG_READY, // Initial log generated, and waiting for reply.
104// This state is entered only after an initial log has been composed, and
105// prepared for transmission. It is also the case that any previously unsent
106// logs have been loaded into instance variables for possible transmission.
107//
initial.commit09911bf2008-07-26 23:55:29108// SENDING_OLD_LOGS, // Sending unsent logs from previous session.
[email protected]cac267c2011-09-29 15:18:10109// This state indicates that the initial log for this session has been
110// successfully sent and it is now time to send any logs that were
111// saved from previous sessions. All such logs will be transmitted before
112// exiting this state, and proceeding with ongoing logs from the current session
113// (see next state).
initial.commit09911bf2008-07-26 23:55:29114//
115// SENDING_CURRENT_LOGS, // Sending standard current logs as they accrue.
[email protected]0b33f80b2008-12-17 21:34:36116// Current logs are being accumulated. Typically every 20 minutes a log is
initial.commit09911bf2008-07-26 23:55:29117// closed and finalized for transmission, at the same time as a new log is
118// started.
119//
120// The progression through the above states is simple, and sequential, in the
121// most common use cases. States proceed from INITIAL to SENDING_CURRENT_LOGS,
122// and remain in the latter until shutdown.
123//
124// The one unusual case is when the user asks that we stop logging. When that
[email protected]cac267c2011-09-29 15:18:10125// happens, any staged (transmission in progress) log is persisted, and any log
126// log that is currently accumulating is also finalized and persisted. We then
127// regress back to the SEND_OLD_LOGS state in case the user enables log
128// recording again during this session. This way anything we have persisted
129// will be sent automatically if/when we progress back to SENDING_CURRENT_LOG
130// state.
initial.commit09911bf2008-07-26 23:55:29131//
[email protected]cac267c2011-09-29 15:18:10132// Also note that whenever we successfully send an old log, we mirror the list
133// of logs into the PrefService. This ensures that IF we crash, we won't start
134// up and retransmit our old logs again.
initial.commit09911bf2008-07-26 23:55:29135//
136// Due to race conditions, it is always possible that a log file could be sent
137// twice. For example, if a log file is sent, but not yet acknowledged by
138// the external server, and the user shuts down, then a copy of the log may be
139// saved for re-transmission. These duplicates could be filtered out server
[email protected]281d2882009-01-20 20:32:42140// side, but are not expected to be a significant problem.
initial.commit09911bf2008-07-26 23:55:29141//
142//
143//------------------------------------------------------------------------------
144
[email protected]40bcc302009-03-02 20:50:39145#include "chrome/browser/metrics/metrics_service.h"
146
[email protected]7f7f1962011-04-20 15:58:16147#include "base/bind.h"
148#include "base/callback.h"
[email protected]5d91c9e2010-07-28 17:25:28149#include "base/command_line.h"
[email protected]46f89e142010-07-19 08:00:42150#include "base/md5.h"
[email protected]835d7c82010-10-14 04:38:38151#include "base/metrics/histogram.h"
[email protected]528c56d2010-07-30 19:28:44152#include "base/string_number_conversions.h"
[email protected]ce072a72010-12-31 20:02:16153#include "base/threading/platform_thread.h"
[email protected]b3841c502011-03-09 01:21:31154#include "base/threading/thread.h"
[email protected]440b37b22010-08-30 05:31:40155#include "base/utf_string_conversions.h"
[email protected]679082052010-07-21 21:30:13156#include "base/values.h"
[email protected]d8e41ed2008-09-11 15:22:32157#include "chrome/browser/bookmarks/bookmark_model.h"
initial.commit09911bf2008-07-26 23:55:29158#include "chrome/browser/browser_process.h"
[email protected]6f371442011-11-09 06:45:46159#include "chrome/browser/extensions/extension_service.h"
160#include "chrome/browser/extensions/process_map.h"
[email protected]84c988a2011-04-19 17:56:33161#include "chrome/browser/memory_details.h"
[email protected]7c927b62010-02-24 09:54:13162#include "chrome/browser/metrics/histogram_synchronizer.h"
[email protected]679082052010-07-21 21:30:13163#include "chrome/browser/metrics/metrics_log.h"
[email protected]cac267c2011-09-29 15:18:10164#include "chrome/browser/metrics/metrics_log_serializer.h"
[email protected]7f7f1962011-04-20 15:58:16165#include "chrome/browser/metrics/metrics_reporting_scheduler.h"
[email protected]adbb3762012-03-09 22:20:08166#include "chrome/browser/net/http_pipelining_compatibility_client.h"
[email protected]d67d1052011-06-09 05:11:41167#include "chrome/browser/net/network_stats.h"
[email protected]37858e52010-08-26 00:22:02168#include "chrome/browser/prefs/pref_service.h"
[email protected]f8628c22011-04-05 12:10:18169#include "chrome/browser/prefs/scoped_user_pref_update.h"
[email protected]8ecad5e2010-12-02 21:18:33170#include "chrome/browser/profiles/profile.h"
[email protected]8e5c89a2011-06-07 18:13:33171#include "chrome/browser/search_engines/template_url_service.h"
[email protected]71b73f02011-04-06 15:57:29172#include "chrome/browser/ui/browser_list.h"
[email protected]157d5472009-11-05 22:31:03173#include "chrome/common/child_process_logging.h"
[email protected]432115822011-07-10 15:52:27174#include "chrome/common/chrome_notification_types.h"
[email protected]92745242009-06-12 16:52:21175#include "chrome/common/chrome_switches.h"
[email protected]3eb0d8f72010-12-15 23:38:25176#include "chrome/common/guid.h"
[email protected]2e4cd1a2012-01-12 08:51:03177#include "chrome/common/metrics/metrics_log_manager.h"
initial.commit09911bf2008-07-26 23:55:29178#include "chrome/common/pref_names.h"
[email protected]e09ba552009-02-05 03:26:29179#include "chrome/common/render_messages.h"
[email protected]4967f792012-01-20 22:14:40180#include "content/public/browser/child_process_data.h"
[email protected]09d31d52012-03-11 22:30:27181#include "content/public/browser/load_notification_details.h"
[email protected]ad50def52011-10-19 23:17:07182#include "content/public/browser/notification_service.h"
[email protected]3a5180ae2011-12-21 02:39:38183#include "content/public/browser/plugin_service.h"
[email protected]f3b1a082011-11-18 00:34:30184#include "content/public/browser/render_process_host.h"
[email protected]36aea2702011-10-26 01:12:22185#include "content/public/common/url_fetcher.h"
[email protected]fe58acc22012-02-29 01:29:58186#include "net/base/load_flags.h"
[email protected]91d9f3d2011-08-14 05:24:44187#include "webkit/plugins/webplugininfo.h"
initial.commit09911bf2008-07-26 23:55:29188
[email protected]e06131d2010-02-10 18:40:33189// TODO(port): port browser_distribution.h.
190#if !defined(OS_POSIX)
[email protected]79bf0b72009-04-27 21:30:55191#include "chrome/installer/util/browser_distribution.h"
[email protected]dc6f4962009-02-13 01:25:50192#endif
193
[email protected]5ccaa412009-11-13 22:00:16194#if defined(OS_CHROMEOS)
[email protected]db342d52010-08-09 21:19:37195#include "chrome/browser/chromeos/cros/cros_library.h"
[email protected]5ccaa412009-11-13 22:00:16196#include "chrome/browser/chromeos/external_metrics.h"
[email protected]d43970a72011-07-10 06:24:52197#include "chrome/browser/chromeos/system/statistics_provider.h"
[email protected]5ccaa412009-11-13 22:00:16198#endif
199
[email protected]e1acf6f2008-10-27 20:43:33200using base::Time;
[email protected]631bb742011-11-02 11:29:39201using content::BrowserThread;
[email protected]4967f792012-01-20 22:14:40202using content::ChildProcessData;
[email protected]09d31d52012-03-11 22:30:27203using content::LoadNotificationDetails;
[email protected]3a5180ae2011-12-21 02:39:38204using content::PluginService;
[email protected]e1acf6f2008-10-27 20:43:33205
[email protected]fe58acc22012-02-29 01:29:58206namespace {
[email protected]b2a4812d2012-02-28 05:31:31207
[email protected]fe58acc22012-02-29 01:29:58208// Check to see that we're being called on only one thread.
209bool IsSingleThreaded() {
210 static base::PlatformThreadId thread_id = 0;
211 if (!thread_id)
212 thread_id = base::PlatformThread::CurrentId();
213 return base::PlatformThread::CurrentId() == thread_id;
214}
215
216const char kMetricsTypeXml[] = "application/vnd.mozilla.metrics.bz2";
217const char kMetricsTypeProto[] = "application/vnd.chrome.uma";
218
219const char kServerUrlXml[] =
220 "https://clients4.google.com/firefox/metrics/collect";
221const char kServerUrlProto[] = "https://clients4.google.com/uma/v2";
initial.commit09911bf2008-07-26 23:55:29222
[email protected]7f7f1962011-04-20 15:58:16223// The delay, in seconds, after starting recording before doing expensive
224// initialization work.
[email protected]fe58acc22012-02-29 01:29:58225const int kInitializationDelaySeconds = 30;
[email protected]252873ef2008-08-04 21:59:45226
[email protected]c9a3ef82009-05-28 22:02:46227// This specifies the amount of time to wait for all renderers to send their
228// data.
[email protected]fe58acc22012-02-29 01:29:58229const int kMaxHistogramGatheringWaitDuration = 60000; // 60 seconds.
[email protected]c9a3ef82009-05-28 22:02:46230
[email protected]54702c92011-04-15 15:06:43231// The maximum number of events in a log uploaded to the UMA server.
[email protected]fe58acc22012-02-29 01:29:58232const int kEventLimit = 2400;
[email protected]68475e602008-08-22 03:21:15233
234// If an upload fails, and the transmission was over this byte count, then we
235// will discard the log, and not try to retransmit it. We also don't persist
236// the log to the prefs for transmission during the next chrome session if this
237// limit is exceeded.
[email protected]fe58acc22012-02-29 01:29:58238const size_t kUploadLogAvoidRetransmitSize = 50000;
initial.commit09911bf2008-07-26 23:55:29239
[email protected]fc4252a72012-01-12 21:58:47240// Interval, in minutes, between state saves.
[email protected]fe58acc22012-02-29 01:29:58241const int kSaveStateIntervalMinutes = 5;
242
243}
initial.commit09911bf2008-07-26 23:55:29244
[email protected]c0c55e92011-09-10 18:47:30245// static
246MetricsService::ShutdownCleanliness MetricsService::clean_shutdown_status_ =
247 MetricsService::CLEANLY_SHUTDOWN;
248
[email protected]679082052010-07-21 21:30:13249// This is used to quickly log stats from child process related notifications in
250// MetricsService::child_stats_buffer_. The buffer's contents are transferred
251// out when Local State is periodically saved. The information is then
252// reported to the UMA server on next launch.
253struct MetricsService::ChildProcessStats {
254 public:
[email protected]bd5d6cf2011-12-01 00:39:12255 explicit ChildProcessStats(content::ProcessType type)
[email protected]679082052010-07-21 21:30:13256 : process_launches(0),
257 process_crashes(0),
258 instances(0),
259 process_type(type) {}
260
261 // This constructor is only used by the map to return some default value for
262 // an index for which no value has been assigned.
263 ChildProcessStats()
264 : process_launches(0),
[email protected]d88bf0a2011-08-30 23:55:57265 process_crashes(0),
266 instances(0),
[email protected]bd5d6cf2011-12-01 00:39:12267 process_type(content::PROCESS_TYPE_UNKNOWN) {}
[email protected]679082052010-07-21 21:30:13268
269 // The number of times that the given child process has been launched
270 int process_launches;
271
272 // The number of times that the given child process has crashed
273 int process_crashes;
274
275 // The number of instances of this child process that have been created.
276 // An instance is a DOM object rendered by this child process during a page
277 // load.
278 int instances;
279
[email protected]bd5d6cf2011-12-01 00:39:12280 content::ProcessType process_type;
[email protected]679082052010-07-21 21:30:13281};
initial.commit09911bf2008-07-26 23:55:29282
[email protected]84c988a2011-04-19 17:56:33283// Handles asynchronous fetching of memory details.
284// Will run the provided task after finished.
285class MetricsMemoryDetails : public MemoryDetails {
286 public:
[email protected]2226c222011-11-22 00:08:40287 explicit MetricsMemoryDetails(const base::Closure& callback)
288 : callback_(callback) {}
[email protected]84c988a2011-04-19 17:56:33289
290 virtual void OnDetailsAvailable() {
[email protected]2226c222011-11-22 00:08:40291 MessageLoop::current()->PostTask(FROM_HERE, callback_);
[email protected]84c988a2011-04-19 17:56:33292 }
293
294 private:
295 ~MetricsMemoryDetails() {}
296
[email protected]2226c222011-11-22 00:08:40297 base::Closure callback_;
[email protected]84c988a2011-04-19 17:56:33298 DISALLOW_COPY_AND_ASSIGN(MetricsMemoryDetails);
299};
300
initial.commit09911bf2008-07-26 23:55:29301// static
302void MetricsService::RegisterPrefs(PrefService* local_state) {
303 DCHECK(IsSingleThreaded());
[email protected]20ce516d2010-06-18 02:20:04304 local_state->RegisterStringPref(prefs::kMetricsClientID, "");
[email protected]0bb1a622009-03-04 03:22:32305 local_state->RegisterInt64Pref(prefs::kMetricsClientIDTimestamp, 0);
306 local_state->RegisterInt64Pref(prefs::kStabilityLaunchTimeSec, 0);
307 local_state->RegisterInt64Pref(prefs::kStabilityLastTimestampSec, 0);
[email protected]20ce516d2010-06-18 02:20:04308 local_state->RegisterStringPref(prefs::kStabilityStatsVersion, "");
[email protected]225c50842010-01-19 21:19:13309 local_state->RegisterInt64Pref(prefs::kStabilityStatsBuildTime, 0);
initial.commit09911bf2008-07-26 23:55:29310 local_state->RegisterBooleanPref(prefs::kStabilityExitedCleanly, true);
311 local_state->RegisterBooleanPref(prefs::kStabilitySessionEndCompleted, true);
312 local_state->RegisterIntegerPref(prefs::kMetricsSessionID, -1);
313 local_state->RegisterIntegerPref(prefs::kStabilityLaunchCount, 0);
314 local_state->RegisterIntegerPref(prefs::kStabilityCrashCount, 0);
315 local_state->RegisterIntegerPref(prefs::kStabilityIncompleteSessionEndCount,
316 0);
317 local_state->RegisterIntegerPref(prefs::kStabilityPageLoadCount, 0);
initial.commit09911bf2008-07-26 23:55:29318 local_state->RegisterIntegerPref(prefs::kStabilityRendererCrashCount, 0);
[email protected]1f085622009-12-04 05:33:45319 local_state->RegisterIntegerPref(prefs::kStabilityExtensionRendererCrashCount,
320 0);
initial.commit09911bf2008-07-26 23:55:29321 local_state->RegisterIntegerPref(prefs::kStabilityRendererHangCount, 0);
[email protected]1f085622009-12-04 05:33:45322 local_state->RegisterIntegerPref(prefs::kStabilityChildProcessCrashCount, 0);
[email protected]e73c01972008-08-13 00:18:24323 local_state->RegisterIntegerPref(prefs::kStabilityBreakpadRegistrationFail,
324 0);
325 local_state->RegisterIntegerPref(prefs::kStabilityBreakpadRegistrationSuccess,
326 0);
327 local_state->RegisterIntegerPref(prefs::kStabilityDebuggerPresent, 0);
328 local_state->RegisterIntegerPref(prefs::kStabilityDebuggerNotPresent, 0);
[email protected]c1834a92011-01-21 18:21:03329#if defined(OS_CHROMEOS)
330 local_state->RegisterIntegerPref(prefs::kStabilityOtherUserCrashCount, 0);
331 local_state->RegisterIntegerPref(prefs::kStabilityKernelCrashCount, 0);
332 local_state->RegisterIntegerPref(prefs::kStabilitySystemUncleanShutdownCount,
333 0);
334#endif // OS_CHROMEOS
[email protected]e73c01972008-08-13 00:18:24335
initial.commit09911bf2008-07-26 23:55:29336 local_state->RegisterDictionaryPref(prefs::kProfileMetrics);
337 local_state->RegisterIntegerPref(prefs::kNumBookmarksOnBookmarkBar, 0);
338 local_state->RegisterIntegerPref(prefs::kNumFoldersOnBookmarkBar, 0);
339 local_state->RegisterIntegerPref(prefs::kNumBookmarksInOtherBookmarkFolder,
340 0);
341 local_state->RegisterIntegerPref(prefs::kNumFoldersInOtherBookmarkFolder, 0);
342 local_state->RegisterIntegerPref(prefs::kNumKeywords, 0);
[email protected]fe58acc22012-02-29 01:29:58343 local_state->RegisterListPref(prefs::kMetricsInitialLogsXml);
344 local_state->RegisterListPref(prefs::kMetricsOngoingLogsXml);
345 local_state->RegisterListPref(prefs::kMetricsInitialLogsProto);
346 local_state->RegisterListPref(prefs::kMetricsOngoingLogsProto);
[email protected]0bb1a622009-03-04 03:22:32347
348 local_state->RegisterInt64Pref(prefs::kUninstallMetricsPageLoadCount, 0);
349 local_state->RegisterInt64Pref(prefs::kUninstallLaunchCount, 0);
[email protected]6b5f21d2009-04-13 17:01:35350 local_state->RegisterInt64Pref(prefs::kUninstallMetricsInstallDate, 0);
[email protected]0bb1a622009-03-04 03:22:32351 local_state->RegisterInt64Pref(prefs::kUninstallMetricsUptimeSec, 0);
352 local_state->RegisterInt64Pref(prefs::kUninstallLastLaunchTimeSec, 0);
353 local_state->RegisterInt64Pref(prefs::kUninstallLastObservedRunTimeSec, 0);
initial.commit09911bf2008-07-26 23:55:29354}
355
[email protected]541f77922009-02-23 21:14:38356// static
357void MetricsService::DiscardOldStabilityStats(PrefService* local_state) {
358 local_state->SetBoolean(prefs::kStabilityExitedCleanly, true);
[email protected]c9abf242009-07-18 06:00:38359 local_state->SetBoolean(prefs::kStabilitySessionEndCompleted, true);
[email protected]541f77922009-02-23 21:14:38360
361 local_state->SetInteger(prefs::kStabilityIncompleteSessionEndCount, 0);
362 local_state->SetInteger(prefs::kStabilityBreakpadRegistrationSuccess, 0);
363 local_state->SetInteger(prefs::kStabilityBreakpadRegistrationFail, 0);
364 local_state->SetInteger(prefs::kStabilityDebuggerPresent, 0);
365 local_state->SetInteger(prefs::kStabilityDebuggerNotPresent, 0);
366
367 local_state->SetInteger(prefs::kStabilityLaunchCount, 0);
368 local_state->SetInteger(prefs::kStabilityCrashCount, 0);
369
370 local_state->SetInteger(prefs::kStabilityPageLoadCount, 0);
371 local_state->SetInteger(prefs::kStabilityRendererCrashCount, 0);
372 local_state->SetInteger(prefs::kStabilityRendererHangCount, 0);
373
[email protected]9165f742010-03-10 22:55:01374 local_state->SetInt64(prefs::kStabilityLaunchTimeSec, 0);
375 local_state->SetInt64(prefs::kStabilityLastTimestampSec, 0);
[email protected]541f77922009-02-23 21:14:38376
377 local_state->ClearPref(prefs::kStabilityPluginStats);
[email protected]ae155cb92009-06-19 06:10:37378
[email protected]fe58acc22012-02-29 01:29:58379 local_state->ClearPref(prefs::kMetricsInitialLogsXml);
380 local_state->ClearPref(prefs::kMetricsOngoingLogsXml);
381 local_state->ClearPref(prefs::kMetricsInitialLogsProto);
382 local_state->ClearPref(prefs::kMetricsOngoingLogsProto);
[email protected]541f77922009-02-23 21:14:38383}
384
initial.commit09911bf2008-07-26 23:55:29385MetricsService::MetricsService()
[email protected]d01b8732008-10-16 02:18:07386 : recording_active_(false),
387 reporting_active_(false),
[email protected]d01b8732008-10-16 02:18:07388 state_(INITIALIZED),
[email protected]d67d1052011-06-09 05:11:41389 io_thread_(NULL),
[email protected]d01b8732008-10-16 02:18:07390 idle_since_last_transmission_(false),
initial.commit09911bf2008-07-26 23:55:29391 next_window_id_(0),
[email protected]c94d7382012-02-28 08:43:40392 ALLOW_THIS_IN_INITIALIZER_LIST(self_ptr_factory_(this)),
[email protected]40bcc302009-03-02 20:50:39393 ALLOW_THIS_IN_INITIALIZER_LIST(state_saver_factory_(this)),
[email protected]7f7f1962011-04-20 15:58:16394 waiting_for_asynchronus_reporting_step_(false) {
initial.commit09911bf2008-07-26 23:55:29395 DCHECK(IsSingleThreaded());
396 InitializeMetricsState();
[email protected]7f7f1962011-04-20 15:58:16397
398 base::Closure callback = base::Bind(&MetricsService::StartScheduledUpload,
[email protected]c94d7382012-02-28 08:43:40399 self_ptr_factory_.GetWeakPtr());
[email protected]7f7f1962011-04-20 15:58:16400 scheduler_.reset(new MetricsReportingScheduler(callback));
[email protected]cac267c2011-09-29 15:18:10401 log_manager_.set_log_serializer(new MetricsLogSerializer());
402 log_manager_.set_max_ongoing_log_store_size(kUploadLogAvoidRetransmitSize);
initial.commit09911bf2008-07-26 23:55:29403}
404
405MetricsService::~MetricsService() {
406 SetRecording(false);
407}
408
[email protected]d01b8732008-10-16 02:18:07409void MetricsService::Start() {
[email protected]b1c8dc02011-04-13 18:32:04410 HandleIdleSinceLastTransmission(false);
[email protected]d01b8732008-10-16 02:18:07411 SetRecording(true);
412 SetReporting(true);
413}
414
415void MetricsService::StartRecordingOnly() {
416 SetRecording(true);
417 SetReporting(false);
418}
419
420void MetricsService::Stop() {
[email protected]b1c8dc02011-04-13 18:32:04421 HandleIdleSinceLastTransmission(false);
[email protected]d01b8732008-10-16 02:18:07422 SetReporting(false);
423 SetRecording(false);
424}
425
[email protected]edafd4c2011-05-10 17:18:53426std::string MetricsService::GetClientId() {
427 return client_id_;
428}
429
[email protected]5cbeeef72012-02-08 02:05:18430void MetricsService::ForceClientIdCreation() {
431 if (!client_id_.empty())
432 return;
433 PrefService* pref = g_browser_process->local_state();
434 client_id_ = pref->GetString(prefs::kMetricsClientID);
435 if (!client_id_.empty())
436 return;
437
438 client_id_ = GenerateClientID();
439 pref->SetString(prefs::kMetricsClientID, client_id_);
440
441 // Might as well make a note of how long this ID has existed
442 pref->SetString(prefs::kMetricsClientIDTimestamp,
443 base::Int64ToString(Time::Now().ToTimeT()));
444}
445
initial.commit09911bf2008-07-26 23:55:29446void MetricsService::SetRecording(bool enabled) {
447 DCHECK(IsSingleThreaded());
448
[email protected]d01b8732008-10-16 02:18:07449 if (enabled == recording_active_)
initial.commit09911bf2008-07-26 23:55:29450 return;
451
452 if (enabled) {
[email protected]5cbeeef72012-02-08 02:05:18453 ForceClientIdCreation();
[email protected]157d5472009-11-05 22:31:03454 child_process_logging::SetClientId(client_id_);
initial.commit09911bf2008-07-26 23:55:29455 StartRecording();
[email protected]005ef3e2009-05-22 20:55:46456
[email protected]3ffd3ae2011-03-17 22:17:52457 SetUpNotifications(&registrar_, this);
initial.commit09911bf2008-07-26 23:55:29458 } else {
[email protected]005ef3e2009-05-22 20:55:46459 registrar_.RemoveAll();
[email protected]cac267c2011-09-29 15:18:10460 PushPendingLogsToPersistentStorage();
461 DCHECK(!log_manager_.has_staged_log());
462 if (state_ > INITIAL_LOG_READY && log_manager_.has_unsent_logs())
463 state_ = SENDING_OLD_LOGS;
initial.commit09911bf2008-07-26 23:55:29464 }
[email protected]d01b8732008-10-16 02:18:07465 recording_active_ = enabled;
initial.commit09911bf2008-07-26 23:55:29466}
467
[email protected]d01b8732008-10-16 02:18:07468bool MetricsService::recording_active() const {
initial.commit09911bf2008-07-26 23:55:29469 DCHECK(IsSingleThreaded());
[email protected]d01b8732008-10-16 02:18:07470 return recording_active_;
initial.commit09911bf2008-07-26 23:55:29471}
472
[email protected]d01b8732008-10-16 02:18:07473void MetricsService::SetReporting(bool enable) {
474 if (reporting_active_ != enable) {
475 reporting_active_ = enable;
476 if (reporting_active_)
[email protected]7f7f1962011-04-20 15:58:16477 StartSchedulerIfNecessary();
initial.commit09911bf2008-07-26 23:55:29478 }
[email protected]d01b8732008-10-16 02:18:07479}
480
481bool MetricsService::reporting_active() const {
482 DCHECK(IsSingleThreaded());
483 return reporting_active_;
initial.commit09911bf2008-07-26 23:55:29484}
485
[email protected]87ef9ea2011-02-26 03:15:15486// static
[email protected]6c2381d2011-10-19 02:52:53487void MetricsService::SetUpNotifications(
488 content::NotificationRegistrar* registrar,
489 content::NotificationObserver* observer) {
490 registrar->Add(observer, chrome::NOTIFICATION_BROWSER_OPENED,
[email protected]ad50def52011-10-19 23:17:07491 content::NotificationService::AllBrowserContextsAndSources());
[email protected]6c2381d2011-10-19 02:52:53492 registrar->Add(observer, chrome::NOTIFICATION_BROWSER_CLOSED,
[email protected]ad50def52011-10-19 23:17:07493 content::NotificationService::AllSources());
[email protected]6c2381d2011-10-19 02:52:53494 registrar->Add(observer, content::NOTIFICATION_USER_ACTION,
[email protected]ad50def52011-10-19 23:17:07495 content::NotificationService::AllSources());
[email protected]6c2381d2011-10-19 02:52:53496 registrar->Add(observer, content::NOTIFICATION_TAB_PARENTED,
[email protected]ad50def52011-10-19 23:17:07497 content::NotificationService::AllSources());
[email protected]6c2381d2011-10-19 02:52:53498 registrar->Add(observer, content::NOTIFICATION_TAB_CLOSING,
[email protected]ad50def52011-10-19 23:17:07499 content::NotificationService::AllSources());
[email protected]6c2381d2011-10-19 02:52:53500 registrar->Add(observer, content::NOTIFICATION_LOAD_START,
[email protected]ad50def52011-10-19 23:17:07501 content::NotificationService::AllSources());
[email protected]6c2381d2011-10-19 02:52:53502 registrar->Add(observer, content::NOTIFICATION_LOAD_STOP,
[email protected]ad50def52011-10-19 23:17:07503 content::NotificationService::AllSources());
[email protected]6c2381d2011-10-19 02:52:53504 registrar->Add(observer, content::NOTIFICATION_RENDERER_PROCESS_CLOSED,
[email protected]ad50def52011-10-19 23:17:07505 content::NotificationService::AllSources());
[email protected]6c2381d2011-10-19 02:52:53506 registrar->Add(observer, content::NOTIFICATION_RENDERER_PROCESS_HANG,
[email protected]ad50def52011-10-19 23:17:07507 content::NotificationService::AllSources());
[email protected]6c2381d2011-10-19 02:52:53508 registrar->Add(observer, content::NOTIFICATION_CHILD_PROCESS_HOST_CONNECTED,
[email protected]ad50def52011-10-19 23:17:07509 content::NotificationService::AllSources());
[email protected]6c2381d2011-10-19 02:52:53510 registrar->Add(observer, content::NOTIFICATION_CHILD_INSTANCE_CREATED,
[email protected]ad50def52011-10-19 23:17:07511 content::NotificationService::AllSources());
[email protected]6c2381d2011-10-19 02:52:53512 registrar->Add(observer, content::NOTIFICATION_CHILD_PROCESS_CRASHED,
[email protected]ad50def52011-10-19 23:17:07513 content::NotificationService::AllSources());
[email protected]6c2381d2011-10-19 02:52:53514 registrar->Add(observer, chrome::NOTIFICATION_TEMPLATE_URL_SERVICE_LOADED,
[email protected]ad50def52011-10-19 23:17:07515 content::NotificationService::AllSources());
[email protected]6c2381d2011-10-19 02:52:53516 registrar->Add(observer, chrome::NOTIFICATION_OMNIBOX_OPENED_URL,
[email protected]ad50def52011-10-19 23:17:07517 content::NotificationService::AllSources());
[email protected]6c2381d2011-10-19 02:52:53518 registrar->Add(observer, chrome::NOTIFICATION_BOOKMARK_MODEL_LOADED,
[email protected]ad50def52011-10-19 23:17:07519 content::NotificationService::AllBrowserContextsAndSources());
[email protected]87ef9ea2011-02-26 03:15:15520}
521
[email protected]432115822011-07-10 15:52:27522void MetricsService::Observe(int type,
[email protected]6c2381d2011-10-19 02:52:53523 const content::NotificationSource& source,
524 const content::NotificationDetails& details) {
[email protected]cac267c2011-09-29 15:18:10525 DCHECK(log_manager_.current_log());
initial.commit09911bf2008-07-26 23:55:29526 DCHECK(IsSingleThreaded());
527
528 if (!CanLogNotification(type, source, details))
529 return;
530
[email protected]432115822011-07-10 15:52:27531 switch (type) {
532 case content::NOTIFICATION_USER_ACTION:
[email protected]cac267c2011-09-29 15:18:10533 log_manager_.current_log()->RecordUserAction(
[email protected]6c2381d2011-10-19 02:52:53534 *content::Details<const char*>(details).ptr());
initial.commit09911bf2008-07-26 23:55:29535 break;
536
[email protected]432115822011-07-10 15:52:27537 case chrome::NOTIFICATION_BROWSER_OPENED:
538 case chrome::NOTIFICATION_BROWSER_CLOSED:
initial.commit09911bf2008-07-26 23:55:29539 LogWindowChange(type, source, details);
540 break;
541
[email protected]432115822011-07-10 15:52:27542 case content::NOTIFICATION_TAB_PARENTED:
543 case content::NOTIFICATION_TAB_CLOSING:
initial.commit09911bf2008-07-26 23:55:29544 LogWindowChange(type, source, details);
545 break;
546
[email protected]432115822011-07-10 15:52:27547 case content::NOTIFICATION_LOAD_STOP:
initial.commit09911bf2008-07-26 23:55:29548 LogLoadComplete(type, source, details);
549 break;
550
[email protected]432115822011-07-10 15:52:27551 case content::NOTIFICATION_LOAD_START:
initial.commit09911bf2008-07-26 23:55:29552 LogLoadStarted();
553 break;
554
[email protected]432115822011-07-10 15:52:27555 case content::NOTIFICATION_RENDERER_PROCESS_CLOSED: {
[email protected]f3b1a082011-11-18 00:34:30556 content::RenderProcessHost::RendererClosedDetails* process_details =
557 content::Details<
558 content::RenderProcessHost::RendererClosedDetails>(
559 details).ptr();
560 content::RenderProcessHost* host =
561 content::Source<content::RenderProcessHost>(source).ptr();
[email protected]718eab62011-10-05 21:16:52562 LogRendererCrash(
563 host, process_details->status, process_details->was_alive);
[email protected]1f085622009-12-04 05:33:45564 }
initial.commit09911bf2008-07-26 23:55:29565 break;
566
[email protected]432115822011-07-10 15:52:27567 case content::NOTIFICATION_RENDERER_PROCESS_HANG:
initial.commit09911bf2008-07-26 23:55:29568 LogRendererHang();
569 break;
570
[email protected]432115822011-07-10 15:52:27571 case content::NOTIFICATION_CHILD_PROCESS_HOST_CONNECTED:
572 case content::NOTIFICATION_CHILD_PROCESS_CRASHED:
573 case content::NOTIFICATION_CHILD_INSTANCE_CREATED:
[email protected]a27a9382009-02-11 23:55:10574 LogChildProcessChange(type, source, details);
initial.commit09911bf2008-07-26 23:55:29575 break;
576
[email protected]432115822011-07-10 15:52:27577 case chrome::NOTIFICATION_TEMPLATE_URL_SERVICE_LOADED:
[email protected]6c2381d2011-10-19 02:52:53578 LogKeywords(content::Source<TemplateURLService>(source).ptr());
initial.commit09911bf2008-07-26 23:55:29579 break;
580
[email protected]432115822011-07-10 15:52:27581 case chrome::NOTIFICATION_OMNIBOX_OPENED_URL: {
[email protected]279703f2012-01-20 22:23:26582 MetricsLog* current_log =
583 static_cast<MetricsLog*>(log_manager_.current_log());
[email protected]1226abb2010-06-10 18:01:28584 DCHECK(current_log);
585 current_log->RecordOmniboxOpenedURL(
[email protected]6c2381d2011-10-19 02:52:53586 *content::Details<AutocompleteLog>(details).ptr());
initial.commit09911bf2008-07-26 23:55:29587 break;
[email protected]1226abb2010-06-10 18:01:28588 }
initial.commit09911bf2008-07-26 23:55:29589
[email protected]432115822011-07-10 15:52:27590 case chrome::NOTIFICATION_BOOKMARK_MODEL_LOADED: {
[email protected]6c2381d2011-10-19 02:52:53591 Profile* p = content::Source<Profile>(source).ptr();
[email protected]b61236c62009-04-09 22:43:55592 if (p)
593 LogBookmarks(p->GetBookmarkModel());
initial.commit09911bf2008-07-26 23:55:29594 break;
[email protected]b61236c62009-04-09 22:43:55595 }
initial.commit09911bf2008-07-26 23:55:29596 default:
[email protected]a063c102010-07-22 22:20:19597 NOTREACHED();
initial.commit09911bf2008-07-26 23:55:29598 break;
599 }
[email protected]d01b8732008-10-16 02:18:07600
601 HandleIdleSinceLastTransmission(false);
602
[email protected]cac267c2011-09-29 15:18:10603 if (log_manager_.current_log())
604 DVLOG(1) << "METRICS: NUMBER OF EVENTS = "
605 << log_manager_.current_log()->num_events();
[email protected]d01b8732008-10-16 02:18:07606}
607
608void MetricsService::HandleIdleSinceLastTransmission(bool in_idle) {
609 // If there wasn't a lot of action, maybe the computer was asleep, in which
610 // case, the log transmissions should have stopped. Here we start them up
611 // again.
[email protected]cac78842008-11-27 01:02:20612 if (!in_idle && idle_since_last_transmission_)
[email protected]7f7f1962011-04-20 15:58:16613 StartSchedulerIfNecessary();
[email protected]cac78842008-11-27 01:02:20614 idle_since_last_transmission_ = in_idle;
initial.commit09911bf2008-07-26 23:55:29615}
616
initial.commit09911bf2008-07-26 23:55:29617void MetricsService::RecordStartOfSessionEnd() {
[email protected]466f3c12011-03-23 21:20:38618 LogCleanShutdown();
initial.commit09911bf2008-07-26 23:55:29619 RecordBooleanPrefValue(prefs::kStabilitySessionEndCompleted, false);
620}
621
622void MetricsService::RecordCompletedSessionEnd() {
[email protected]466f3c12011-03-23 21:20:38623 LogCleanShutdown();
initial.commit09911bf2008-07-26 23:55:29624 RecordBooleanPrefValue(prefs::kStabilitySessionEndCompleted, true);
625}
626
[email protected]7f7f1962011-04-20 15:58:16627void MetricsService::RecordBreakpadRegistration(bool success) {
[email protected]68475e602008-08-22 03:21:15628 if (!success)
[email protected]e73c01972008-08-13 00:18:24629 IncrementPrefValue(prefs::kStabilityBreakpadRegistrationFail);
630 else
631 IncrementPrefValue(prefs::kStabilityBreakpadRegistrationSuccess);
632}
633
634void MetricsService::RecordBreakpadHasDebugger(bool has_debugger) {
635 if (!has_debugger)
636 IncrementPrefValue(prefs::kStabilityDebuggerNotPresent);
637 else
[email protected]68475e602008-08-22 03:21:15638 IncrementPrefValue(prefs::kStabilityDebuggerPresent);
[email protected]e73c01972008-08-13 00:18:24639}
640
initial.commit09911bf2008-07-26 23:55:29641//------------------------------------------------------------------------------
642// private methods
643//------------------------------------------------------------------------------
644
645
646//------------------------------------------------------------------------------
647// Initialization methods
648
649void MetricsService::InitializeMetricsState() {
[email protected]79bf0b72009-04-27 21:30:55650#if defined(OS_POSIX)
[email protected]fe58acc22012-02-29 01:29:58651 server_url_xml_ = ASCIIToUTF16(kServerUrlXml);
652 server_url_proto_ = ASCIIToUTF16(kServerUrlProto);
[email protected]04d2728b2011-12-20 03:25:09653 network_stats_server_ = "chrome.googleechotest.com";
[email protected]adbb3762012-03-09 22:20:08654 // TODO(simonjam): Figure out where this will be hosted.
655 http_pipelining_test_server_ = "";
[email protected]79bf0b72009-04-27 21:30:55656#else
657 BrowserDistribution* dist = BrowserDistribution::GetDistribution();
[email protected]fe58acc22012-02-29 01:29:58658 server_url_xml_ = dist->GetStatsServerURL();
659 server_url_proto_ = ASCIIToUTF16(kServerUrlProto);
[email protected]d67d1052011-06-09 05:11:41660 network_stats_server_ = dist->GetNetworkStatsServer();
[email protected]adbb3762012-03-09 22:20:08661 http_pipelining_test_server_ = dist->GetHttpPipeliningTestServer();
[email protected]79bf0b72009-04-27 21:30:55662#endif
663
initial.commit09911bf2008-07-26 23:55:29664 PrefService* pref = g_browser_process->local_state();
665 DCHECK(pref);
666
[email protected]225c50842010-01-19 21:19:13667 if ((pref->GetInt64(prefs::kStabilityStatsBuildTime)
668 != MetricsLog::GetBuildTime()) ||
[email protected]ddd231e2010-06-29 20:35:19669 (pref->GetString(prefs::kStabilityStatsVersion)
[email protected]225c50842010-01-19 21:19:13670 != MetricsLog::GetVersionString())) {
[email protected]541f77922009-02-23 21:14:38671 // This is a new version, so we don't want to confuse the stats about the
672 // old version with info that we upload.
673 DiscardOldStabilityStats(pref);
674 pref->SetString(prefs::kStabilityStatsVersion,
[email protected]ddd231e2010-06-29 20:35:19675 MetricsLog::GetVersionString());
[email protected]225c50842010-01-19 21:19:13676 pref->SetInt64(prefs::kStabilityStatsBuildTime,
677 MetricsLog::GetBuildTime());
[email protected]541f77922009-02-23 21:14:38678 }
679
initial.commit09911bf2008-07-26 23:55:29680 // Update session ID
681 session_id_ = pref->GetInteger(prefs::kMetricsSessionID);
682 ++session_id_;
683 pref->SetInteger(prefs::kMetricsSessionID, session_id_);
684
initial.commit09911bf2008-07-26 23:55:29685 // Stability bookkeeping
[email protected]e73c01972008-08-13 00:18:24686 IncrementPrefValue(prefs::kStabilityLaunchCount);
initial.commit09911bf2008-07-26 23:55:29687
[email protected]e73c01972008-08-13 00:18:24688 if (!pref->GetBoolean(prefs::kStabilityExitedCleanly)) {
689 IncrementPrefValue(prefs::kStabilityCrashCount);
[email protected]c0c55e92011-09-10 18:47:30690 // Reset flag, and wait until we call LogNeedForCleanShutdown() before
691 // monitoring.
692 pref->SetBoolean(prefs::kStabilityExitedCleanly, true);
initial.commit09911bf2008-07-26 23:55:29693 }
[email protected]e73c01972008-08-13 00:18:24694
[email protected]e73c01972008-08-13 00:18:24695 if (!pref->GetBoolean(prefs::kStabilitySessionEndCompleted)) {
696 IncrementPrefValue(prefs::kStabilityIncompleteSessionEndCount);
[email protected]c9abf242009-07-18 06:00:38697 // This is marked false when we get a WM_ENDSESSION.
698 pref->SetBoolean(prefs::kStabilitySessionEndCompleted, true);
initial.commit09911bf2008-07-26 23:55:29699 }
initial.commit09911bf2008-07-26 23:55:29700
[email protected]9165f742010-03-10 22:55:01701 // Initialize uptime counters.
702 int64 startup_uptime = MetricsLog::GetIncrementalUptime(pref);
[email protected]ae393ec702010-06-27 16:23:14703 DCHECK_EQ(0, startup_uptime);
[email protected]9165f742010-03-10 22:55:01704 // For backwards compatibility, leave this intact in case Omaha is checking
705 // them. prefs::kStabilityLastTimestampSec may also be useless now.
706 // TODO(jar): Delete these if they have no uses.
[email protected]0bb1a622009-03-04 03:22:32707 pref->SetInt64(prefs::kStabilityLaunchTimeSec, Time::Now().ToTimeT());
708
709 // Bookkeeping for the uninstall metrics.
710 IncrementLongPrefsValue(prefs::kUninstallLaunchCount);
initial.commit09911bf2008-07-26 23:55:29711
712 // Save profile metrics.
713 PrefService* prefs = g_browser_process->local_state();
714 if (prefs) {
715 // Remove the current dictionary and store it for use when sending data to
716 // server. By removing the value we prune potentially dead profiles
717 // (and keys). All valid values are added back once services startup.
718 const DictionaryValue* profile_dictionary =
719 prefs->GetDictionary(prefs::kProfileMetrics);
720 if (profile_dictionary) {
721 // Do a deep copy of profile_dictionary since ClearPref will delete it.
722 profile_dictionary_.reset(static_cast<DictionaryValue*>(
723 profile_dictionary->DeepCopy()));
724 prefs->ClearPref(prefs::kProfileMetrics);
725 }
726 }
727
[email protected]92745242009-06-12 16:52:21728 // Get stats on use of command line.
729 const CommandLine* command_line(CommandLine::ForCurrentProcess());
730 size_t common_commands = 0;
731 if (command_line->HasSwitch(switches::kUserDataDir)) {
732 ++common_commands;
733 UMA_HISTOGRAM_COUNTS_100("Chrome.CommandLineDatDirCount", 1);
734 }
735
736 if (command_line->HasSwitch(switches::kApp)) {
737 ++common_commands;
738 UMA_HISTOGRAM_COUNTS_100("Chrome.CommandLineAppModeCount", 1);
739 }
740
[email protected]62b4e522011-07-13 21:46:32741 size_t switch_count = command_line->GetSwitches().size();
742 UMA_HISTOGRAM_COUNTS_100("Chrome.CommandLineFlagCount", switch_count);
[email protected]92745242009-06-12 16:52:21743 UMA_HISTOGRAM_COUNTS_100("Chrome.CommandLineUncommonFlagCount",
[email protected]62b4e522011-07-13 21:46:32744 switch_count - common_commands);
[email protected]92745242009-06-12 16:52:21745
initial.commit09911bf2008-07-26 23:55:29746 // Kick off the process of saving the state (so the uptime numbers keep
747 // getting updated) every n minutes.
748 ScheduleNextStateSave();
749}
750
[email protected]c94d7382012-02-28 08:43:40751// static
[email protected]d33e7cc2011-09-23 01:43:56752void MetricsService::InitTaskGetHardwareClass(
[email protected]c94d7382012-02-28 08:43:40753 base::WeakPtr<MetricsService> self,
[email protected]d33e7cc2011-09-23 01:43:56754 base::MessageLoopProxy* target_loop) {
[email protected]d33e7cc2011-09-23 01:43:56755 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::FILE));
756
757 std::string hardware_class;
758#if defined(OS_CHROMEOS)
759 chromeos::system::StatisticsProvider::GetInstance()->GetMachineStatistic(
760 "hardware_class", &hardware_class);
761#endif // OS_CHROMEOS
762
763 target_loop->PostTask(FROM_HERE,
764 base::Bind(&MetricsService::OnInitTaskGotHardwareClass,
[email protected]c94d7382012-02-28 08:43:40765 self, hardware_class));
[email protected]d33e7cc2011-09-23 01:43:56766}
767
768void MetricsService::OnInitTaskGotHardwareClass(
769 const std::string& hardware_class) {
[email protected]c94d7382012-02-28 08:43:40770 DCHECK_EQ(state_, INIT_TASK_SCHEDULED);
[email protected]85ed9d42010-06-08 22:37:44771 hardware_class_ = hardware_class;
[email protected]d33e7cc2011-09-23 01:43:56772
773 // Start the next part of the init task: loading plugin information.
774 PluginService::GetInstance()->GetPlugins(
775 base::Bind(&MetricsService::OnInitTaskGotPluginInfo,
[email protected]c94d7382012-02-28 08:43:40776 self_ptr_factory_.GetWeakPtr()));
[email protected]d33e7cc2011-09-23 01:43:56777}
778
779void MetricsService::OnInitTaskGotPluginInfo(
780 const std::vector<webkit::WebPluginInfo>& plugins) {
[email protected]c94d7382012-02-28 08:43:40781 DCHECK_EQ(state_, INIT_TASK_SCHEDULED);
[email protected]35fa6a22009-08-15 00:04:01782 plugins_ = plugins;
[email protected]d33e7cc2011-09-23 01:43:56783
[email protected]d67d1052011-06-09 05:11:41784 io_thread_ = g_browser_process->io_thread();
[email protected]85ed9d42010-06-08 22:37:44785 if (state_ == INIT_TASK_SCHEDULED)
786 state_ = INIT_TASK_DONE;
initial.commit09911bf2008-07-26 23:55:29787}
788
789std::string MetricsService::GenerateClientID() {
[email protected]3469e7e2010-10-14 20:34:59790 return guid::GenerateGUID();
initial.commit09911bf2008-07-26 23:55:29791}
792
initial.commit09911bf2008-07-26 23:55:29793//------------------------------------------------------------------------------
794// State save methods
795
796void MetricsService::ScheduleNextStateSave() {
[email protected]8454aeb2011-11-19 23:38:20797 state_saver_factory_.InvalidateWeakPtrs();
initial.commit09911bf2008-07-26 23:55:29798
799 MessageLoop::current()->PostDelayedTask(FROM_HERE,
[email protected]8454aeb2011-11-19 23:38:20800 base::Bind(&MetricsService::SaveLocalState,
801 state_saver_factory_.GetWeakPtr()),
[email protected]fc4252a72012-01-12 21:58:47802 base::TimeDelta::FromMinutes(kSaveStateIntervalMinutes));
initial.commit09911bf2008-07-26 23:55:29803}
804
805void MetricsService::SaveLocalState() {
806 PrefService* pref = g_browser_process->local_state();
807 if (!pref) {
[email protected]a063c102010-07-22 22:20:19808 NOTREACHED();
initial.commit09911bf2008-07-26 23:55:29809 return;
810 }
811
812 RecordCurrentState(pref);
initial.commit09911bf2008-07-26 23:55:29813
[email protected]fc4252a72012-01-12 21:58:47814 // TODO(jar):110021 Does this run down the batteries????
initial.commit09911bf2008-07-26 23:55:29815 ScheduleNextStateSave();
816}
817
818
819//------------------------------------------------------------------------------
820// Recording control methods
821
822void MetricsService::StartRecording() {
[email protected]cac267c2011-09-29 15:18:10823 if (log_manager_.current_log())
initial.commit09911bf2008-07-26 23:55:29824 return;
825
[email protected]29948262012-03-01 12:15:08826 log_manager_.BeginLoggingWithLog(new MetricsLog(client_id_, session_id_),
827 MetricsLogManager::ONGOING_LOG);
initial.commit09911bf2008-07-26 23:55:29828 if (state_ == INITIALIZED) {
829 // We only need to schedule that run once.
[email protected]85ed9d42010-06-08 22:37:44830 state_ = INIT_TASK_SCHEDULED;
initial.commit09911bf2008-07-26 23:55:29831
[email protected]85ed9d42010-06-08 22:37:44832 // Schedules a task on the file thread for execution of slower
833 // initialization steps (such as plugin list generation) necessary
834 // for sending the initial log. This avoids blocking the main UI
835 // thread.
[email protected]ed10dd12011-12-07 12:03:42836 BrowserThread::PostDelayedTask(
837 BrowserThread::FILE,
838 FROM_HERE,
[email protected]d33e7cc2011-09-23 01:43:56839 base::Bind(&MetricsService::InitTaskGetHardwareClass,
[email protected]c94d7382012-02-28 08:43:40840 self_ptr_factory_.GetWeakPtr(),
[email protected]d33e7cc2011-09-23 01:43:56841 MessageLoop::current()->message_loop_proxy()),
[email protected]7e560102012-03-08 20:58:42842 base::TimeDelta::FromSeconds(kInitializationDelaySeconds));
initial.commit09911bf2008-07-26 23:55:29843 }
844}
845
[email protected]024b5cd2011-05-27 03:29:38846void MetricsService::StopRecording() {
[email protected]cac267c2011-09-29 15:18:10847 if (!log_manager_.current_log())
initial.commit09911bf2008-07-26 23:55:29848 return;
849
[email protected]68475e602008-08-22 03:21:15850 // TODO(jar): Integrate bounds on log recording more consistently, so that we
851 // can stop recording logs that are too big much sooner.
[email protected]cac267c2011-09-29 15:18:10852 if (log_manager_.current_log()->num_events() > kEventLimit) {
[email protected]553dba62009-02-24 19:08:23853 UMA_HISTOGRAM_COUNTS("UMA.Discarded Log Events",
[email protected]cac267c2011-09-29 15:18:10854 log_manager_.current_log()->num_events());
855 log_manager_.DiscardCurrentLog();
[email protected]68475e602008-08-22 03:21:15856 StartRecording(); // Start trivial log to hold our histograms.
857 }
858
[email protected]cac267c2011-09-29 15:18:10859 // Adds to ongoing logs.
860 log_manager_.current_log()->set_hardware_class(hardware_class_);
[email protected]accdfa62011-09-20 01:56:52861
[email protected]0b33f80b2008-12-17 21:34:36862 // Put incremental data (histogram deltas, and realtime stats deltas) at the
[email protected]147bbc0b2009-01-06 19:37:40863 // end of all log transmissions (initial log handles this separately).
[email protected]024b5cd2011-05-27 03:29:38864 // RecordIncrementalStabilityElements only exists on the derived
865 // MetricsLog class.
[email protected]279703f2012-01-20 22:23:26866 MetricsLog* current_log =
867 static_cast<MetricsLog*>(log_manager_.current_log());
[email protected]024b5cd2011-05-27 03:29:38868 DCHECK(current_log);
[email protected]fe58acc22012-02-29 01:29:58869 current_log->RecordIncrementalStabilityElements(plugins_);
[email protected]024b5cd2011-05-27 03:29:38870 RecordCurrentHistograms();
initial.commit09911bf2008-07-26 23:55:29871
[email protected]29948262012-03-01 12:15:08872 log_manager_.FinishCurrentLog();
initial.commit09911bf2008-07-26 23:55:29873}
874
[email protected]cac267c2011-09-29 15:18:10875void MetricsService::PushPendingLogsToPersistentStorage() {
initial.commit09911bf2008-07-26 23:55:29876 if (state_ < INITIAL_LOG_READY)
[email protected]28ab7f92009-01-06 21:39:04877 return; // We didn't and still don't have time to get plugin list etc.
initial.commit09911bf2008-07-26 23:55:29878
[email protected]cac267c2011-09-29 15:18:10879 if (log_manager_.has_staged_log()) {
[email protected]29948262012-03-01 12:15:08880 // We may race here, and send second copy of initial log later.
881 if (state_ == INITIAL_LOG_READY)
[email protected]cac267c2011-09-29 15:18:10882 state_ = SENDING_OLD_LOGS;
[email protected]29948262012-03-01 12:15:08883 log_manager_.StoreStagedLogAsUnsent();
initial.commit09911bf2008-07-26 23:55:29884 }
[email protected]cac267c2011-09-29 15:18:10885 DCHECK(!log_manager_.has_staged_log());
[email protected]024b5cd2011-05-27 03:29:38886 StopRecording();
initial.commit09911bf2008-07-26 23:55:29887 StoreUnsentLogs();
888}
889
890//------------------------------------------------------------------------------
891// Transmission of logs methods
892
[email protected]7f7f1962011-04-20 15:58:16893void MetricsService::StartSchedulerIfNecessary() {
894 if (reporting_active() && recording_active())
895 scheduler_->Start();
initial.commit09911bf2008-07-26 23:55:29896}
897
[email protected]7f7f1962011-04-20 15:58:16898void MetricsService::StartScheduledUpload() {
899 // If reporting has been turned off, the scheduler doesn't need to run.
900 if (!reporting_active() || !recording_active()) {
901 scheduler_->Stop();
902 scheduler_->UploadCancelled();
903 return;
904 }
905
[email protected]29948262012-03-01 12:15:08906 StartFinalLogInfoCollection();
907}
908
909void MetricsService::StartFinalLogInfoCollection() {
910 // Begin the multi-step process of collecting memory usage histograms:
911 // First spawn a task to collect the memory details; when that task is
912 // finished, it will call OnMemoryDetailCollectionDone. That will in turn
913 // call HistogramSynchronization to collect histograms from all renderers and
914 // then call OnHistogramSynchronizationDone to continue processing.
[email protected]7f7f1962011-04-20 15:58:16915 DCHECK(!waiting_for_asynchronus_reporting_step_);
916 waiting_for_asynchronus_reporting_step_ = true;
917
[email protected]2226c222011-11-22 00:08:40918 base::Closure callback =
919 base::Bind(&MetricsService::OnMemoryDetailCollectionDone,
[email protected]c94d7382012-02-28 08:43:40920 self_ptr_factory_.GetWeakPtr());
[email protected]84c988a2011-04-19 17:56:33921
[email protected]2226c222011-11-22 00:08:40922 scoped_refptr<MetricsMemoryDetails> details(
923 new MetricsMemoryDetails(callback));
[email protected]84c988a2011-04-19 17:56:33924 details->StartFetch();
925
926 // Collect WebCore cache information to put into a histogram.
[email protected]f3b1a082011-11-18 00:34:30927 for (content::RenderProcessHost::iterator i(
928 content::RenderProcessHost::AllHostsIterator());
[email protected]84c988a2011-04-19 17:56:33929 !i.IsAtEnd(); i.Advance())
[email protected]2ccf45c2011-08-19 23:35:50930 i.GetCurrentValue()->Send(new ChromeViewMsg_GetCacheResourceStats());
[email protected]84c988a2011-04-19 17:56:33931}
932
933void MetricsService::OnMemoryDetailCollectionDone() {
[email protected]c9a3ef82009-05-28 22:02:46934 DCHECK(IsSingleThreaded());
[email protected]7f7f1962011-04-20 15:58:16935 // This function should only be called as the callback from an ansynchronous
936 // step.
937 DCHECK(waiting_for_asynchronus_reporting_step_);
[email protected]c9a3ef82009-05-28 22:02:46938
[email protected]c9a3ef82009-05-28 22:02:46939 // Create a callback_task for OnHistogramSynchronizationDone.
[email protected]2226c222011-11-22 00:08:40940 base::Closure callback = base::Bind(
941 &MetricsService::OnHistogramSynchronizationDone,
[email protected]c94d7382012-02-28 08:43:40942 self_ptr_factory_.GetWeakPtr());
[email protected]c9a3ef82009-05-28 22:02:46943
[email protected]908de522011-10-20 00:55:00944 base::StatisticsRecorder::CollectHistogramStats("Browser");
945
[email protected]c9a3ef82009-05-28 22:02:46946 // Set up the callback to task to call after we receive histograms from all
947 // renderer processes. Wait time specifies how long to wait before absolutely
948 // calling us back on the task.
949 HistogramSynchronizer::FetchRendererHistogramsAsynchronously(
[email protected]2226c222011-11-22 00:08:40950 MessageLoop::current(), callback,
[email protected]7e560102012-03-08 20:58:42951 base::TimeDelta::FromMilliseconds(kMaxHistogramGatheringWaitDuration));
[email protected]c9a3ef82009-05-28 22:02:46952}
953
954void MetricsService::OnHistogramSynchronizationDone() {
initial.commit09911bf2008-07-26 23:55:29955 DCHECK(IsSingleThreaded());
[email protected]29948262012-03-01 12:15:08956 // This function should only be called as the callback from an ansynchronous
957 // step.
958 DCHECK(waiting_for_asynchronus_reporting_step_);
initial.commit09911bf2008-07-26 23:55:29959
[email protected]29948262012-03-01 12:15:08960 waiting_for_asynchronus_reporting_step_ = false;
961 OnFinalLogInfoCollectionDone();
962}
963
964void MetricsService::OnFinalLogInfoCollectionDone() {
[email protected]7f7f1962011-04-20 15:58:16965 // If somehow there is a fetch in progress, we return and hope things work
966 // out. The scheduler isn't informed since if this happens, the scheduler
967 // will get a response from the upload.
[email protected]fe58acc22012-02-29 01:29:58968 DCHECK(!current_fetch_xml_.get());
969 DCHECK(!current_fetch_proto_.get());
970 if (current_fetch_xml_.get() || current_fetch_proto_.get())
[email protected]7f7f1962011-04-20 15:58:16971 return;
972
[email protected]d01b8732008-10-16 02:18:07973 // If we're getting no notifications, then the log won't have much in it, and
974 // it's possible the computer is about to go to sleep, so don't upload and
[email protected]7f7f1962011-04-20 15:58:16975 // stop the scheduler.
976 // Similarly, if logs should no longer be uploaded, stop here.
977 if (idle_since_last_transmission_ ||
978 !recording_active() || !reporting_active()) {
979 scheduler_->Stop();
980 scheduler_->UploadCancelled();
[email protected]d01b8732008-10-16 02:18:07981 return;
982 }
983
[email protected]cac267c2011-09-29 15:18:10984 MakeStagedLog();
initial.commit09911bf2008-07-26 23:55:29985
[email protected]cac267c2011-09-29 15:18:10986 // MakeStagedLog should have prepared log text; if it didn't, skip this
987 // upload and hope things work out next time.
988 if (log_manager_.staged_log_text().empty()) {
[email protected]7f7f1962011-04-20 15:58:16989 scheduler_->UploadCancelled();
[email protected]d01b8732008-10-16 02:18:07990 return;
991 }
initial.commit09911bf2008-07-26 23:55:29992
[email protected]29948262012-03-01 12:15:08993 SendStagedLog();
994}
995
996void MetricsService::MakeStagedLog() {
997 if (log_manager_.has_staged_log())
998 return;
999
1000 switch (state_) {
1001 case INITIALIZED:
1002 case INIT_TASK_SCHEDULED: // We should be further along by now.
1003 DCHECK(false);
1004 return;
1005
1006 case INIT_TASK_DONE:
1007 // We need to wait for the initial log to be ready before sending
1008 // anything, because the server will tell us whether it wants to hear
1009 // from us.
1010 PrepareInitialLog();
1011 DCHECK(state_ == INIT_TASK_DONE);
1012 log_manager_.LoadPersistedUnsentLogs();
1013 state_ = INITIAL_LOG_READY;
1014 break;
1015
1016 case SENDING_OLD_LOGS:
1017 if (log_manager_.has_unsent_logs()) {
1018 log_manager_.StageNextLogForUpload();
1019 break;
1020 }
1021 state_ = SENDING_CURRENT_LOGS;
1022 // Fall through.
1023
1024 case SENDING_CURRENT_LOGS:
1025 StopRecording();
1026 StartRecording();
1027 log_manager_.StageNextLogForUpload();
1028 break;
1029
1030 default:
1031 NOTREACHED();
1032 return;
1033 }
1034
1035 DCHECK(log_manager_.has_staged_log());
1036}
1037
1038void MetricsService::PrepareInitialLog() {
1039 DCHECK(state_ == INIT_TASK_DONE);
1040
1041 MetricsLog* log = new MetricsLog(client_id_, session_id_);
1042 log->set_hardware_class(hardware_class_); // Adds to initial log.
1043 log->RecordEnvironment(plugins_, profile_dictionary_.get());
1044
1045 // Histograms only get written to the current log, so make the new log current
1046 // before writing them.
1047 log_manager_.PauseCurrentLog();
1048 log_manager_.BeginLoggingWithLog(log, MetricsLogManager::INITIAL_LOG);
1049 RecordCurrentHistograms();
1050 log_manager_.FinishCurrentLog();
1051 log_manager_.ResumePausedLog();
1052
1053 DCHECK(!log_manager_.has_staged_log());
1054 log_manager_.StageNextLogForUpload();
1055}
1056
1057void MetricsService::StoreUnsentLogs() {
1058 if (state_ < INITIAL_LOG_READY)
1059 return; // We never Recalled the prior unsent logs.
1060
1061 log_manager_.PersistUnsentLogs();
1062}
1063
1064void MetricsService::SendStagedLog() {
1065 DCHECK(log_manager_.has_staged_log());
1066
[email protected]cac267c2011-09-29 15:18:101067 PrepareFetchWithStagedLog();
[email protected]d01b8732008-10-16 02:18:071068
[email protected]fe58acc22012-02-29 01:29:581069 if (!current_fetch_xml_.get()) {
1070 DCHECK(!current_fetch_proto_.get());
[email protected]d01b8732008-10-16 02:18:071071 // Compression failed, and log discarded :-/.
[email protected]cac267c2011-09-29 15:18:101072 log_manager_.DiscardStagedLog();
[email protected]7f7f1962011-04-20 15:58:161073 scheduler_->UploadCancelled();
[email protected]d01b8732008-10-16 02:18:071074 // TODO(jar): If compression failed, we should have created a tiny log and
1075 // compressed that, so that we can signal that we're losing logs.
1076 return;
1077 }
[email protected]fe58acc22012-02-29 01:29:581078 // Currently, the staged log for the protobuf version of the data is discarded
1079 // after we create the URL request, so that there is no chance for
1080 // re-transmission in case the corresponding XML request fails. We will
1081 // handle protobuf failures more carefully once that becomes the main
1082 // pipeline, i.e. once we switch away from the XML pipeline.
1083 DCHECK(current_fetch_proto_.get() || !log_manager_.has_staged_log_proto());
[email protected]d01b8732008-10-16 02:18:071084
[email protected]7f7f1962011-04-20 15:58:161085 DCHECK(!waiting_for_asynchronus_reporting_step_);
[email protected]d01b8732008-10-16 02:18:071086
[email protected]7f7f1962011-04-20 15:58:161087 waiting_for_asynchronus_reporting_step_ = true;
[email protected]fe58acc22012-02-29 01:29:581088 current_fetch_xml_->Start();
1089 if (current_fetch_proto_.get())
1090 current_fetch_proto_->Start();
[email protected]d01b8732008-10-16 02:18:071091
1092 HandleIdleSinceLastTransmission(true);
1093}
1094
[email protected]cac267c2011-09-29 15:18:101095void MetricsService::PrepareFetchWithStagedLog() {
1096 DCHECK(!log_manager_.staged_log_text().empty());
[email protected]cac78842008-11-27 01:02:201097
[email protected]fe58acc22012-02-29 01:29:581098 // Prepare the XML version.
1099 DCHECK(!current_fetch_xml_.get());
1100 current_fetch_xml_.reset(content::URLFetcher::Create(
1101 GURL(server_url_xml_), content::URLFetcher::POST, this));
1102 current_fetch_xml_->SetRequestContext(
[email protected]8ef3d8052011-07-22 09:03:001103 g_browser_process->system_request_context());
[email protected]fe58acc22012-02-29 01:29:581104 current_fetch_xml_->SetUploadData(kMetricsTypeXml,
1105 log_manager_.staged_log_text().xml);
1106 // We already drop cookies server-side, but we might as well strip them out
1107 // client-side as well.
1108 current_fetch_xml_->SetLoadFlags(net::LOAD_DO_NOT_SAVE_COOKIES |
1109 net::LOAD_DO_NOT_SEND_COOKIES);
1110
1111 // Prepare the protobuf version.
1112 DCHECK(!current_fetch_proto_.get());
1113 if (log_manager_.has_staged_log_proto()) {
1114 current_fetch_proto_.reset(content::URLFetcher::Create(
1115 GURL(server_url_proto_), content::URLFetcher::POST, this));
1116 current_fetch_proto_->SetRequestContext(
1117 g_browser_process->system_request_context());
1118 current_fetch_proto_->SetUploadData(kMetricsTypeProto,
1119 log_manager_.staged_log_text().proto);
1120 // We already drop cookies server-side, but we might as well strip them out
1121 // client-side as well.
1122 current_fetch_proto_->SetLoadFlags(net::LOAD_DO_NOT_SAVE_COOKIES |
1123 net::LOAD_DO_NOT_SEND_COOKIES);
1124
1125 // Discard the protobuf version of the staged log, so that we will avoid
1126 // re-uploading it even if we need to re-upload the XML version.
1127 // TODO(isherman): Handle protobuf upload failures more gracefully once we
1128 // transition away from the XML-based pipeline.
1129 log_manager_.DiscardStagedLogProto();
1130 }
initial.commit09911bf2008-07-26 23:55:291131}
1132
[email protected]f90bf0d92011-01-13 02:12:441133static const char* StatusToString(const net::URLRequestStatus& status) {
initial.commit09911bf2008-07-26 23:55:291134 switch (status.status()) {
[email protected]f90bf0d92011-01-13 02:12:441135 case net::URLRequestStatus::SUCCESS:
initial.commit09911bf2008-07-26 23:55:291136 return "SUCCESS";
1137
[email protected]f90bf0d92011-01-13 02:12:441138 case net::URLRequestStatus::IO_PENDING:
initial.commit09911bf2008-07-26 23:55:291139 return "IO_PENDING";
1140
[email protected]f90bf0d92011-01-13 02:12:441141 case net::URLRequestStatus::HANDLED_EXTERNALLY:
initial.commit09911bf2008-07-26 23:55:291142 return "HANDLED_EXTERNALLY";
1143
[email protected]f90bf0d92011-01-13 02:12:441144 case net::URLRequestStatus::CANCELED:
initial.commit09911bf2008-07-26 23:55:291145 return "CANCELED";
1146
[email protected]f90bf0d92011-01-13 02:12:441147 case net::URLRequestStatus::FAILED:
initial.commit09911bf2008-07-26 23:55:291148 return "FAILED";
1149
1150 default:
[email protected]a063c102010-07-22 22:20:191151 NOTREACHED();
initial.commit09911bf2008-07-26 23:55:291152 return "Unknown";
1153 }
1154}
1155
[email protected]fe58acc22012-02-29 01:29:581156// We need to wait for two responses: the response to the XML upload, and the
1157// response to the protobuf upload. For now, only the XML upload's response
1158// affects decisions like whether to retry the upload, whether to abandon the
1159// upload because it is too large, etc. However, we still need to wait for the
1160// protobuf upload, as we cannot reset |current_fetch_proto_| until we have
1161// confirmation that the network request was sent; and the easiest way to do
1162// that is to wait for the response. In case the XML upload's response arrives
1163// first, we cache that response until the protobuf upload's response also
1164// arrives.
1165//
1166// Note that if the XML upload succeeds but the protobuf upload fails, we will
1167// not retry the protobuf upload. If the XML upload fails while the protobuf
1168// upload succeeds, we will still avoid re-uploading the protobuf data because
1169// we "zap" the data after the first upload attempt. This means that we might
1170// lose protobuf uploads when XML ones succeed; but we will never duplicate any
1171// protobuf uploads. Protobuf failures should be rare enough to where this
1172// should be ok while we have the two pipelines running in parallel.
[email protected]7cc6e5632011-10-25 17:56:121173void MetricsService::OnURLFetchComplete(const content::URLFetcher* source) {
[email protected]7f7f1962011-04-20 15:58:161174 DCHECK(waiting_for_asynchronus_reporting_step_);
[email protected]fe58acc22012-02-29 01:29:581175
1176 // We're not allowed to re-use the existing |URLFetcher|s, so free them here.
1177 scoped_ptr<content::URLFetcher> s;
1178 if (source == current_fetch_xml_.get()) {
1179 s.reset(current_fetch_xml_.release());
1180
1181 // Cache the XML responses, in case we still need to wait for the protobuf
1182 // response.
1183 response_code_ = source->GetResponseCode();
1184 response_status_ = StatusToString(source->GetStatus());
1185 source->GetResponseAsString(&response_data_);
1186 } else if (source == current_fetch_proto_.get()) {
1187 s.reset(current_fetch_proto_.release());
1188 } else {
1189 NOTREACHED();
1190 return;
1191 }
1192
1193 // If we're still waiting for one of the responses, keep waiting...
1194 if (current_fetch_xml_.get() || current_fetch_proto_.get())
1195 return;
1196
1197 // We should only be able to reach here once we've received responses to both
1198 // the XML and the protobuf requests. We should always have the response code
1199 // available.
1200 DCHECK_NE(response_code_, content::URLFetcher::RESPONSE_CODE_INVALID);
[email protected]7f7f1962011-04-20 15:58:161201 waiting_for_asynchronus_reporting_step_ = false;
[email protected]fe58acc22012-02-29 01:29:581202
initial.commit09911bf2008-07-26 23:55:291203
1204 // Confirm send so that we can move on.
[email protected]fe58acc22012-02-29 01:29:581205 VLOG(1) << "METRICS RESPONSE CODE: " << response_code_
1206 << " status=" << response_status_;
[email protected]252873ef2008-08-04 21:59:451207
[email protected]fe58acc22012-02-29 01:29:581208 bool upload_succeeded = response_code_ == 200;
[email protected]7f7f1962011-04-20 15:58:161209
[email protected]0eb34fee2009-01-21 08:04:381210 // Provide boolean for error recovery (allow us to ignore response_code).
[email protected]dc6f4962009-02-13 01:25:501211 bool discard_log = false;
[email protected]0eb34fee2009-01-21 08:04:381212
[email protected]7f7f1962011-04-20 15:58:161213 if (!upload_succeeded &&
[email protected]fe58acc22012-02-29 01:29:581214 log_manager_.staged_log_text().xml.length() >
1215 kUploadLogAvoidRetransmitSize) {
[email protected]cac267c2011-09-29 15:18:101216 UMA_HISTOGRAM_COUNTS(
1217 "UMA.Large Rejected Log was Discarded",
[email protected]fe58acc22012-02-29 01:29:581218 static_cast<int>(log_manager_.staged_log_text().xml.length()));
[email protected]0eb34fee2009-01-21 08:04:381219 discard_log = true;
[email protected]fe58acc22012-02-29 01:29:581220 } else if (response_code_ == 400) {
[email protected]0eb34fee2009-01-21 08:04:381221 // Bad syntax. Retransmission won't work.
[email protected]553dba62009-02-24 19:08:231222 UMA_HISTOGRAM_COUNTS("UMA.Unacceptable_Log_Discarded", state_);
[email protected]0eb34fee2009-01-21 08:04:381223 discard_log = true;
[email protected]68475e602008-08-22 03:21:151224 }
1225
[email protected]7f7f1962011-04-20 15:58:161226 if (!upload_succeeded && !discard_log) {
[email protected]666205032010-10-21 20:56:581227 VLOG(1) << "METRICS: transmission attempt returned a failure code: "
[email protected]fe58acc22012-02-29 01:29:581228 << response_code_ << ". Verify network connectivity";
[email protected]7f7f1962011-04-20 15:58:161229 LogBadResponseCode();
[email protected]0eb34fee2009-01-21 08:04:381230 } else { // Successful receipt (or we are discarding log).
[email protected]fe58acc22012-02-29 01:29:581231 VLOG(1) << "METRICS RESPONSE DATA: " << response_data_;
initial.commit09911bf2008-07-26 23:55:291232 switch (state_) {
1233 case INITIAL_LOG_READY:
[email protected]cac267c2011-09-29 15:18:101234 state_ = SENDING_OLD_LOGS;
initial.commit09911bf2008-07-26 23:55:291235 break;
1236
initial.commit09911bf2008-07-26 23:55:291237 case SENDING_OLD_LOGS:
[email protected]d53e2232011-06-30 15:54:571238 // Store the updated list to disk now that the removed log is uploaded.
initial.commit09911bf2008-07-26 23:55:291239 StoreUnsentLogs();
1240 break;
1241
1242 case SENDING_CURRENT_LOGS:
1243 break;
1244
1245 default:
[email protected]a063c102010-07-22 22:20:191246 NOTREACHED();
initial.commit09911bf2008-07-26 23:55:291247 break;
1248 }
[email protected]d01b8732008-10-16 02:18:071249
[email protected]cac267c2011-09-29 15:18:101250 log_manager_.DiscardStagedLog();
[email protected]252873ef2008-08-04 21:59:451251
[email protected]cac267c2011-09-29 15:18:101252 if (log_manager_.has_unsent_logs())
initial.commit09911bf2008-07-26 23:55:291253 DCHECK(state_ < SENDING_CURRENT_LOGS);
initial.commit09911bf2008-07-26 23:55:291254 }
[email protected]252873ef2008-08-04 21:59:451255
[email protected]7f7f1962011-04-20 15:58:161256 // Error 400 indicates a problem with the log, not with the server, so
1257 // don't consider that a sign that the server is in trouble.
[email protected]fe58acc22012-02-29 01:29:581258 bool server_is_healthy = upload_succeeded || response_code_ == 400;
[email protected]7f7f1962011-04-20 15:58:161259
[email protected]cac267c2011-09-29 15:18:101260 scheduler_->UploadFinished(server_is_healthy,
1261 log_manager_.has_unsent_logs());
[email protected]d67d1052011-06-09 05:11:411262
1263 // Collect network stats if UMA upload succeeded.
[email protected]adbb3762012-03-09 22:20:081264 if (server_is_healthy && io_thread_) {
[email protected]d67d1052011-06-09 05:11:411265 chrome_browser_net::CollectNetworkStats(network_stats_server_, io_thread_);
[email protected]adbb3762012-03-09 22:20:081266 chrome_browser_net::CollectPipeliningCapabilityStatsOnUIThread(
1267 http_pipelining_test_server_, io_thread_);
1268 }
[email protected]fe58acc22012-02-29 01:29:581269
1270 // Reset the cached response data.
1271 response_code_ = content::URLFetcher::RESPONSE_CODE_INVALID;
1272 response_data_ = std::string();
1273 response_status_ = std::string();
initial.commit09911bf2008-07-26 23:55:291274}
1275
[email protected]7f7f1962011-04-20 15:58:161276void MetricsService::LogBadResponseCode() {
[email protected]666205032010-10-21 20:56:581277 VLOG(1) << "Verify your metrics logs are formatted correctly. Verify server "
[email protected]fe58acc22012-02-29 01:29:581278 "is active at " << server_url_xml_;
[email protected]cac267c2011-09-29 15:18:101279 if (!log_manager_.has_staged_log()) {
[email protected]666205032010-10-21 20:56:581280 VLOG(1) << "METRICS: Recorder shutdown during log transmission.";
[email protected]252873ef2008-08-04 21:59:451281 } else {
[email protected]7f7f1962011-04-20 15:58:161282 VLOG(1) << "METRICS: transmission retry being scheduled for "
[email protected]fe58acc22012-02-29 01:29:581283 << log_manager_.staged_log_text().xml;
initial.commit09911bf2008-07-26 23:55:291284 }
initial.commit09911bf2008-07-26 23:55:291285}
1286
[email protected]6c2381d2011-10-19 02:52:531287void MetricsService::LogWindowChange(
1288 int type,
1289 const content::NotificationSource& source,
1290 const content::NotificationDetails& details) {
[email protected]534e54b2008-08-13 15:40:091291 int controller_id = -1;
1292 uintptr_t window_or_tab = source.map_key();
initial.commit09911bf2008-07-26 23:55:291293 MetricsLog::WindowEventType window_type;
1294
1295 // Note: since we stop all logging when a single OTR session is active, it is
1296 // possible that we start getting notifications about a window that we don't
1297 // know about.
[email protected]534e54b2008-08-13 15:40:091298 if (window_map_.find(window_or_tab) == window_map_.end()) {
1299 controller_id = next_window_id_++;
1300 window_map_[window_or_tab] = controller_id;
initial.commit09911bf2008-07-26 23:55:291301 } else {
[email protected]534e54b2008-08-13 15:40:091302 controller_id = window_map_[window_or_tab];
initial.commit09911bf2008-07-26 23:55:291303 }
[email protected]92745242009-06-12 16:52:211304 DCHECK_NE(controller_id, -1);
initial.commit09911bf2008-07-26 23:55:291305
[email protected]432115822011-07-10 15:52:271306 switch (type) {
1307 case content::NOTIFICATION_TAB_PARENTED:
1308 case chrome::NOTIFICATION_BROWSER_OPENED:
initial.commit09911bf2008-07-26 23:55:291309 window_type = MetricsLog::WINDOW_CREATE;
1310 break;
1311
[email protected]432115822011-07-10 15:52:271312 case content::NOTIFICATION_TAB_CLOSING:
1313 case chrome::NOTIFICATION_BROWSER_CLOSED:
[email protected]534e54b2008-08-13 15:40:091314 window_map_.erase(window_map_.find(window_or_tab));
initial.commit09911bf2008-07-26 23:55:291315 window_type = MetricsLog::WINDOW_DESTROY;
1316 break;
1317
1318 default:
[email protected]a063c102010-07-22 22:20:191319 NOTREACHED();
[email protected]68d74f02009-02-13 01:36:501320 return;
initial.commit09911bf2008-07-26 23:55:291321 }
1322
[email protected]534e54b2008-08-13 15:40:091323 // TODO(brettw) we should have some kind of ID for the parent.
[email protected]cac267c2011-09-29 15:18:101324 log_manager_.current_log()->RecordWindowEvent(window_type, controller_id, 0);
initial.commit09911bf2008-07-26 23:55:291325}
1326
[email protected]6c2381d2011-10-19 02:52:531327void MetricsService::LogLoadComplete(
1328 int type,
1329 const content::NotificationSource& source,
1330 const content::NotificationDetails& details) {
[email protected]ad50def52011-10-19 23:17:071331 if (details == content::NotificationService::NoDetails())
initial.commit09911bf2008-07-26 23:55:291332 return;
1333
[email protected]68475e602008-08-22 03:21:151334 // TODO(jar): There is a bug causing this to be called too many times, and
1335 // the log overflows. For now, we won't record these events.
[email protected]553dba62009-02-24 19:08:231336 UMA_HISTOGRAM_COUNTS("UMA.LogLoadComplete called", 1);
[email protected]68475e602008-08-22 03:21:151337 return;
1338
[email protected]6c2381d2011-10-19 02:52:531339 const content::Details<LoadNotificationDetails> load_details(details);
[email protected]534e54b2008-08-13 15:40:091340 int controller_id = window_map_[details.map_key()];
[email protected]cac267c2011-09-29 15:18:101341 log_manager_.current_log()->RecordLoadEvent(controller_id,
[email protected]09d31d52012-03-11 22:30:271342 load_details->url,
1343 load_details->origin,
1344 load_details->session_index,
1345 load_details->load_time);
initial.commit09911bf2008-07-26 23:55:291346}
1347
[email protected]57ecc4b2010-08-11 03:02:511348void MetricsService::IncrementPrefValue(const char* path) {
[email protected]e73c01972008-08-13 00:18:241349 PrefService* pref = g_browser_process->local_state();
1350 DCHECK(pref);
1351 int value = pref->GetInteger(path);
1352 pref->SetInteger(path, value + 1);
1353}
1354
[email protected]57ecc4b2010-08-11 03:02:511355void MetricsService::IncrementLongPrefsValue(const char* path) {
[email protected]0bb1a622009-03-04 03:22:321356 PrefService* pref = g_browser_process->local_state();
1357 DCHECK(pref);
1358 int64 value = pref->GetInt64(path);
[email protected]b42c5e42010-06-03 20:43:251359 pref->SetInt64(path, value + 1);
[email protected]0bb1a622009-03-04 03:22:321360}
1361
initial.commit09911bf2008-07-26 23:55:291362void MetricsService::LogLoadStarted() {
[email protected]dd8d12a2011-09-02 02:10:151363 HISTOGRAM_ENUMERATION("Chrome.UmaPageloadCounter", 1, 2);
[email protected]e73c01972008-08-13 00:18:241364 IncrementPrefValue(prefs::kStabilityPageLoadCount);
[email protected]0bb1a622009-03-04 03:22:321365 IncrementLongPrefsValue(prefs::kUninstallMetricsPageLoadCount);
[email protected]0b33f80b2008-12-17 21:34:361366 // We need to save the prefs, as page load count is a critical stat, and it
1367 // might be lost due to a crash :-(.
initial.commit09911bf2008-07-26 23:55:291368}
1369
[email protected]f3b1a082011-11-18 00:34:301370void MetricsService::LogRendererCrash(content::RenderProcessHost* host,
[email protected]718eab62011-10-05 21:16:521371 base::TerminationStatus status,
1372 bool was_alive) {
[email protected]f3b1a082011-11-18 00:34:301373 Profile* profile = Profile::FromBrowserContext(host->GetBrowserContext());
[email protected]6f371442011-11-09 06:45:461374 ExtensionService* service = profile->GetExtensionService();
1375 bool was_extension_process =
[email protected]f3b1a082011-11-18 00:34:301376 service && service->process_map()->Contains(host->GetID());
[email protected]718eab62011-10-05 21:16:521377 if (status == base::TERMINATION_STATUS_PROCESS_CRASHED ||
1378 status == base::TERMINATION_STATUS_ABNORMAL_TERMINATION) {
1379 if (was_extension_process)
1380 IncrementPrefValue(prefs::kStabilityExtensionRendererCrashCount);
1381 else
1382 IncrementPrefValue(prefs::kStabilityRendererCrashCount);
initial.commit09911bf2008-07-26 23:55:291383
[email protected]718eab62011-10-05 21:16:521384 UMA_HISTOGRAM_PERCENTAGE("BrowserRenderProcessHost.ChildCrashes",
1385 was_extension_process ? 2 : 1);
1386 if (was_alive) {
1387 UMA_HISTOGRAM_PERCENTAGE("BrowserRenderProcessHost.ChildCrashesWasAlive",
1388 was_extension_process ? 2 : 1);
1389 }
1390 } else if (status == base::TERMINATION_STATUS_PROCESS_WAS_KILLED) {
1391 UMA_HISTOGRAM_PERCENTAGE("BrowserRenderProcessHost.ChildKills",
1392 was_extension_process ? 2 : 1);
1393 if (was_alive) {
1394 UMA_HISTOGRAM_PERCENTAGE("BrowserRenderProcessHost.ChildKillsWasAlive",
1395 was_extension_process ? 2 : 1);
1396 }
1397 }
[email protected]1f085622009-12-04 05:33:451398}
1399
initial.commit09911bf2008-07-26 23:55:291400void MetricsService::LogRendererHang() {
[email protected]e73c01972008-08-13 00:18:241401 IncrementPrefValue(prefs::kStabilityRendererHangCount);
initial.commit09911bf2008-07-26 23:55:291402}
1403
[email protected]c0c55e92011-09-10 18:47:301404void MetricsService::LogNeedForCleanShutdown() {
1405 PrefService* pref = g_browser_process->local_state();
1406 pref->SetBoolean(prefs::kStabilityExitedCleanly, false);
1407 // Redundant setting to be sure we call for a clean shutdown.
1408 clean_shutdown_status_ = NEED_TO_SHUTDOWN;
1409}
1410
1411bool MetricsService::UmaMetricsProperlyShutdown() {
1412 CHECK(clean_shutdown_status_ == CLEANLY_SHUTDOWN ||
1413 clean_shutdown_status_ == NEED_TO_SHUTDOWN);
1414 return clean_shutdown_status_ == CLEANLY_SHUTDOWN;
1415}
1416
[email protected]67c4e952011-09-17 00:44:271417// For use in hack in LogCleanShutdown.
1418static void Signal(base::WaitableEvent* event) {
1419 event->Signal();
1420}
1421
[email protected]466f3c12011-03-23 21:20:381422void MetricsService::LogCleanShutdown() {
[email protected]acd55b32011-09-05 17:35:311423 // Redundant hack to write pref ASAP.
1424 PrefService* pref = g_browser_process->local_state();
1425 pref->SetBoolean(prefs::kStabilityExitedCleanly, true);
[email protected]fbe17c8a2011-12-27 16:41:481426 pref->CommitPendingWrite();
[email protected]67c4e952011-09-17 00:44:271427 // Hack: TBD: Remove this wait.
1428 // We are so concerned that the pref gets written, we are now willing to stall
1429 // the UI thread until we get assurance that a pref-writing task has
1430 // completed.
1431 base::WaitableEvent done_writing(false, false);
1432 BrowserThread::PostTask(BrowserThread::FILE, FROM_HERE,
[email protected]8454aeb2011-11-19 23:38:201433 base::Bind(Signal, &done_writing));
[email protected]67c4e952011-09-17 00:44:271434 done_writing.TimedWait(base::TimeDelta::FromHours(1));
1435
[email protected]c0c55e92011-09-10 18:47:301436 // Redundant setting to assure that we always reset this value at shutdown
1437 // (and that we don't use some alternate path, and not call LogCleanShutdown).
1438 clean_shutdown_status_ = CLEANLY_SHUTDOWN;
[email protected]acd55b32011-09-05 17:35:311439
[email protected]466f3c12011-03-23 21:20:381440 RecordBooleanPrefValue(prefs::kStabilityExitedCleanly, true);
1441}
1442
[email protected]c1834a92011-01-21 18:21:031443#if defined(OS_CHROMEOS)
1444void MetricsService::LogChromeOSCrash(const std::string &crash_type) {
1445 if (crash_type == "user")
1446 IncrementPrefValue(prefs::kStabilityOtherUserCrashCount);
1447 else if (crash_type == "kernel")
1448 IncrementPrefValue(prefs::kStabilityKernelCrashCount);
1449 else if (crash_type == "uncleanshutdown")
1450 IncrementPrefValue(prefs::kStabilitySystemUncleanShutdownCount);
1451 else
1452 NOTREACHED() << "Unexpected Chrome OS crash type " << crash_type;
1453 // Wake up metrics logs sending if necessary now that new
1454 // log data is available.
1455 HandleIdleSinceLastTransmission(false);
1456}
1457#endif // OS_CHROMEOS
1458
[email protected]a27a9382009-02-11 23:55:101459void MetricsService::LogChildProcessChange(
[email protected]432115822011-07-10 15:52:271460 int type,
[email protected]6c2381d2011-10-19 02:52:531461 const content::NotificationSource& source,
1462 const content::NotificationDetails& details) {
[email protected]4967f792012-01-20 22:14:401463 content::Details<ChildProcessData> child_details(details);
[email protected]4306c3792011-12-02 01:57:531464 const string16& child_name = child_details->name;
[email protected]0d84c5d2009-10-09 01:10:421465
[email protected]a27a9382009-02-11 23:55:101466 if (child_process_stats_buffer_.find(child_name) ==
1467 child_process_stats_buffer_.end()) {
[email protected]0d84c5d2009-10-09 01:10:421468 child_process_stats_buffer_[child_name] =
[email protected]4306c3792011-12-02 01:57:531469 ChildProcessStats(child_details->type);
initial.commit09911bf2008-07-26 23:55:291470 }
1471
[email protected]a27a9382009-02-11 23:55:101472 ChildProcessStats& stats = child_process_stats_buffer_[child_name];
[email protected]432115822011-07-10 15:52:271473 switch (type) {
1474 case content::NOTIFICATION_CHILD_PROCESS_HOST_CONNECTED:
initial.commit09911bf2008-07-26 23:55:291475 stats.process_launches++;
1476 break;
1477
[email protected]432115822011-07-10 15:52:271478 case content::NOTIFICATION_CHILD_INSTANCE_CREATED:
initial.commit09911bf2008-07-26 23:55:291479 stats.instances++;
1480 break;
1481
[email protected]432115822011-07-10 15:52:271482 case content::NOTIFICATION_CHILD_PROCESS_CRASHED:
initial.commit09911bf2008-07-26 23:55:291483 stats.process_crashes++;
[email protected]1f085622009-12-04 05:33:451484 // Exclude plugin crashes from the count below because we report them via
1485 // a separate UMA metric.
[email protected]4306c3792011-12-02 01:57:531486 if (!IsPluginProcess(child_details->type)) {
[email protected]1f085622009-12-04 05:33:451487 IncrementPrefValue(prefs::kStabilityChildProcessCrashCount);
1488 }
initial.commit09911bf2008-07-26 23:55:291489 break;
1490
1491 default:
[email protected]432115822011-07-10 15:52:271492 NOTREACHED() << "Unexpected notification type " << type;
initial.commit09911bf2008-07-26 23:55:291493 return;
1494 }
1495}
1496
1497// Recursively counts the number of bookmarks and folders in node.
[email protected]b3c33d462009-06-26 22:29:201498static void CountBookmarks(const BookmarkNode* node,
1499 int* bookmarks,
1500 int* folders) {
[email protected]0890e60e2011-06-27 14:55:211501 if (node->is_url())
initial.commit09911bf2008-07-26 23:55:291502 (*bookmarks)++;
1503 else
1504 (*folders)++;
[email protected]9c1a75a2011-03-10 02:38:121505 for (int i = 0; i < node->child_count(); ++i)
initial.commit09911bf2008-07-26 23:55:291506 CountBookmarks(node->GetChild(i), bookmarks, folders);
1507}
1508
[email protected]b3c33d462009-06-26 22:29:201509void MetricsService::LogBookmarks(const BookmarkNode* node,
[email protected]57ecc4b2010-08-11 03:02:511510 const char* num_bookmarks_key,
1511 const char* num_folders_key) {
initial.commit09911bf2008-07-26 23:55:291512 DCHECK(node);
1513 int num_bookmarks = 0;
1514 int num_folders = 0;
1515 CountBookmarks(node, &num_bookmarks, &num_folders);
1516 num_folders--; // Don't include the root folder in the count.
1517
1518 PrefService* pref = g_browser_process->local_state();
1519 DCHECK(pref);
1520 pref->SetInteger(num_bookmarks_key, num_bookmarks);
1521 pref->SetInteger(num_folders_key, num_folders);
1522}
1523
[email protected]d8e41ed2008-09-11 15:22:321524void MetricsService::LogBookmarks(BookmarkModel* model) {
initial.commit09911bf2008-07-26 23:55:291525 DCHECK(model);
[email protected]72bdcfe2011-07-22 17:21:581526 LogBookmarks(model->bookmark_bar_node(),
initial.commit09911bf2008-07-26 23:55:291527 prefs::kNumBookmarksOnBookmarkBar,
1528 prefs::kNumFoldersOnBookmarkBar);
1529 LogBookmarks(model->other_node(),
1530 prefs::kNumBookmarksInOtherBookmarkFolder,
1531 prefs::kNumFoldersInOtherBookmarkFolder);
1532 ScheduleNextStateSave();
1533}
1534
[email protected]8e5c89a2011-06-07 18:13:331535void MetricsService::LogKeywords(const TemplateURLService* url_model) {
initial.commit09911bf2008-07-26 23:55:291536 DCHECK(url_model);
1537
1538 PrefService* pref = g_browser_process->local_state();
1539 DCHECK(pref);
1540 pref->SetInteger(prefs::kNumKeywords,
1541 static_cast<int>(url_model->GetTemplateURLs().size()));
1542 ScheduleNextStateSave();
1543}
1544
1545void MetricsService::RecordPluginChanges(PrefService* pref) {
[email protected]f8628c22011-04-05 12:10:181546 ListPrefUpdate update(pref, prefs::kStabilityPluginStats);
1547 ListValue* plugins = update.Get();
initial.commit09911bf2008-07-26 23:55:291548 DCHECK(plugins);
1549
1550 for (ListValue::iterator value_iter = plugins->begin();
1551 value_iter != plugins->end(); ++value_iter) {
1552 if (!(*value_iter)->IsType(Value::TYPE_DICTIONARY)) {
[email protected]a063c102010-07-22 22:20:191553 NOTREACHED();
initial.commit09911bf2008-07-26 23:55:291554 continue;
1555 }
1556
1557 DictionaryValue* plugin_dict = static_cast<DictionaryValue*>(*value_iter);
[email protected]57ecc4b2010-08-11 03:02:511558 std::string plugin_name;
[email protected]8e50b602009-03-03 22:59:431559 plugin_dict->GetString(prefs::kStabilityPluginName, &plugin_name);
[email protected]6470ee8f2009-03-03 20:46:401560 if (plugin_name.empty()) {
[email protected]a063c102010-07-22 22:20:191561 NOTREACHED();
initial.commit09911bf2008-07-26 23:55:291562 continue;
1563 }
1564
[email protected]57ecc4b2010-08-11 03:02:511565 // TODO(viettrungluu): remove conversions
[email protected]68b9e72b2011-08-05 23:08:221566 string16 name16 = UTF8ToUTF16(plugin_name);
1567 if (child_process_stats_buffer_.find(name16) ==
1568 child_process_stats_buffer_.end()) {
initial.commit09911bf2008-07-26 23:55:291569 continue;
[email protected]68b9e72b2011-08-05 23:08:221570 }
initial.commit09911bf2008-07-26 23:55:291571
[email protected]68b9e72b2011-08-05 23:08:221572 ChildProcessStats stats = child_process_stats_buffer_[name16];
initial.commit09911bf2008-07-26 23:55:291573 if (stats.process_launches) {
1574 int launches = 0;
[email protected]8e50b602009-03-03 22:59:431575 plugin_dict->GetInteger(prefs::kStabilityPluginLaunches, &launches);
initial.commit09911bf2008-07-26 23:55:291576 launches += stats.process_launches;
[email protected]8e50b602009-03-03 22:59:431577 plugin_dict->SetInteger(prefs::kStabilityPluginLaunches, launches);
initial.commit09911bf2008-07-26 23:55:291578 }
1579 if (stats.process_crashes) {
1580 int crashes = 0;
[email protected]8e50b602009-03-03 22:59:431581 plugin_dict->GetInteger(prefs::kStabilityPluginCrashes, &crashes);
initial.commit09911bf2008-07-26 23:55:291582 crashes += stats.process_crashes;
[email protected]8e50b602009-03-03 22:59:431583 plugin_dict->SetInteger(prefs::kStabilityPluginCrashes, crashes);
initial.commit09911bf2008-07-26 23:55:291584 }
1585 if (stats.instances) {
1586 int instances = 0;
[email protected]8e50b602009-03-03 22:59:431587 plugin_dict->GetInteger(prefs::kStabilityPluginInstances, &instances);
initial.commit09911bf2008-07-26 23:55:291588 instances += stats.instances;
[email protected]8e50b602009-03-03 22:59:431589 plugin_dict->SetInteger(prefs::kStabilityPluginInstances, instances);
initial.commit09911bf2008-07-26 23:55:291590 }
1591
[email protected]68b9e72b2011-08-05 23:08:221592 child_process_stats_buffer_.erase(name16);
initial.commit09911bf2008-07-26 23:55:291593 }
1594
1595 // Now go through and add dictionaries for plugins that didn't already have
1596 // reports in Local State.
[email protected]68b9e72b2011-08-05 23:08:221597 for (std::map<string16, ChildProcessStats>::iterator cache_iter =
[email protected]a27a9382009-02-11 23:55:101598 child_process_stats_buffer_.begin();
1599 cache_iter != child_process_stats_buffer_.end(); ++cache_iter) {
[email protected]a27a9382009-02-11 23:55:101600 ChildProcessStats stats = cache_iter->second;
[email protected]0d84c5d2009-10-09 01:10:421601
1602 // Insert only plugins information into the plugins list.
[email protected]8d5f1dae2011-11-11 14:30:411603 if (!IsPluginProcess(stats.process_type))
[email protected]0d84c5d2009-10-09 01:10:421604 continue;
1605
[email protected]57ecc4b2010-08-11 03:02:511606 // TODO(viettrungluu): remove conversion
[email protected]68b9e72b2011-08-05 23:08:221607 std::string plugin_name = UTF16ToUTF8(cache_iter->first);
[email protected]0d84c5d2009-10-09 01:10:421608
initial.commit09911bf2008-07-26 23:55:291609 DictionaryValue* plugin_dict = new DictionaryValue;
1610
[email protected]8e50b602009-03-03 22:59:431611 plugin_dict->SetString(prefs::kStabilityPluginName, plugin_name);
1612 plugin_dict->SetInteger(prefs::kStabilityPluginLaunches,
initial.commit09911bf2008-07-26 23:55:291613 stats.process_launches);
[email protected]8e50b602009-03-03 22:59:431614 plugin_dict->SetInteger(prefs::kStabilityPluginCrashes,
initial.commit09911bf2008-07-26 23:55:291615 stats.process_crashes);
[email protected]8e50b602009-03-03 22:59:431616 plugin_dict->SetInteger(prefs::kStabilityPluginInstances,
initial.commit09911bf2008-07-26 23:55:291617 stats.instances);
1618 plugins->Append(plugin_dict);
1619 }
[email protected]a27a9382009-02-11 23:55:101620 child_process_stats_buffer_.clear();
initial.commit09911bf2008-07-26 23:55:291621}
1622
[email protected]6c2381d2011-10-19 02:52:531623bool MetricsService::CanLogNotification(
1624 int type,
1625 const content::NotificationSource& source,
1626 const content::NotificationDetails& details) {
[email protected]2c910b72011-03-08 21:16:321627 // We simply don't log anything to UMA if there is a single incognito
initial.commit09911bf2008-07-26 23:55:291628 // session visible. The problem is that we always notify using the orginal
1629 // profile in order to simplify notification processing.
1630 return !BrowserList::IsOffTheRecordSessionActive();
1631}
1632
[email protected]57ecc4b2010-08-11 03:02:511633void MetricsService::RecordBooleanPrefValue(const char* path, bool value) {
initial.commit09911bf2008-07-26 23:55:291634 DCHECK(IsSingleThreaded());
1635
1636 PrefService* pref = g_browser_process->local_state();
1637 DCHECK(pref);
1638
1639 pref->SetBoolean(path, value);
1640 RecordCurrentState(pref);
1641}
1642
1643void MetricsService::RecordCurrentState(PrefService* pref) {
[email protected]0bb1a622009-03-04 03:22:321644 pref->SetInt64(prefs::kStabilityLastTimestampSec, Time::Now().ToTimeT());
initial.commit09911bf2008-07-26 23:55:291645
1646 RecordPluginChanges(pref);
1647}
1648
[email protected]8d5f1dae2011-11-11 14:30:411649// static
[email protected]bd5d6cf2011-12-01 00:39:121650bool MetricsService::IsPluginProcess(content::ProcessType type) {
1651 return (type == content::PROCESS_TYPE_PLUGIN||
1652 type == content::PROCESS_TYPE_PPAPI_PLUGIN);
[email protected]8d5f1dae2011-11-11 14:30:411653}
1654
[email protected]5ccaa412009-11-13 22:00:161655#if defined(OS_CHROMEOS)
[email protected]29cf16772010-04-21 15:13:471656void MetricsService::StartExternalMetrics() {
[email protected]5ccaa412009-11-13 22:00:161657 external_metrics_ = new chromeos::ExternalMetrics;
[email protected]29cf16772010-04-21 15:13:471658 external_metrics_->Start();
[email protected]5ccaa412009-11-13 22:00:161659}
1660#endif
[email protected]3819f2ee2011-08-21 09:44:381661
1662// static
1663bool MetricsServiceHelper::IsMetricsReportingEnabled() {
1664 bool result = false;
1665 const PrefService* local_state = g_browser_process->local_state();
1666 if (local_state) {
1667 const PrefService::Preference* uma_pref =
1668 local_state->FindPreference(prefs::kMetricsReportingEnabled);
1669 if (uma_pref) {
1670 bool success = uma_pref->GetValue()->GetAsBoolean(&result);
1671 DCHECK(success);
1672 }
1673 }
1674 return result;
1675}