blob: 90e4ce549919c40e9e7a97a92c7f29588e087a6d [file] [log] [blame]
tfarina@chromium.org4d818fee2010-06-06 13:32:271// Copyright (c) 2010 The Chromium Authors. All rights reserved.
license.botbf09a502008-08-24 00:55:552// Use of this source code is governed by a BSD-style license that can be
3// found in the LICENSE file.
initial.commit09911bf2008-07-26 23:55:294
5
6
7//------------------------------------------------------------------------------
8// Description of the life cycle of a instance of MetricsService.
9//
10// OVERVIEW
11//
12// A MetricsService instance is typically created at application startup. It
13// is the central controller for the acquisition of log data, and the automatic
14// transmission of that log data to an external server. Its major job is to
15// manage logs, grouping them for transmission, and transmitting them. As part
16// of its grouping, MS finalizes logs by including some just-in-time gathered
17// memory statistics, snapshotting the current stats of numerous histograms,
18// closing the logs, translating to XML text, and compressing the results for
19// transmission. Transmission includes submitting a compressed log as data in a
jar@chromium.org281d2882009-01-20 20:32:4220// URL-post, and retransmitting (or retaining at process termination) if the
initial.commit09911bf2008-07-26 23:55:2921// attempted transmission failed. Retention across process terminations is done
22// using the the PrefServices facilities. The format for the retained
23// logs (ones that never got transmitted) is always the uncompressed textual
24// representation.
25//
jar@chromium.org281d2882009-01-20 20:32:4226// Logs fall into one of two categories: "initial logs," and "ongoing logs."
27// There is at most one initial log sent for each complete run of the chromium
initial.commit09911bf2008-07-26 23:55:2928// product (from startup, to browser shutdown). An initial log is generally
29// transmitted some short time (1 minute?) after startup, and includes stats
30// such as recent crash info, the number and types of plugins, etc. The
jar@chromium.org281d2882009-01-20 20:32:4231// external server's response to the initial log conceptually tells this MS if
32// it should continue transmitting logs (during this session). The server
33// response can actually be much more detailed, and always includes (at a
34// minimum) how often additional ongoing logs should be sent.
initial.commit09911bf2008-07-26 23:55:2935//
36// After the above initial log, a series of ongoing logs will be transmitted.
37// The first ongoing log actually begins to accumulate information stating when
38// the MS was first constructed. Note that even though the initial log is
39// commonly sent a full minute after startup, the initial log does not include
40// much in the way of user stats. The most common interlog period (delay)
jar@google.com0b33f80b2008-12-17 21:34:3641// is 20 minutes. That time period starts when the first user action causes a
initial.commit09911bf2008-07-26 23:55:2942// logging event. This means that if there is no user action, there may be long
jar@chromium.org281d2882009-01-20 20:32:4243// periods without any (ongoing) log transmissions. Ongoing logs typically
initial.commit09911bf2008-07-26 23:55:2944// contain very detailed records of user activities (ex: opened tab, closed
45// tab, fetched URL, maximized window, etc.) In addition, just before an
46// ongoing log is closed out, a call is made to gather memory statistics. Those
47// memory statistics are deposited into a histogram, and the log finalization
48// code is then called. In the finalization, a call to a Histogram server
49// acquires a list of all local histograms that have been flagged for upload
jar@chromium.org281d2882009-01-20 20:32:4250// to the UMA server. The finalization also acquires a the most recent number
51// of page loads, along with any counts of renderer or plugin crashes.
initial.commit09911bf2008-07-26 23:55:2952//
53// When the browser shuts down, there will typically be a fragment of an ongoing
54// log that has not yet been transmitted. At shutdown time, that fragment
55// is closed (including snapshotting histograms), and converted to text. Note
56// that memory stats are not gathered during shutdown, as gathering *might* be
57// too time consuming. The textual representation of the fragment of the
58// ongoing log is then stored persistently as a string in the PrefServices, for
59// potential transmission during a future run of the product.
60//
61// There are two slightly abnormal shutdown conditions. There is a
62// "disconnected scenario," and a "really fast startup and shutdown" scenario.
63// In the "never connected" situation, the user has (during the running of the
64// process) never established an internet connection. As a result, attempts to
65// transmit the initial log have failed, and a lot(?) of data has accumulated in
66// the ongoing log (which didn't yet get closed, because there was never even a
67// contemplation of sending it). There is also a kindred "lost connection"
68// situation, where a loss of connection prevented an ongoing log from being
69// transmitted, and a (still open) log was stuck accumulating a lot(?) of data,
70// while the earlier log retried its transmission. In both of these
71// disconnected situations, two logs need to be, and are, persistently stored
72// for future transmission.
73//
74// The other unusual shutdown condition, termed "really fast startup and
75// shutdown," involves the deliberate user termination of the process before
76// the initial log is even formed or transmitted. In that situation, no logging
77// is done, but the historical crash statistics remain (unlogged) for inclusion
78// in a future run's initial log. (i.e., we don't lose crash stats).
79//
80// With the above overview, we can now describe the state machine's various
81// stats, based on the State enum specified in the state_ member. Those states
82// are:
83//
84// INITIALIZED, // Constructor was called.
avi@google.com28ab7f92009-01-06 21:39:0485// PLUGIN_LIST_REQUESTED, // Waiting for plugin list to be loaded.
initial.commit09911bf2008-07-26 23:55:2986// PLUGIN_LIST_ARRIVED, // Waiting for timer to send initial log.
87// INITIAL_LOG_READY, // Initial log generated, and waiting for reply.
88// SEND_OLD_INITIAL_LOGS, // Sending unsent logs from previous session.
89// SENDING_OLD_LOGS, // Sending unsent logs from previous session.
90// SENDING_CURRENT_LOGS, // Sending standard current logs as they accrue.
91//
92// In more detail, we have:
93//
94// INITIALIZED, // Constructor was called.
95// The MS has been constructed, but has taken no actions to compose the
96// initial log.
97//
avi@google.com28ab7f92009-01-06 21:39:0498// PLUGIN_LIST_REQUESTED, // Waiting for plugin list to be loaded.
initial.commit09911bf2008-07-26 23:55:2999// Typically about 30 seconds after startup, a task is sent to a second thread
100// to get the list of plugins. That task will (when complete) make an async
101// callback (via a Task) to indicate the completion.
102//
103// PLUGIN_LIST_ARRIVED, // Waiting for timer to send initial log.
104// The callback has arrived, and it is now possible for an initial log to be
105// created. This callback typically arrives back less than one second after
106// the task is dispatched.
107//
108// INITIAL_LOG_READY, // Initial log generated, and waiting for reply.
109// This state is entered only after an initial log has been composed, and
110// prepared for transmission. It is also the case that any previously unsent
111// logs have been loaded into instance variables for possible transmission.
112//
113// SEND_OLD_INITIAL_LOGS, // Sending unsent logs from previous session.
114// This state indicates that the initial log for this session has been
115// successfully sent and it is now time to send any "initial logs" that were
116// saved from previous sessions. Most commonly, there are none, but all old
117// logs that were "initial logs" must be sent before this state is exited.
118//
119// SENDING_OLD_LOGS, // Sending unsent logs from previous session.
120// This state indicates that there are no more unsent initial logs, and now any
121// ongoing logs from previous sessions should be transmitted. All such logs
122// will be transmitted before exiting this state, and proceeding with ongoing
123// logs from the current session (see next state).
124//
125// SENDING_CURRENT_LOGS, // Sending standard current logs as they accrue.
jar@google.com0b33f80b2008-12-17 21:34:36126// Current logs are being accumulated. Typically every 20 minutes a log is
initial.commit09911bf2008-07-26 23:55:29127// closed and finalized for transmission, at the same time as a new log is
128// started.
129//
130// The progression through the above states is simple, and sequential, in the
131// most common use cases. States proceed from INITIAL to SENDING_CURRENT_LOGS,
132// and remain in the latter until shutdown.
133//
134// The one unusual case is when the user asks that we stop logging. When that
135// happens, any pending (transmission in progress) log is pushed into the list
136// of old unsent logs (the appropriate list, depending on whether it is an
137// initial log, or an ongoing log). An addition, any log that is currently
138// accumulating is also finalized, and pushed into the unsent log list. With
jar@chromium.org281d2882009-01-20 20:32:42139// those pushes performed, we regress back to the SEND_OLD_INITIAL_LOGS state in
initial.commit09911bf2008-07-26 23:55:29140// case the user enables log recording again during this session. This way
141// anything we have "pushed back" will be sent automatically if/when we progress
142// back to SENDING_CURRENT_LOG state.
143//
144// Also note that whenever the member variables containing unsent logs are
145// modified (i.e., when we send an old log), we mirror the list of logs into
146// the PrefServices. This ensures that IF we crash, we won't start up and
147// retransmit our old logs again.
148//
149// Due to race conditions, it is always possible that a log file could be sent
150// twice. For example, if a log file is sent, but not yet acknowledged by
151// the external server, and the user shuts down, then a copy of the log may be
152// saved for re-transmission. These duplicates could be filtered out server
jar@chromium.org281d2882009-01-20 20:32:42153// side, but are not expected to be a significant problem.
initial.commit09911bf2008-07-26 23:55:29154//
155//
156//------------------------------------------------------------------------------
157
maruel@chromium.org40bcc302009-03-02 20:50:39158#include "chrome/browser/metrics/metrics_service.h"
159
paul@chromium.orgdc6f4962009-02-13 01:25:50160#if defined(OS_WIN)
initial.commit09911bf2008-07-26 23:55:29161#include <windows.h>
maruel@chromium.org40bcc302009-03-02 20:50:39162#include <objbase.h>
paul@chromium.orgdc6f4962009-02-13 01:25:50163#endif
initial.commit09911bf2008-07-26 23:55:29164
agl@chromium.org7ef52bf2009-08-06 19:04:50165#if defined(USE_SYSTEM_LIBBZ2)
166#include <bzlib.h>
167#else
168#include "third_party/bzip2/bzlib.h"
169#endif
170
pkasting@chromium.org4d022ff2009-10-23 18:47:09171#include "base/thread.h"
sky@google.comd8e41ed2008-09-11 15:22:32172#include "chrome/browser/bookmarks/bookmark_model.h"
initial.commit09911bf2008-07-26 23:55:29173#include "chrome/browser/browser_list.h"
174#include "chrome/browser/browser_process.h"
175#include "chrome/browser/load_notification_details.h"
176#include "chrome/browser/memory_details.h"
phajdan.jr@chromium.org7c927b62010-02-24 09:54:13177#include "chrome/browser/metrics/histogram_synchronizer.h"
phajdan.jr@chromium.org052313b2010-02-19 09:43:08178#include "chrome/browser/pref_service.h"
initial.commit09911bf2008-07-26 23:55:29179#include "chrome/browser/profile.h"
brettw@chromium.org8c8657d62009-01-16 18:31:26180#include "chrome/browser/renderer_host/render_process_host.h"
ben@chromium.orgd54e03a52009-01-16 00:31:04181#include "chrome/browser/search_engines/template_url_model.h"
kuchhal@chromium.org157d5472009-11-05 22:31:03182#include "chrome/common/child_process_logging.h"
jar@chromium.org92745242009-06-12 16:52:21183#include "chrome/common/chrome_switches.h"
brettw@chromium.orgbfd04a62009-02-01 18:16:56184#include "chrome/common/notification_service.h"
initial.commit09911bf2008-07-26 23:55:29185#include "chrome/common/pref_names.h"
jam@chromium.orge09ba552009-02-05 03:26:29186#include "chrome/common/render_messages.h"
jam@chromium.org35fa6a22009-08-15 00:04:01187#include "webkit/glue/plugins/plugin_list.h"
initial.commit09911bf2008-07-26 23:55:29188
pkasting@chromium.org4d022ff2009-10-23 18:47:09189#if !defined(OS_WIN)
190#include "base/rand_util.h"
191#endif
192
phajdan.jr@chromium.orge06131d2010-02-10 18:40:33193// TODO(port): port browser_distribution.h.
194#if !defined(OS_POSIX)
kuchhal@chromium.org79bf0b72009-04-27 21:30:55195#include "chrome/installer/util/browser_distribution.h"
paul@chromium.orgdc6f4962009-02-13 01:25:50196#endif
197
rvargas@google.com5ccaa412009-11-13 22:00:16198#if defined(OS_CHROMEOS)
199#include "chrome/browser/chromeos/external_metrics.h"
200#endif
201
dsh@google.come1acf6f2008-10-27 20:43:33202using base::Time;
203using base::TimeDelta;
204
initial.commit09911bf2008-07-26 23:55:29205// Check to see that we're being called on only one thread.
206static bool IsSingleThreaded();
207
initial.commit09911bf2008-07-26 23:55:29208static const char kMetricsType[] = "application/vnd.mozilla.metrics.bz2";
209
210// The delay, in seconds, after startup before sending the first log message.
petersont@google.com252873ef2008-08-04 21:59:45211static const int kInitialInterlogDuration = 60; // one minute
212
jar@chromium.orgc9a3ef82009-05-28 22:02:46213// This specifies the amount of time to wait for all renderers to send their
214// data.
215static const int kMaxHistogramGatheringWaitDuration = 60000; // 60 seconds.
216
petersont@google.com252873ef2008-08-04 21:59:45217// The default maximum number of events in a log uploaded to the UMA server.
jar@google.com0b33f80b2008-12-17 21:34:36218static const int kInitialEventLimit = 2400;
jar@google.com68475e602008-08-22 03:21:15219
220// If an upload fails, and the transmission was over this byte count, then we
221// will discard the log, and not try to retransmit it. We also don't persist
222// the log to the prefs for transmission during the next chrome session if this
223// limit is exceeded.
224static const int kUploadLogAvoidRetransmitSize = 50000;
initial.commit09911bf2008-07-26 23:55:29225
226// When we have logs from previous Chrome sessions to send, how long should we
227// delay (in seconds) between each log transmission.
228static const int kUnsentLogDelay = 15; // 15 seconds
229
230// Minimum time a log typically exists before sending, in seconds.
231// This number is supplied by the server, but until we parse it out of a server
232// response, we use this duration to specify how long we should wait before
233// sending the next log. If the channel is busy, such as when there is a
234// failure during an attempt to transmit a previous log, then a log may wait
jar@chromium.org2fe42fe2010-05-07 19:22:39235// (and continue to accrue new log entries) for a much greater period of time.
236static const int kMinSecondsPerLog = 30 * 60; // Thirty minutes.
initial.commit09911bf2008-07-26 23:55:29237
initial.commit09911bf2008-07-26 23:55:29238// When we don't succeed at transmitting a log to a server, we progressively
239// wait longer and longer before sending the next log. This backoff process
240// help reduce load on the server, and makes the amount of backoff vary between
241// clients so that a collision (server overload?) on retransmit is less likely.
242// The following is the constant we use to expand that inter-log duration.
243static const double kBackoff = 1.1;
244// We limit the maximum backoff to be no greater than some multiple of the
245// default kMinSecondsPerLog. The following is that maximum ratio.
246static const int kMaxBackoff = 10;
247
248// Interval, in seconds, between state saves.
249static const int kSaveStateInterval = 5 * 60; // five minutes
250
251// The number of "initial" logs we're willing to save, and hope to send during
252// a future Chrome session. Initial logs contain crash stats, and are pretty
253// small.
254static const size_t kMaxInitialLogsPersisted = 20;
255
256// The number of ongoing logs we're willing to save persistently, and hope to
jar@chromium.org281d2882009-01-20 20:32:42257// send during a this or future sessions. Note that each log may be pretty
initial.commit09911bf2008-07-26 23:55:29258// large, as presumably the related "initial" log wasn't sent (probably nothing
259// was, as the user was probably off-line). As a result, the log probably kept
260// accumulating while the "initial" log was stalled (pending_), and couldn't be
261// sent. As a result, we don't want to save too many of these mega-logs.
262// A "standard shutdown" will create a small log, including just the data that
263// was not yet been transmitted, and that is normal (to have exactly one
264// ongoing_log_ at startup).
jar@chromium.org281d2882009-01-20 20:32:42265static const size_t kMaxOngoingLogsPersisted = 8;
initial.commit09911bf2008-07-26 23:55:29266
267
268// Handles asynchronous fetching of memory details.
269// Will run the provided task after finished.
270class MetricsMemoryDetails : public MemoryDetails {
271 public:
272 explicit MetricsMemoryDetails(Task* completion) : completion_(completion) {}
273
274 virtual void OnDetailsAvailable() {
275 MessageLoop::current()->PostTask(FROM_HERE, completion_);
276 }
277
278 private:
jam@chromium.orge6e6ba42009-11-07 01:56:19279 ~MetricsMemoryDetails() {}
280
initial.commit09911bf2008-07-26 23:55:29281 Task* completion_;
tfarina@chromium.org4d818fee2010-06-06 13:32:27282 DISALLOW_COPY_AND_ASSIGN(MetricsMemoryDetails);
initial.commit09911bf2008-07-26 23:55:29283};
284
jamesr@chromium.org7f2e792e2009-11-30 23:18:29285class MetricsService::GetPluginListTaskComplete : public Task {
jam@chromium.org35fa6a22009-08-15 00:04:01286 public:
jamesr@chromium.org7f2e792e2009-11-30 23:18:29287 explicit GetPluginListTaskComplete(
288 const std::vector<WebPluginInfo>& plugins) : plugins_(plugins) { }
289 virtual void Run() {
290 g_browser_process->metrics_service()->OnGetPluginListTaskComplete(plugins_);
initial.commit09911bf2008-07-26 23:55:29291 }
jam@chromium.org35fa6a22009-08-15 00:04:01292
jamesr@chromium.org7f2e792e2009-11-30 23:18:29293 private:
294 std::vector<WebPluginInfo> plugins_;
initial.commit09911bf2008-07-26 23:55:29295};
296
jamesr@chromium.org7f2e792e2009-11-30 23:18:29297class MetricsService::GetPluginListTask : public Task {
298 public:
299 explicit GetPluginListTask(MessageLoop* callback_loop)
300 : callback_loop_(callback_loop) {}
301
302 virtual void Run() {
303 std::vector<WebPluginInfo> plugins;
304 NPAPI::PluginList::Singleton()->GetPlugins(false, &plugins);
305
306 callback_loop_->PostTask(
307 FROM_HERE, new GetPluginListTaskComplete(plugins));
308 }
309
310 private:
311 MessageLoop* callback_loop_;
312};
evan@chromium.org90d41372009-11-30 21:52:32313
initial.commit09911bf2008-07-26 23:55:29314// static
315void MetricsService::RegisterPrefs(PrefService* local_state) {
316 DCHECK(IsSingleThreaded());
317 local_state->RegisterStringPref(prefs::kMetricsClientID, L"");
robertshield@google.com0bb1a622009-03-04 03:22:32318 local_state->RegisterInt64Pref(prefs::kMetricsClientIDTimestamp, 0);
319 local_state->RegisterInt64Pref(prefs::kStabilityLaunchTimeSec, 0);
320 local_state->RegisterInt64Pref(prefs::kStabilityLastTimestampSec, 0);
jar@chromium.org541f77922009-02-23 21:14:38321 local_state->RegisterStringPref(prefs::kStabilityStatsVersion, L"");
jar@chromium.org225c50842010-01-19 21:19:13322 local_state->RegisterInt64Pref(prefs::kStabilityStatsBuildTime, 0);
initial.commit09911bf2008-07-26 23:55:29323 local_state->RegisterBooleanPref(prefs::kStabilityExitedCleanly, true);
324 local_state->RegisterBooleanPref(prefs::kStabilitySessionEndCompleted, true);
325 local_state->RegisterIntegerPref(prefs::kMetricsSessionID, -1);
326 local_state->RegisterIntegerPref(prefs::kStabilityLaunchCount, 0);
327 local_state->RegisterIntegerPref(prefs::kStabilityCrashCount, 0);
328 local_state->RegisterIntegerPref(prefs::kStabilityIncompleteSessionEndCount,
329 0);
330 local_state->RegisterIntegerPref(prefs::kStabilityPageLoadCount, 0);
initial.commit09911bf2008-07-26 23:55:29331 local_state->RegisterIntegerPref(prefs::kStabilityRendererCrashCount, 0);
asargent@chromium.org1f085622009-12-04 05:33:45332 local_state->RegisterIntegerPref(prefs::kStabilityExtensionRendererCrashCount,
333 0);
initial.commit09911bf2008-07-26 23:55:29334 local_state->RegisterIntegerPref(prefs::kStabilityRendererHangCount, 0);
asargent@chromium.org1f085622009-12-04 05:33:45335 local_state->RegisterIntegerPref(prefs::kStabilityChildProcessCrashCount, 0);
cpu@google.come73c01972008-08-13 00:18:24336 local_state->RegisterIntegerPref(prefs::kStabilityBreakpadRegistrationFail,
337 0);
338 local_state->RegisterIntegerPref(prefs::kStabilityBreakpadRegistrationSuccess,
339 0);
340 local_state->RegisterIntegerPref(prefs::kStabilityDebuggerPresent, 0);
341 local_state->RegisterIntegerPref(prefs::kStabilityDebuggerNotPresent, 0);
342
initial.commit09911bf2008-07-26 23:55:29343 local_state->RegisterDictionaryPref(prefs::kProfileMetrics);
344 local_state->RegisterIntegerPref(prefs::kNumBookmarksOnBookmarkBar, 0);
345 local_state->RegisterIntegerPref(prefs::kNumFoldersOnBookmarkBar, 0);
346 local_state->RegisterIntegerPref(prefs::kNumBookmarksInOtherBookmarkFolder,
347 0);
348 local_state->RegisterIntegerPref(prefs::kNumFoldersInOtherBookmarkFolder, 0);
349 local_state->RegisterIntegerPref(prefs::kNumKeywords, 0);
350 local_state->RegisterListPref(prefs::kMetricsInitialLogs);
351 local_state->RegisterListPref(prefs::kMetricsOngoingLogs);
robertshield@google.com0bb1a622009-03-04 03:22:32352
353 local_state->RegisterInt64Pref(prefs::kUninstallMetricsPageLoadCount, 0);
354 local_state->RegisterInt64Pref(prefs::kUninstallLaunchCount, 0);
robertshield@google.com6b5f21d2009-04-13 17:01:35355 local_state->RegisterInt64Pref(prefs::kUninstallMetricsInstallDate, 0);
robertshield@google.com0bb1a622009-03-04 03:22:32356 local_state->RegisterInt64Pref(prefs::kUninstallMetricsUptimeSec, 0);
357 local_state->RegisterInt64Pref(prefs::kUninstallLastLaunchTimeSec, 0);
358 local_state->RegisterInt64Pref(prefs::kUninstallLastObservedRunTimeSec, 0);
initial.commit09911bf2008-07-26 23:55:29359}
360
jar@chromium.org541f77922009-02-23 21:14:38361// static
362void MetricsService::DiscardOldStabilityStats(PrefService* local_state) {
363 local_state->SetBoolean(prefs::kStabilityExitedCleanly, true);
jar@chromium.orgc9abf242009-07-18 06:00:38364 local_state->SetBoolean(prefs::kStabilitySessionEndCompleted, true);
jar@chromium.org541f77922009-02-23 21:14:38365
366 local_state->SetInteger(prefs::kStabilityIncompleteSessionEndCount, 0);
367 local_state->SetInteger(prefs::kStabilityBreakpadRegistrationSuccess, 0);
368 local_state->SetInteger(prefs::kStabilityBreakpadRegistrationFail, 0);
369 local_state->SetInteger(prefs::kStabilityDebuggerPresent, 0);
370 local_state->SetInteger(prefs::kStabilityDebuggerNotPresent, 0);
371
372 local_state->SetInteger(prefs::kStabilityLaunchCount, 0);
373 local_state->SetInteger(prefs::kStabilityCrashCount, 0);
374
375 local_state->SetInteger(prefs::kStabilityPageLoadCount, 0);
376 local_state->SetInteger(prefs::kStabilityRendererCrashCount, 0);
377 local_state->SetInteger(prefs::kStabilityRendererHangCount, 0);
378
jar@chromium.org9165f742010-03-10 22:55:01379 local_state->SetInt64(prefs::kStabilityLaunchTimeSec, 0);
380 local_state->SetInt64(prefs::kStabilityLastTimestampSec, 0);
jar@chromium.org541f77922009-02-23 21:14:38381
382 local_state->ClearPref(prefs::kStabilityPluginStats);
jar@chromium.orgae155cb92009-06-19 06:10:37383
384 ListValue* unsent_initial_logs = local_state->GetMutableList(
385 prefs::kMetricsInitialLogs);
386 unsent_initial_logs->Clear();
387
388 ListValue* unsent_ongoing_logs = local_state->GetMutableList(
389 prefs::kMetricsOngoingLogs);
390 unsent_ongoing_logs->Clear();
jar@chromium.org541f77922009-02-23 21:14:38391}
392
initial.commit09911bf2008-07-26 23:55:29393MetricsService::MetricsService()
petersont@google.comd01b8732008-10-16 02:18:07394 : recording_active_(false),
395 reporting_active_(false),
396 user_permits_upload_(false),
397 server_permits_upload_(true),
398 state_(INITIALIZED),
initial.commit09911bf2008-07-26 23:55:29399 pending_log_(NULL),
mark@chromium.org9ffcccf42009-09-15 22:19:18400 pending_log_text_(),
initial.commit09911bf2008-07-26 23:55:29401 current_fetch_(NULL),
402 current_log_(NULL),
petersont@google.comd01b8732008-10-16 02:18:07403 idle_since_last_transmission_(false),
initial.commit09911bf2008-07-26 23:55:29404 next_window_id_(0),
maruel@chromium.org40bcc302009-03-02 20:50:39405 ALLOW_THIS_IN_INITIALIZER_LIST(log_sender_factory_(this)),
406 ALLOW_THIS_IN_INITIALIZER_LIST(state_saver_factory_(this)),
initial.commit09911bf2008-07-26 23:55:29407 logged_samples_(),
petersont@google.com252873ef2008-08-04 21:59:45408 interlog_duration_(TimeDelta::FromSeconds(kInitialInterlogDuration)),
petersont@google.comd01b8732008-10-16 02:18:07409 log_event_limit_(kInitialEventLimit),
initial.commit09911bf2008-07-26 23:55:29410 timer_pending_(false) {
411 DCHECK(IsSingleThreaded());
412 InitializeMetricsState();
413}
414
415MetricsService::~MetricsService() {
416 SetRecording(false);
kuchhal@chromium.orgd8bc79bf2009-01-28 01:17:58417 if (pending_log_) {
418 delete pending_log_;
419 pending_log_ = NULL;
420 }
421 if (current_log_) {
422 delete current_log_;
423 current_log_ = NULL;
424 }
initial.commit09911bf2008-07-26 23:55:29425}
426
petersont@google.comd01b8732008-10-16 02:18:07427void MetricsService::SetUserPermitsUpload(bool enabled) {
428 HandleIdleSinceLastTransmission(false);
429 user_permits_upload_ = enabled;
430}
431
432void MetricsService::Start() {
433 SetRecording(true);
434 SetReporting(true);
435}
436
437void MetricsService::StartRecordingOnly() {
438 SetRecording(true);
439 SetReporting(false);
440}
441
442void MetricsService::Stop() {
443 SetReporting(false);
444 SetRecording(false);
445}
446
initial.commit09911bf2008-07-26 23:55:29447void MetricsService::SetRecording(bool enabled) {
448 DCHECK(IsSingleThreaded());
449
petersont@google.comd01b8732008-10-16 02:18:07450 if (enabled == recording_active_)
initial.commit09911bf2008-07-26 23:55:29451 return;
452
453 if (enabled) {
jar@chromium.orgb0c819f2009-03-08 04:52:15454 if (client_id_.empty()) {
455 PrefService* pref = g_browser_process->local_state();
456 DCHECK(pref);
457 client_id_ = WideToUTF8(pref->GetString(prefs::kMetricsClientID));
458 if (client_id_.empty()) {
459 client_id_ = GenerateClientID();
460 pref->SetString(prefs::kMetricsClientID, UTF8ToWide(client_id_));
461
462 // Might as well make a note of how long this ID has existed
463 pref->SetString(prefs::kMetricsClientIDTimestamp,
464 Int64ToWString(Time::Now().ToTimeT()));
465 }
466 }
kuchhal@chromium.org157d5472009-11-05 22:31:03467 child_process_logging::SetClientId(client_id_);
initial.commit09911bf2008-07-26 23:55:29468 StartRecording();
pkasting@chromium.org005ef3e2009-05-22 20:55:46469
470 registrar_.Add(this, NotificationType::BROWSER_OPENED,
471 NotificationService::AllSources());
472 registrar_.Add(this, NotificationType::BROWSER_CLOSED,
473 NotificationService::AllSources());
474 registrar_.Add(this, NotificationType::USER_ACTION,
475 NotificationService::AllSources());
476 registrar_.Add(this, NotificationType::TAB_PARENTED,
477 NotificationService::AllSources());
478 registrar_.Add(this, NotificationType::TAB_CLOSING,
479 NotificationService::AllSources());
480 registrar_.Add(this, NotificationType::LOAD_START,
481 NotificationService::AllSources());
482 registrar_.Add(this, NotificationType::LOAD_STOP,
483 NotificationService::AllSources());
kkania@chromium.orgcd69619b2010-05-05 02:41:38484 registrar_.Add(this, NotificationType::RENDERER_PROCESS_CLOSED,
pkasting@chromium.org005ef3e2009-05-22 20:55:46485 NotificationService::AllSources());
486 registrar_.Add(this, NotificationType::RENDERER_PROCESS_HANG,
487 NotificationService::AllSources());
488 registrar_.Add(this, NotificationType::CHILD_PROCESS_HOST_CONNECTED,
489 NotificationService::AllSources());
490 registrar_.Add(this, NotificationType::CHILD_INSTANCE_CREATED,
491 NotificationService::AllSources());
492 registrar_.Add(this, NotificationType::CHILD_PROCESS_CRASHED,
493 NotificationService::AllSources());
494 registrar_.Add(this, NotificationType::TEMPLATE_URL_MODEL_LOADED,
495 NotificationService::AllSources());
496 registrar_.Add(this, NotificationType::OMNIBOX_OPENED_URL,
497 NotificationService::AllSources());
498 registrar_.Add(this, NotificationType::BOOKMARK_MODEL_LOADED,
499 NotificationService::AllSources());
initial.commit09911bf2008-07-26 23:55:29500 } else {
pkasting@chromium.org005ef3e2009-05-22 20:55:46501 registrar_.RemoveAll();
initial.commit09911bf2008-07-26 23:55:29502 PushPendingLogsToUnsentLists();
503 DCHECK(!pending_log());
504 if (state_ > INITIAL_LOG_READY && unsent_logs())
505 state_ = SEND_OLD_INITIAL_LOGS;
506 }
petersont@google.comd01b8732008-10-16 02:18:07507 recording_active_ = enabled;
initial.commit09911bf2008-07-26 23:55:29508}
509
petersont@google.comd01b8732008-10-16 02:18:07510bool MetricsService::recording_active() const {
initial.commit09911bf2008-07-26 23:55:29511 DCHECK(IsSingleThreaded());
petersont@google.comd01b8732008-10-16 02:18:07512 return recording_active_;
initial.commit09911bf2008-07-26 23:55:29513}
514
petersont@google.comd01b8732008-10-16 02:18:07515void MetricsService::SetReporting(bool enable) {
516 if (reporting_active_ != enable) {
517 reporting_active_ = enable;
518 if (reporting_active_)
initial.commit09911bf2008-07-26 23:55:29519 StartLogTransmissionTimer();
520 }
petersont@google.comd01b8732008-10-16 02:18:07521}
522
523bool MetricsService::reporting_active() const {
524 DCHECK(IsSingleThreaded());
525 return reporting_active_;
initial.commit09911bf2008-07-26 23:55:29526}
527
528void MetricsService::Observe(NotificationType type,
529 const NotificationSource& source,
530 const NotificationDetails& details) {
531 DCHECK(current_log_);
532 DCHECK(IsSingleThreaded());
533
534 if (!CanLogNotification(type, source, details))
535 return;
536
brettw@chromium.orgbfd04a62009-02-01 18:16:56537 switch (type.value) {
538 case NotificationType::USER_ACTION:
evan@chromium.orgafe3a1672009-11-17 19:04:12539 current_log_->RecordUserAction(*Details<const char*>(details).ptr());
initial.commit09911bf2008-07-26 23:55:29540 break;
541
brettw@chromium.orgbfd04a62009-02-01 18:16:56542 case NotificationType::BROWSER_OPENED:
543 case NotificationType::BROWSER_CLOSED:
initial.commit09911bf2008-07-26 23:55:29544 LogWindowChange(type, source, details);
545 break;
546
brettw@chromium.orgbfd04a62009-02-01 18:16:56547 case NotificationType::TAB_PARENTED:
548 case NotificationType::TAB_CLOSING:
initial.commit09911bf2008-07-26 23:55:29549 LogWindowChange(type, source, details);
550 break;
551
brettw@chromium.orgbfd04a62009-02-01 18:16:56552 case NotificationType::LOAD_STOP:
initial.commit09911bf2008-07-26 23:55:29553 LogLoadComplete(type, source, details);
554 break;
555
brettw@chromium.orgbfd04a62009-02-01 18:16:56556 case NotificationType::LOAD_START:
initial.commit09911bf2008-07-26 23:55:29557 LogLoadStarted();
558 break;
559
kkania@chromium.orgcd69619b2010-05-05 02:41:38560 case NotificationType::RENDERER_PROCESS_CLOSED:
asargent@chromium.org1f085622009-12-04 05:33:45561 {
kkania@chromium.orgcd69619b2010-05-05 02:41:38562 RenderProcessHost::RendererClosedDetails* process_details =
563 Details<RenderProcessHost::RendererClosedDetails>(details).ptr();
564 if (process_details->did_crash) {
565 if (process_details->was_extension_renderer) {
566 LogExtensionRendererCrash();
567 } else {
568 LogRendererCrash();
569 }
570 }
asargent@chromium.org1f085622009-12-04 05:33:45571 }
initial.commit09911bf2008-07-26 23:55:29572 break;
573
brettw@chromium.orgbfd04a62009-02-01 18:16:56574 case NotificationType::RENDERER_PROCESS_HANG:
initial.commit09911bf2008-07-26 23:55:29575 LogRendererHang();
576 break;
577
jam@chromium.orga27a9382009-02-11 23:55:10578 case NotificationType::CHILD_PROCESS_HOST_CONNECTED:
579 case NotificationType::CHILD_PROCESS_CRASHED:
580 case NotificationType::CHILD_INSTANCE_CREATED:
581 LogChildProcessChange(type, source, details);
initial.commit09911bf2008-07-26 23:55:29582 break;
583
brettw@chromium.orgbfd04a62009-02-01 18:16:56584 case NotificationType::TEMPLATE_URL_MODEL_LOADED:
initial.commit09911bf2008-07-26 23:55:29585 LogKeywords(Source<TemplateURLModel>(source).ptr());
586 break;
587
brettw@chromium.orgbfd04a62009-02-01 18:16:56588 case NotificationType::OMNIBOX_OPENED_URL:
initial.commit09911bf2008-07-26 23:55:29589 current_log_->RecordOmniboxOpenedURL(
590 *Details<AutocompleteLog>(details).ptr());
591 break;
592
tim@chromium.orgb61236c62009-04-09 22:43:55593 case NotificationType::BOOKMARK_MODEL_LOADED: {
594 Profile* p = Source<Profile>(source).ptr();
595 if (p)
596 LogBookmarks(p->GetBookmarkModel());
initial.commit09911bf2008-07-26 23:55:29597 break;
tim@chromium.orgb61236c62009-04-09 22:43:55598 }
initial.commit09911bf2008-07-26 23:55:29599 default:
jar@chromium.orgb42c5e42010-06-03 20:43:25600 LOG(DFATAL);
initial.commit09911bf2008-07-26 23:55:29601 break;
602 }
petersont@google.comd01b8732008-10-16 02:18:07603
604 HandleIdleSinceLastTransmission(false);
605
606 if (current_log_)
jar@chromium.org281d2882009-01-20 20:32:42607 DLOG(INFO) << "METRICS: NUMBER OF EVENTS = " << current_log_->num_events();
petersont@google.comd01b8732008-10-16 02:18:07608}
609
610void MetricsService::HandleIdleSinceLastTransmission(bool in_idle) {
611 // If there wasn't a lot of action, maybe the computer was asleep, in which
612 // case, the log transmissions should have stopped. Here we start them up
613 // again.
pkasting@chromium.orgcac78842008-11-27 01:02:20614 if (!in_idle && idle_since_last_transmission_)
615 StartLogTransmissionTimer();
616 idle_since_last_transmission_ = in_idle;
initial.commit09911bf2008-07-26 23:55:29617}
618
619void MetricsService::RecordCleanShutdown() {
620 RecordBooleanPrefValue(prefs::kStabilityExitedCleanly, true);
621}
622
623void MetricsService::RecordStartOfSessionEnd() {
624 RecordBooleanPrefValue(prefs::kStabilitySessionEndCompleted, false);
625}
626
627void MetricsService::RecordCompletedSessionEnd() {
628 RecordBooleanPrefValue(prefs::kStabilitySessionEndCompleted, true);
629}
630
cpu@google.come73c01972008-08-13 00:18:24631void MetricsService:: RecordBreakpadRegistration(bool success) {
jar@google.com68475e602008-08-22 03:21:15632 if (!success)
cpu@google.come73c01972008-08-13 00:18:24633 IncrementPrefValue(prefs::kStabilityBreakpadRegistrationFail);
634 else
635 IncrementPrefValue(prefs::kStabilityBreakpadRegistrationSuccess);
636}
637
638void MetricsService::RecordBreakpadHasDebugger(bool has_debugger) {
639 if (!has_debugger)
640 IncrementPrefValue(prefs::kStabilityDebuggerNotPresent);
641 else
jar@google.com68475e602008-08-22 03:21:15642 IncrementPrefValue(prefs::kStabilityDebuggerPresent);
cpu@google.come73c01972008-08-13 00:18:24643}
644
initial.commit09911bf2008-07-26 23:55:29645//------------------------------------------------------------------------------
646// private methods
647//------------------------------------------------------------------------------
648
649
650//------------------------------------------------------------------------------
651// Initialization methods
652
653void MetricsService::InitializeMetricsState() {
kuchhal@chromium.org79bf0b72009-04-27 21:30:55654#if defined(OS_POSIX)
655 server_url_ = L"https://clients4.google.com/firefox/metrics/collect";
656#else
657 BrowserDistribution* dist = BrowserDistribution::GetDistribution();
658 server_url_ = dist->GetStatsServerURL();
659#endif
660
initial.commit09911bf2008-07-26 23:55:29661 PrefService* pref = g_browser_process->local_state();
662 DCHECK(pref);
663
jar@chromium.org225c50842010-01-19 21:19:13664 if ((pref->GetInt64(prefs::kStabilityStatsBuildTime)
665 != MetricsLog::GetBuildTime()) ||
666 (WideToUTF8(pref->GetString(prefs::kStabilityStatsVersion))
667 != MetricsLog::GetVersionString())) {
jar@chromium.org541f77922009-02-23 21:14:38668 // This is a new version, so we don't want to confuse the stats about the
669 // old version with info that we upload.
670 DiscardOldStabilityStats(pref);
671 pref->SetString(prefs::kStabilityStatsVersion,
672 UTF8ToWide(MetricsLog::GetVersionString()));
jar@chromium.org225c50842010-01-19 21:19:13673 pref->SetInt64(prefs::kStabilityStatsBuildTime,
674 MetricsLog::GetBuildTime());
jar@chromium.org541f77922009-02-23 21:14:38675 }
676
initial.commit09911bf2008-07-26 23:55:29677 // Update session ID
678 session_id_ = pref->GetInteger(prefs::kMetricsSessionID);
679 ++session_id_;
680 pref->SetInteger(prefs::kMetricsSessionID, session_id_);
681
initial.commit09911bf2008-07-26 23:55:29682 // Stability bookkeeping
cpu@google.come73c01972008-08-13 00:18:24683 IncrementPrefValue(prefs::kStabilityLaunchCount);
initial.commit09911bf2008-07-26 23:55:29684
cpu@google.come73c01972008-08-13 00:18:24685 if (!pref->GetBoolean(prefs::kStabilityExitedCleanly)) {
686 IncrementPrefValue(prefs::kStabilityCrashCount);
initial.commit09911bf2008-07-26 23:55:29687 }
cpu@google.come73c01972008-08-13 00:18:24688
689 // This will be set to 'true' if we exit cleanly.
initial.commit09911bf2008-07-26 23:55:29690 pref->SetBoolean(prefs::kStabilityExitedCleanly, false);
691
cpu@google.come73c01972008-08-13 00:18:24692 if (!pref->GetBoolean(prefs::kStabilitySessionEndCompleted)) {
693 IncrementPrefValue(prefs::kStabilityIncompleteSessionEndCount);
jar@chromium.orgc9abf242009-07-18 06:00:38694 // This is marked false when we get a WM_ENDSESSION.
695 pref->SetBoolean(prefs::kStabilitySessionEndCompleted, true);
initial.commit09911bf2008-07-26 23:55:29696 }
initial.commit09911bf2008-07-26 23:55:29697
jar@chromium.org9165f742010-03-10 22:55:01698 // Initialize uptime counters.
699 int64 startup_uptime = MetricsLog::GetIncrementalUptime(pref);
700 DCHECK(0 == startup_uptime);
701 // For backwards compatibility, leave this intact in case Omaha is checking
702 // them. prefs::kStabilityLastTimestampSec may also be useless now.
703 // TODO(jar): Delete these if they have no uses.
robertshield@google.com0bb1a622009-03-04 03:22:32704 pref->SetInt64(prefs::kStabilityLaunchTimeSec, Time::Now().ToTimeT());
705
706 // Bookkeeping for the uninstall metrics.
707 IncrementLongPrefsValue(prefs::kUninstallLaunchCount);
initial.commit09911bf2008-07-26 23:55:29708
709 // Save profile metrics.
710 PrefService* prefs = g_browser_process->local_state();
711 if (prefs) {
712 // Remove the current dictionary and store it for use when sending data to
713 // server. By removing the value we prune potentially dead profiles
714 // (and keys). All valid values are added back once services startup.
715 const DictionaryValue* profile_dictionary =
716 prefs->GetDictionary(prefs::kProfileMetrics);
717 if (profile_dictionary) {
718 // Do a deep copy of profile_dictionary since ClearPref will delete it.
719 profile_dictionary_.reset(static_cast<DictionaryValue*>(
720 profile_dictionary->DeepCopy()));
721 prefs->ClearPref(prefs::kProfileMetrics);
722 }
723 }
724
jar@chromium.org92745242009-06-12 16:52:21725 // Get stats on use of command line.
726 const CommandLine* command_line(CommandLine::ForCurrentProcess());
727 size_t common_commands = 0;
728 if (command_line->HasSwitch(switches::kUserDataDir)) {
729 ++common_commands;
730 UMA_HISTOGRAM_COUNTS_100("Chrome.CommandLineDatDirCount", 1);
731 }
732
733 if (command_line->HasSwitch(switches::kApp)) {
734 ++common_commands;
735 UMA_HISTOGRAM_COUNTS_100("Chrome.CommandLineAppModeCount", 1);
736 }
737
738 UMA_HISTOGRAM_COUNTS_100("Chrome.CommandLineFlagCount",
739 command_line->GetSwitchCount());
740 UMA_HISTOGRAM_COUNTS_100("Chrome.CommandLineUncommonFlagCount",
741 command_line->GetSwitchCount() - common_commands);
742
initial.commit09911bf2008-07-26 23:55:29743 // Kick off the process of saving the state (so the uptime numbers keep
744 // getting updated) every n minutes.
745 ScheduleNextStateSave();
746}
747
jamesr@chromium.org7f2e792e2009-11-30 23:18:29748void MetricsService::OnGetPluginListTaskComplete(
jam@chromium.org35fa6a22009-08-15 00:04:01749 const std::vector<WebPluginInfo>& plugins) {
initial.commit09911bf2008-07-26 23:55:29750 DCHECK(state_ == PLUGIN_LIST_REQUESTED);
jam@chromium.org35fa6a22009-08-15 00:04:01751 plugins_ = plugins;
initial.commit09911bf2008-07-26 23:55:29752 if (state_ == PLUGIN_LIST_REQUESTED)
753 state_ = PLUGIN_LIST_ARRIVED;
754}
755
756std::string MetricsService::GenerateClientID() {
paul@chromium.orgdc6f4962009-02-13 01:25:50757#if defined(OS_WIN)
initial.commit09911bf2008-07-26 23:55:29758 const int kGUIDSize = 39;
759
760 GUID guid;
761 HRESULT guid_result = CoCreateGuid(&guid);
762 DCHECK(SUCCEEDED(guid_result));
763
764 std::wstring guid_string;
765 int result = StringFromGUID2(guid,
766 WriteInto(&guid_string, kGUIDSize), kGUIDSize);
767 DCHECK(result == kGUIDSize);
768
769 return WideToUTF8(guid_string.substr(1, guid_string.length() - 2));
evan@chromium.org271b24f2009-07-28 16:05:51770#else
sky@chromium.org06aaac22009-07-08 20:54:13771 uint64 sixteen_bytes[2] = { base::RandUint64(), base::RandUint64() };
772 return RandomBytesToGUIDString(sixteen_bytes);
paul@chromium.orgdc6f4962009-02-13 01:25:50773#endif
initial.commit09911bf2008-07-26 23:55:29774}
775
sky@chromium.org06aaac22009-07-08 20:54:13776#if defined(OS_POSIX)
777// TODO(cmasone): Once we're comfortable this works, migrate Windows code to
778// use this as well.
779std::string MetricsService::RandomBytesToGUIDString(const uint64 bytes[2]) {
evan@chromium.org34b2b002009-11-20 06:53:28780 return StringPrintf("%08X-%04X-%04X-%04X-%012llX",
781 static_cast<unsigned int>(bytes[0] >> 32),
782 static_cast<unsigned int>((bytes[0] >> 16) & 0x0000ffff),
783 static_cast<unsigned int>(bytes[0] & 0x0000ffff),
784 static_cast<unsigned int>(bytes[1] >> 48),
sky@chromium.org06aaac22009-07-08 20:54:13785 bytes[1] & 0x0000ffffffffffffULL);
786}
787#endif
initial.commit09911bf2008-07-26 23:55:29788
789//------------------------------------------------------------------------------
790// State save methods
791
792void MetricsService::ScheduleNextStateSave() {
793 state_saver_factory_.RevokeAll();
794
795 MessageLoop::current()->PostDelayedTask(FROM_HERE,
796 state_saver_factory_.NewRunnableMethod(&MetricsService::SaveLocalState),
797 kSaveStateInterval * 1000);
798}
799
800void MetricsService::SaveLocalState() {
801 PrefService* pref = g_browser_process->local_state();
802 if (!pref) {
jar@chromium.orgb42c5e42010-06-03 20:43:25803 LOG(DFATAL);
initial.commit09911bf2008-07-26 23:55:29804 return;
805 }
806
807 RecordCurrentState(pref);
phajdan.jr@chromium.org6faa0e0d2009-04-28 06:50:36808 pref->ScheduleSavePersistentPrefs();
initial.commit09911bf2008-07-26 23:55:29809
jar@chromium.org281d2882009-01-20 20:32:42810 // TODO(jar): Does this run down the batteries????
initial.commit09911bf2008-07-26 23:55:29811 ScheduleNextStateSave();
812}
813
814
815//------------------------------------------------------------------------------
816// Recording control methods
817
818void MetricsService::StartRecording() {
819 if (current_log_)
820 return;
821
822 current_log_ = new MetricsLog(client_id_, session_id_);
823 if (state_ == INITIALIZED) {
824 // We only need to schedule that run once.
825 state_ = PLUGIN_LIST_REQUESTED;
826
827 // Make sure the plugin list is loaded before the inital log is sent, so
828 // that the main thread isn't blocked generating the list.
jamesr@chromium.org7f2e792e2009-11-30 23:18:29829 g_browser_process->file_thread()->message_loop()->PostDelayedTask(FROM_HERE,
830 new GetPluginListTask(MessageLoop::current()),
petersont@google.com252873ef2008-08-04 21:59:45831 kInitialInterlogDuration * 1000 / 2);
initial.commit09911bf2008-07-26 23:55:29832 }
833}
834
835void MetricsService::StopRecording(MetricsLog** log) {
836 if (!current_log_)
837 return;
838
jar@google.com68475e602008-08-22 03:21:15839 // TODO(jar): Integrate bounds on log recording more consistently, so that we
840 // can stop recording logs that are too big much sooner.
petersont@google.comd01b8732008-10-16 02:18:07841 if (current_log_->num_events() > log_event_limit_) {
dsh@google.com553dba62009-02-24 19:08:23842 UMA_HISTOGRAM_COUNTS("UMA.Discarded Log Events",
jar@google.com68475e602008-08-22 03:21:15843 current_log_->num_events());
844 current_log_->CloseLog();
845 delete current_log_;
jar@google.com294638782008-09-24 00:22:41846 current_log_ = NULL;
jar@google.com68475e602008-08-22 03:21:15847 StartRecording(); // Start trivial log to hold our histograms.
848 }
849
jar@google.com0b33f80b2008-12-17 21:34:36850 // Put incremental data (histogram deltas, and realtime stats deltas) at the
jar@google.com147bbc0b2009-01-06 19:37:40851 // end of all log transmissions (initial log handles this separately).
initial.commit09911bf2008-07-26 23:55:29852 // Don't bother if we're going to discard current_log_.
jar@google.com0b33f80b2008-12-17 21:34:36853 if (log) {
jar@chromium.orgc96d53092009-02-24 01:25:06854 current_log_->RecordIncrementalStabilityElements();
initial.commit09911bf2008-07-26 23:55:29855 RecordCurrentHistograms();
jar@google.com0b33f80b2008-12-17 21:34:36856 }
initial.commit09911bf2008-07-26 23:55:29857
858 current_log_->CloseLog();
pkasting@chromium.orgcac78842008-11-27 01:02:20859 if (log)
initial.commit09911bf2008-07-26 23:55:29860 *log = current_log_;
pkasting@chromium.orgcac78842008-11-27 01:02:20861 else
initial.commit09911bf2008-07-26 23:55:29862 delete current_log_;
initial.commit09911bf2008-07-26 23:55:29863 current_log_ = NULL;
864}
865
initial.commit09911bf2008-07-26 23:55:29866void MetricsService::PushPendingLogsToUnsentLists() {
867 if (state_ < INITIAL_LOG_READY)
avi@google.com28ab7f92009-01-06 21:39:04868 return; // We didn't and still don't have time to get plugin list etc.
initial.commit09911bf2008-07-26 23:55:29869
870 if (pending_log()) {
871 PreparePendingLogText();
872 if (state_ == INITIAL_LOG_READY) {
873 // We may race here, and send second copy of initial log later.
874 unsent_initial_logs_.push_back(pending_log_text_);
petersont@google.comd01b8732008-10-16 02:18:07875 state_ = SEND_OLD_INITIAL_LOGS;
initial.commit09911bf2008-07-26 23:55:29876 } else {
jar@chromium.org281d2882009-01-20 20:32:42877 // TODO(jar): Verify correctness in other states, including sending unsent
jar@chromium.org541f77922009-02-23 21:14:38878 // initial logs.
jar@google.com68475e602008-08-22 03:21:15879 PushPendingLogTextToUnsentOngoingLogs();
initial.commit09911bf2008-07-26 23:55:29880 }
881 DiscardPendingLog();
882 }
883 DCHECK(!pending_log());
884 StopRecording(&pending_log_);
885 PreparePendingLogText();
jar@google.com68475e602008-08-22 03:21:15886 PushPendingLogTextToUnsentOngoingLogs();
initial.commit09911bf2008-07-26 23:55:29887 DiscardPendingLog();
888 StoreUnsentLogs();
889}
890
jar@google.com68475e602008-08-22 03:21:15891void MetricsService::PushPendingLogTextToUnsentOngoingLogs() {
petersont@google.comd01b8732008-10-16 02:18:07892 // If UMA response told us not to upload, there's no need to save the pending
893 // log. It wasn't supposed to be uploaded anyway.
894 if (!server_permits_upload_)
895 return;
896
paul@chromium.orgdc6f4962009-02-13 01:25:50897 if (pending_log_text_.length() >
898 static_cast<size_t>(kUploadLogAvoidRetransmitSize)) {
dsh@google.com553dba62009-02-24 19:08:23899 UMA_HISTOGRAM_COUNTS("UMA.Large Accumulated Log Not Persisted",
jar@google.com68475e602008-08-22 03:21:15900 static_cast<int>(pending_log_text_.length()));
901 return;
902 }
903 unsent_ongoing_logs_.push_back(pending_log_text_);
904}
905
initial.commit09911bf2008-07-26 23:55:29906//------------------------------------------------------------------------------
907// Transmission of logs methods
908
909void MetricsService::StartLogTransmissionTimer() {
petersont@google.comd01b8732008-10-16 02:18:07910 // If we're not reporting, there's no point in starting a log transmission
911 // timer.
912 if (!reporting_active())
913 return;
914
initial.commit09911bf2008-07-26 23:55:29915 if (!current_log_)
916 return; // Recorder is shutdown.
petersont@google.comd01b8732008-10-16 02:18:07917
918 // If there is already a timer running, we leave it running.
919 // If timer_pending is true because the fetch is waiting for a response,
920 // we return for now and let the response handler start the timer.
921 if (timer_pending_)
initial.commit09911bf2008-07-26 23:55:29922 return;
petersont@google.comd01b8732008-10-16 02:18:07923
petersont@google.comd01b8732008-10-16 02:18:07924 // Before starting the timer, set timer_pending_ to true.
initial.commit09911bf2008-07-26 23:55:29925 timer_pending_ = true;
petersont@google.comd01b8732008-10-16 02:18:07926
927 // Right before the UMA transmission gets started, there's one more thing we'd
928 // like to record: the histogram of memory usage, so we spawn a task to
jar@chromium.orgc9a3ef82009-05-28 22:02:46929 // collect the memory details and when that task is finished, it will call
930 // OnMemoryDetailCollectionDone, which will call HistogramSynchronization to
931 // collect histograms from all renderers and then we will call
932 // OnHistogramSynchronizationDone to continue processing.
initial.commit09911bf2008-07-26 23:55:29933 MessageLoop::current()->PostDelayedTask(FROM_HERE,
934 log_sender_factory_.
jar@chromium.orgc9a3ef82009-05-28 22:02:46935 NewRunnableMethod(&MetricsService::LogTransmissionTimerDone),
phajdan.jr@chromium.org743ace42009-06-17 17:23:51936 interlog_duration_.InMilliseconds());
initial.commit09911bf2008-07-26 23:55:29937}
938
jar@chromium.orgc9a3ef82009-05-28 22:02:46939void MetricsService::LogTransmissionTimerDone() {
940 Task* task = log_sender_factory_.
941 NewRunnableMethod(&MetricsService::OnMemoryDetailCollectionDone);
942
jam@chromium.orge9adedb2009-12-01 22:23:59943 scoped_refptr<MetricsMemoryDetails> details = new MetricsMemoryDetails(task);
jar@chromium.orgc9a3ef82009-05-28 22:02:46944 details->StartFetch();
945
946 // Collect WebCore cache information to put into a histogram.
pkasting@chromium.org019191a2009-10-02 20:37:27947 for (RenderProcessHost::iterator i(RenderProcessHost::AllHostsIterator());
948 !i.IsAtEnd(); i.Advance())
949 i.GetCurrentValue()->Send(new ViewMsg_GetCacheResourceStats());
jar@chromium.orgc9a3ef82009-05-28 22:02:46950}
951
952void MetricsService::OnMemoryDetailCollectionDone() {
953 DCHECK(IsSingleThreaded());
954
955 // HistogramSynchronizer will Collect histograms from all renderers and it
956 // will call OnHistogramSynchronizationDone (if wait time elapses before it
957 // heard from all renderers, then also it will call
958 // OnHistogramSynchronizationDone).
959
960 // Create a callback_task for OnHistogramSynchronizationDone.
961 Task* callback_task = log_sender_factory_.NewRunnableMethod(
962 &MetricsService::OnHistogramSynchronizationDone);
963
964 // Set up the callback to task to call after we receive histograms from all
965 // renderer processes. Wait time specifies how long to wait before absolutely
966 // calling us back on the task.
967 HistogramSynchronizer::FetchRendererHistogramsAsynchronously(
968 MessageLoop::current(), callback_task,
969 kMaxHistogramGatheringWaitDuration);
970}
971
972void MetricsService::OnHistogramSynchronizationDone() {
initial.commit09911bf2008-07-26 23:55:29973 DCHECK(IsSingleThreaded());
974
petersont@google.comd01b8732008-10-16 02:18:07975 // This function should only be called via timer, so timer_pending_
976 // should be true.
977 DCHECK(timer_pending_);
978 timer_pending_ = false;
initial.commit09911bf2008-07-26 23:55:29979
980 DCHECK(!current_fetch_.get());
initial.commit09911bf2008-07-26 23:55:29981
petersont@google.comd01b8732008-10-16 02:18:07982 // If we're getting no notifications, then the log won't have much in it, and
983 // it's possible the computer is about to go to sleep, so don't upload and
984 // don't restart the transmission timer.
985 if (idle_since_last_transmission_)
986 return;
987
988 // If somehow there is a fetch in progress, we return setting timer_pending_
989 // to true and hope things work out.
990 if (current_fetch_.get()) {
991 timer_pending_ = true;
992 return;
993 }
994
995 // If uploads are forbidden by UMA response, there's no point in keeping
996 // the current_log_, and the more often we delete it, the less likely it is
997 // to expand forever.
998 if (!server_permits_upload_ && current_log_) {
999 StopRecording(NULL);
1000 StartRecording();
1001 }
initial.commit09911bf2008-07-26 23:55:291002
1003 if (!current_log_)
1004 return; // Logging was disabled.
petersont@google.comd01b8732008-10-16 02:18:071005 if (!reporting_active())
initial.commit09911bf2008-07-26 23:55:291006 return; // Don't do work if we're not going to send anything now.
1007
petersont@google.comd01b8732008-10-16 02:18:071008 MakePendingLog();
initial.commit09911bf2008-07-26 23:55:291009
petersont@google.comd01b8732008-10-16 02:18:071010 // MakePendingLog should have put something in the pending log, if it didn't,
1011 // we start the timer again, return and hope things work out.
1012 if (!pending_log()) {
1013 StartLogTransmissionTimer();
1014 return;
1015 }
initial.commit09911bf2008-07-26 23:55:291016
petersont@google.comd01b8732008-10-16 02:18:071017 // If we're not supposed to upload any UMA data because the response or the
1018 // user said so, cancel the upload at this point, but start the timer.
1019 if (!TransmissionPermitted()) {
1020 DiscardPendingLog();
1021 StartLogTransmissionTimer();
1022 return;
1023 }
initial.commit09911bf2008-07-26 23:55:291024
petersont@google.comd01b8732008-10-16 02:18:071025 PrepareFetchWithPendingLog();
1026
1027 if (!current_fetch_.get()) {
1028 // Compression failed, and log discarded :-/.
1029 DiscardPendingLog();
1030 StartLogTransmissionTimer(); // Maybe we'll do better next time
1031 // TODO(jar): If compression failed, we should have created a tiny log and
1032 // compressed that, so that we can signal that we're losing logs.
1033 return;
1034 }
1035
1036 DCHECK(!timer_pending_);
1037
1038 // The URL fetch is a like timer in that after a while we get called back
1039 // so we set timer_pending_ true just as we start the url fetch.
1040 timer_pending_ = true;
1041 current_fetch_->Start();
1042
1043 HandleIdleSinceLastTransmission(true);
1044}
1045
1046
1047void MetricsService::MakePendingLog() {
1048 if (pending_log())
1049 return;
1050
1051 switch (state_) {
1052 case INITIALIZED:
1053 case PLUGIN_LIST_REQUESTED: // We should be further along by now.
1054 DCHECK(false);
1055 return;
1056
1057 case PLUGIN_LIST_ARRIVED:
1058 // We need to wait for the initial log to be ready before sending
1059 // anything, because the server will tell us whether it wants to hear
1060 // from us.
1061 PrepareInitialLog();
1062 DCHECK(state_ == PLUGIN_LIST_ARRIVED);
1063 RecallUnsentLogs();
1064 state_ = INITIAL_LOG_READY;
1065 break;
1066
1067 case SEND_OLD_INITIAL_LOGS:
pkasting@chromium.orgcac78842008-11-27 01:02:201068 if (!unsent_initial_logs_.empty()) {
1069 pending_log_text_ = unsent_initial_logs_.back();
1070 break;
1071 }
petersont@google.comd01b8732008-10-16 02:18:071072 state_ = SENDING_OLD_LOGS;
1073 // Fall through.
initial.commit09911bf2008-07-26 23:55:291074
petersont@google.comd01b8732008-10-16 02:18:071075 case SENDING_OLD_LOGS:
1076 if (!unsent_ongoing_logs_.empty()) {
1077 pending_log_text_ = unsent_ongoing_logs_.back();
1078 break;
1079 }
1080 state_ = SENDING_CURRENT_LOGS;
1081 // Fall through.
1082
1083 case SENDING_CURRENT_LOGS:
1084 StopRecording(&pending_log_);
1085 StartRecording();
1086 break;
1087
1088 default:
jar@chromium.orgb42c5e42010-06-03 20:43:251089 LOG(DFATAL);
petersont@google.comd01b8732008-10-16 02:18:071090 return;
1091 }
1092
1093 DCHECK(pending_log());
1094}
1095
1096bool MetricsService::TransmissionPermitted() const {
1097 // If the user forbids uploading that's they're business, and we don't upload
1098 // anything. If the server forbids uploading, that's our business, so we take
1099 // that to mean it forbids current logs, but we still send up the inital logs
1100 // and any old logs.
petersont@google.comd01b8732008-10-16 02:18:071101 if (!user_permits_upload_)
1102 return false;
pkasting@chromium.orgcac78842008-11-27 01:02:201103 if (server_permits_upload_)
petersont@google.comd01b8732008-10-16 02:18:071104 return true;
initial.commit09911bf2008-07-26 23:55:291105
pkasting@chromium.orgcac78842008-11-27 01:02:201106 switch (state_) {
1107 case INITIAL_LOG_READY:
1108 case SEND_OLD_INITIAL_LOGS:
1109 case SENDING_OLD_LOGS:
1110 return true;
1111
1112 case SENDING_CURRENT_LOGS:
1113 default:
1114 return false;
nsylvain@chromium.org8c8824b2008-09-20 01:55:501115 }
initial.commit09911bf2008-07-26 23:55:291116}
1117
initial.commit09911bf2008-07-26 23:55:291118void MetricsService::PrepareInitialLog() {
1119 DCHECK(state_ == PLUGIN_LIST_ARRIVED);
initial.commit09911bf2008-07-26 23:55:291120
1121 MetricsLog* log = new MetricsLog(client_id_, session_id_);
jam@chromium.org35fa6a22009-08-15 00:04:011122 log->RecordEnvironment(plugins_, profile_dictionary_.get());
initial.commit09911bf2008-07-26 23:55:291123
1124 // Histograms only get written to current_log_, so setup for the write.
1125 MetricsLog* save_log = current_log_;
1126 current_log_ = log;
1127 RecordCurrentHistograms(); // Into current_log_... which is really log.
1128 current_log_ = save_log;
1129
1130 log->CloseLog();
1131 DCHECK(!pending_log());
1132 pending_log_ = log;
1133}
1134
1135void MetricsService::RecallUnsentLogs() {
1136 DCHECK(unsent_initial_logs_.empty());
1137 DCHECK(unsent_ongoing_logs_.empty());
1138
1139 PrefService* local_state = g_browser_process->local_state();
1140 DCHECK(local_state);
1141
1142 ListValue* unsent_initial_logs = local_state->GetMutableList(
1143 prefs::kMetricsInitialLogs);
1144 for (ListValue::iterator it = unsent_initial_logs->begin();
1145 it != unsent_initial_logs->end(); ++it) {
scherkus@chromium.org5e324b72008-12-18 00:07:591146 std::string log;
1147 (*it)->GetAsString(&log);
1148 unsent_initial_logs_.push_back(log);
initial.commit09911bf2008-07-26 23:55:291149 }
1150
1151 ListValue* unsent_ongoing_logs = local_state->GetMutableList(
1152 prefs::kMetricsOngoingLogs);
1153 for (ListValue::iterator it = unsent_ongoing_logs->begin();
1154 it != unsent_ongoing_logs->end(); ++it) {
scherkus@chromium.org5e324b72008-12-18 00:07:591155 std::string log;
1156 (*it)->GetAsString(&log);
1157 unsent_ongoing_logs_.push_back(log);
initial.commit09911bf2008-07-26 23:55:291158 }
1159}
1160
1161void MetricsService::StoreUnsentLogs() {
1162 if (state_ < INITIAL_LOG_READY)
1163 return; // We never Recalled the prior unsent logs.
1164
1165 PrefService* local_state = g_browser_process->local_state();
1166 DCHECK(local_state);
1167
1168 ListValue* unsent_initial_logs = local_state->GetMutableList(
1169 prefs::kMetricsInitialLogs);
1170 unsent_initial_logs->Clear();
1171 size_t start = 0;
1172 if (unsent_initial_logs_.size() > kMaxInitialLogsPersisted)
1173 start = unsent_initial_logs_.size() - kMaxInitialLogsPersisted;
1174 for (size_t i = start; i < unsent_initial_logs_.size(); ++i)
1175 unsent_initial_logs->Append(
scherkus@chromium.org5e324b72008-12-18 00:07:591176 Value::CreateStringValue(unsent_initial_logs_[i]));
initial.commit09911bf2008-07-26 23:55:291177
1178 ListValue* unsent_ongoing_logs = local_state->GetMutableList(
1179 prefs::kMetricsOngoingLogs);
1180 unsent_ongoing_logs->Clear();
1181 start = 0;
1182 if (unsent_ongoing_logs_.size() > kMaxOngoingLogsPersisted)
1183 start = unsent_ongoing_logs_.size() - kMaxOngoingLogsPersisted;
1184 for (size_t i = start; i < unsent_ongoing_logs_.size(); ++i)
1185 unsent_ongoing_logs->Append(
scherkus@chromium.org5e324b72008-12-18 00:07:591186 Value::CreateStringValue(unsent_ongoing_logs_[i]));
initial.commit09911bf2008-07-26 23:55:291187}
1188
1189void MetricsService::PreparePendingLogText() {
1190 DCHECK(pending_log());
1191 if (!pending_log_text_.empty())
1192 return;
mark@chromium.org9ffcccf42009-09-15 22:19:181193 int text_size = pending_log_->GetEncodedLogSize();
1194
1195 // Leave room for the NUL terminator.
1196 pending_log_->GetEncodedLog(WriteInto(&pending_log_text_, text_size + 1),
1197 text_size);
initial.commit09911bf2008-07-26 23:55:291198}
1199
petersont@google.comd01b8732008-10-16 02:18:071200void MetricsService::PrepareFetchWithPendingLog() {
initial.commit09911bf2008-07-26 23:55:291201 DCHECK(pending_log());
1202 DCHECK(!current_fetch_.get());
1203 PreparePendingLogText();
1204 DCHECK(!pending_log_text_.empty());
1205
1206 // Allow security conscious users to see all metrics logs that we send.
1207 LOG(INFO) << "METRICS LOG: " << pending_log_text_;
1208
1209 std::string compressed_log;
pkasting@chromium.orgcac78842008-11-27 01:02:201210 if (!Bzip2Compress(pending_log_text_, &compressed_log)) {
jar@chromium.orgb42c5e42010-06-03 20:43:251211 LOG(DFATAL) << "Failed to compress log for transmission.";
initial.commit09911bf2008-07-26 23:55:291212 DiscardPendingLog();
1213 StartLogTransmissionTimer(); // Maybe we'll do better on next log :-/.
1214 return;
1215 }
pkasting@chromium.orgcac78842008-11-27 01:02:201216
kuchhal@chromium.org79bf0b72009-04-27 21:30:551217 current_fetch_.reset(new URLFetcher(GURL(WideToUTF16(server_url_)),
1218 URLFetcher::POST,
initial.commit09911bf2008-07-26 23:55:291219 this));
1220 current_fetch_->set_request_context(Profile::GetDefaultRequestContext());
1221 current_fetch_->set_upload_data(kMetricsType, compressed_log);
initial.commit09911bf2008-07-26 23:55:291222}
1223
1224void MetricsService::DiscardPendingLog() {
1225 if (pending_log_) { // Shutdown might have deleted it!
1226 delete pending_log_;
1227 pending_log_ = NULL;
1228 }
1229 pending_log_text_.clear();
1230}
1231
1232// This implementation is based on the Firefox MetricsService implementation.
1233bool MetricsService::Bzip2Compress(const std::string& input,
1234 std::string* output) {
1235 bz_stream stream = {0};
1236 // As long as our input is smaller than the bzip2 block size, we should get
1237 // the best compression. For example, if your input was 250k, using a block
1238 // size of 300k or 500k should result in the same compression ratio. Since
1239 // our data should be under 100k, using the minimum block size of 100k should
1240 // allocate less temporary memory, but result in the same compression ratio.
1241 int result = BZ2_bzCompressInit(&stream,
1242 1, // 100k (min) block size
1243 0, // quiet
1244 0); // default "work factor"
1245 if (result != BZ_OK) { // out of memory?
1246 return false;
1247 }
1248
1249 output->clear();
1250
1251 stream.next_in = const_cast<char*>(input.data());
1252 stream.avail_in = static_cast<int>(input.size());
1253 // NOTE: we don't need a BZ_RUN phase since our input buffer contains
1254 // the entire input
1255 do {
1256 output->resize(output->size() + 1024);
1257 stream.next_out = &((*output)[stream.total_out_lo32]);
1258 stream.avail_out = static_cast<int>(output->size()) - stream.total_out_lo32;
1259 result = BZ2_bzCompress(&stream, BZ_FINISH);
1260 } while (result == BZ_FINISH_OK);
1261 if (result != BZ_STREAM_END) // unknown failure?
1262 return false;
1263 result = BZ2_bzCompressEnd(&stream);
1264 DCHECK(result == BZ_OK);
1265
1266 output->resize(stream.total_out_lo32);
1267
1268 return true;
1269}
1270
1271static const char* StatusToString(const URLRequestStatus& status) {
1272 switch (status.status()) {
1273 case URLRequestStatus::SUCCESS:
1274 return "SUCCESS";
1275
1276 case URLRequestStatus::IO_PENDING:
1277 return "IO_PENDING";
1278
1279 case URLRequestStatus::HANDLED_EXTERNALLY:
1280 return "HANDLED_EXTERNALLY";
1281
1282 case URLRequestStatus::CANCELED:
1283 return "CANCELED";
1284
1285 case URLRequestStatus::FAILED:
1286 return "FAILED";
1287
1288 default:
jar@chromium.orgb42c5e42010-06-03 20:43:251289 LOG(DFATAL);
initial.commit09911bf2008-07-26 23:55:291290 return "Unknown";
1291 }
1292}
1293
1294void MetricsService::OnURLFetchComplete(const URLFetcher* source,
1295 const GURL& url,
1296 const URLRequestStatus& status,
1297 int response_code,
1298 const ResponseCookies& cookies,
1299 const std::string& data) {
1300 DCHECK(timer_pending_);
1301 timer_pending_ = false;
1302 DCHECK(current_fetch_.get());
1303 current_fetch_.reset(NULL); // We're not allowed to re-use it.
1304
1305 // Confirm send so that we can move on.
jar@chromium.org281d2882009-01-20 20:32:421306 LOG(INFO) << "METRICS RESPONSE CODE: " << response_code << " status=" <<
pkasting@chromium.orgcac78842008-11-27 01:02:201307 StatusToString(status);
petersont@google.com252873ef2008-08-04 21:59:451308
jar@chromium.org0eb34fee2009-01-21 08:04:381309 // Provide boolean for error recovery (allow us to ignore response_code).
paul@chromium.orgdc6f4962009-02-13 01:25:501310 bool discard_log = false;
jar@chromium.org0eb34fee2009-01-21 08:04:381311
jar@google.com68475e602008-08-22 03:21:151312 if (response_code != 200 &&
paul@chromium.orgdc6f4962009-02-13 01:25:501313 pending_log_text_.length() >
1314 static_cast<size_t>(kUploadLogAvoidRetransmitSize)) {
dsh@google.com553dba62009-02-24 19:08:231315 UMA_HISTOGRAM_COUNTS("UMA.Large Rejected Log was Discarded",
jar@google.com68475e602008-08-22 03:21:151316 static_cast<int>(pending_log_text_.length()));
jar@chromium.org0eb34fee2009-01-21 08:04:381317 discard_log = true;
1318 } else if (response_code == 400) {
1319 // Bad syntax. Retransmission won't work.
dsh@google.com553dba62009-02-24 19:08:231320 UMA_HISTOGRAM_COUNTS("UMA.Unacceptable_Log_Discarded", state_);
jar@chromium.org0eb34fee2009-01-21 08:04:381321 discard_log = true;
jar@google.com68475e602008-08-22 03:21:151322 }
1323
jar@chromium.org0eb34fee2009-01-21 08:04:381324 if (response_code != 200 && !discard_log) {
jar@chromium.org281d2882009-01-20 20:32:421325 LOG(INFO) << "METRICS: transmission attempt returned a failure code: "
1326 << response_code << ". Verify network connectivity";
petersont@google.com252873ef2008-08-04 21:59:451327 HandleBadResponseCode();
jar@chromium.org0eb34fee2009-01-21 08:04:381328 } else { // Successful receipt (or we are discarding log).
jar@chromium.org281d2882009-01-20 20:32:421329 LOG(INFO) << "METRICS RESPONSE DATA: " << data;
initial.commit09911bf2008-07-26 23:55:291330 switch (state_) {
1331 case INITIAL_LOG_READY:
1332 state_ = SEND_OLD_INITIAL_LOGS;
1333 break;
1334
1335 case SEND_OLD_INITIAL_LOGS:
1336 DCHECK(!unsent_initial_logs_.empty());
1337 unsent_initial_logs_.pop_back();
1338 StoreUnsentLogs();
1339 break;
1340
1341 case SENDING_OLD_LOGS:
1342 DCHECK(!unsent_ongoing_logs_.empty());
1343 unsent_ongoing_logs_.pop_back();
1344 StoreUnsentLogs();
1345 break;
1346
1347 case SENDING_CURRENT_LOGS:
1348 break;
1349
1350 default:
jar@chromium.orgb42c5e42010-06-03 20:43:251351 LOG(DFATAL);
initial.commit09911bf2008-07-26 23:55:291352 break;
1353 }
petersont@google.comd01b8732008-10-16 02:18:071354
initial.commit09911bf2008-07-26 23:55:291355 DiscardPendingLog();
jar@google.com29be92552008-08-07 22:49:271356 // Since we sent a log, make sure our in-memory state is recorded to disk.
1357 PrefService* local_state = g_browser_process->local_state();
1358 DCHECK(local_state);
1359 if (local_state)
phajdan.jr@chromium.org6faa0e0d2009-04-28 06:50:361360 local_state->ScheduleSavePersistentPrefs();
petersont@google.com252873ef2008-08-04 21:59:451361
jar@google.com147bbc0b2009-01-06 19:37:401362 // Provide a default (free of exponetial backoff, other varances) in case
1363 // the server does not specify a value.
1364 interlog_duration_ = TimeDelta::FromSeconds(kMinSecondsPerLog);
1365
petersont@google.com252873ef2008-08-04 21:59:451366 GetSettingsFromResponseData(data);
petersont@google.com252873ef2008-08-04 21:59:451367 // Override server specified interlog delay if there are unsent logs to
jar@google.com29be92552008-08-07 22:49:271368 // transmit.
initial.commit09911bf2008-07-26 23:55:291369 if (unsent_logs()) {
1370 DCHECK(state_ < SENDING_CURRENT_LOGS);
1371 interlog_duration_ = TimeDelta::FromSeconds(kUnsentLogDelay);
initial.commit09911bf2008-07-26 23:55:291372 }
1373 }
petersont@google.com252873ef2008-08-04 21:59:451374
initial.commit09911bf2008-07-26 23:55:291375 StartLogTransmissionTimer();
1376}
1377
petersont@google.com252873ef2008-08-04 21:59:451378void MetricsService::HandleBadResponseCode() {
jar@chromium.org281d2882009-01-20 20:32:421379 LOG(INFO) << "Verify your metrics logs are formatted correctly. "
kuchhal@chromium.org79bf0b72009-04-27 21:30:551380 "Verify server is active at " << server_url_;
petersont@google.com252873ef2008-08-04 21:59:451381 if (!pending_log()) {
jar@chromium.org281d2882009-01-20 20:32:421382 LOG(INFO) << "METRICS: Recorder shutdown during log transmission.";
petersont@google.com252873ef2008-08-04 21:59:451383 } else {
1384 // Send progressively less frequently.
1385 DCHECK(kBackoff > 1.0);
1386 interlog_duration_ = TimeDelta::FromMicroseconds(
1387 static_cast<int64>(kBackoff * interlog_duration_.InMicroseconds()));
1388
1389 if (kMaxBackoff * TimeDelta::FromSeconds(kMinSecondsPerLog) <
pkasting@chromium.orgcac78842008-11-27 01:02:201390 interlog_duration_) {
petersont@google.com252873ef2008-08-04 21:59:451391 interlog_duration_ = kMaxBackoff *
1392 TimeDelta::FromSeconds(kMinSecondsPerLog);
pkasting@chromium.orgcac78842008-11-27 01:02:201393 }
petersont@google.com252873ef2008-08-04 21:59:451394
jar@chromium.org281d2882009-01-20 20:32:421395 LOG(INFO) << "METRICS: transmission retry being scheduled in " <<
petersont@google.com252873ef2008-08-04 21:59:451396 interlog_duration_.InSeconds() << " seconds for " <<
1397 pending_log_text_;
initial.commit09911bf2008-07-26 23:55:291398 }
initial.commit09911bf2008-07-26 23:55:291399}
1400
petersont@google.com252873ef2008-08-04 21:59:451401void MetricsService::GetSettingsFromResponseData(const std::string& data) {
1402 // We assume that the file is structured as a block opened by <response>
petersont@google.comd01b8732008-10-16 02:18:071403 // and that inside response, there is a block opened by tag <chrome_config>
1404 // other tags are ignored for now except the content of <chrome_config>.
jar@chromium.org281d2882009-01-20 20:32:421405 LOG(INFO) << "METRICS: getting settings from response data: " << data;
petersont@google.comd01b8732008-10-16 02:18:071406
petersont@google.com252873ef2008-08-04 21:59:451407 int data_size = static_cast<int>(data.size());
1408 if (data_size < 0) {
jar@chromium.org281d2882009-01-20 20:32:421409 LOG(INFO) << "METRICS: server response data bad size: " << data_size <<
pkasting@chromium.orgcac78842008-11-27 01:02:201410 "; aborting extraction of settings";
petersont@google.com252873ef2008-08-04 21:59:451411 return;
1412 }
pkasting@chromium.orgcac78842008-11-27 01:02:201413 xmlDocPtr doc = xmlReadMemory(data.c_str(), data_size, "", NULL, 0);
petersont@google.com252873ef2008-08-04 21:59:451414 DCHECK(doc);
petersont@google.comd01b8732008-10-16 02:18:071415 // If the document is malformed, we just use the settings that were there.
1416 if (!doc) {
jar@chromium.org281d2882009-01-20 20:32:421417 LOG(INFO) << "METRICS: reading xml from server response data failed";
petersont@google.com252873ef2008-08-04 21:59:451418 return;
petersont@google.comd01b8732008-10-16 02:18:071419 }
petersont@google.com252873ef2008-08-04 21:59:451420
petersont@google.comd01b8732008-10-16 02:18:071421 xmlNodePtr top_node = xmlDocGetRootElement(doc), chrome_config_node = NULL;
1422 // Here, we find the chrome_config node by name.
petersont@google.com252873ef2008-08-04 21:59:451423 for (xmlNodePtr p = top_node->children; p; p = p->next) {
petersont@google.comd01b8732008-10-16 02:18:071424 if (xmlStrEqual(p->name, BAD_CAST "chrome_config")) {
1425 chrome_config_node = p;
petersont@google.com252873ef2008-08-04 21:59:451426 break;
1427 }
1428 }
1429 // If the server data is formatted wrong and there is no
1430 // config node where we expect, we just drop out.
petersont@google.comd01b8732008-10-16 02:18:071431 if (chrome_config_node != NULL)
1432 GetSettingsFromChromeConfigNode(chrome_config_node);
petersont@google.com252873ef2008-08-04 21:59:451433 xmlFreeDoc(doc);
1434}
1435
petersont@google.comd01b8732008-10-16 02:18:071436void MetricsService::GetSettingsFromChromeConfigNode(
1437 xmlNodePtr chrome_config_node) {
1438 // Iterate through all children of the config node.
1439 for (xmlNodePtr current_node = chrome_config_node->children;
1440 current_node;
1441 current_node = current_node->next) {
1442 // If we find the upload tag, we appeal to another function
1443 // GetSettingsFromUploadNode to read all the data in it.
petersont@google.com252873ef2008-08-04 21:59:451444 if (xmlStrEqual(current_node->name, BAD_CAST "upload")) {
petersont@google.comd01b8732008-10-16 02:18:071445 GetSettingsFromUploadNode(current_node);
petersont@google.com252873ef2008-08-04 21:59:451446 continue;
1447 }
1448 }
1449}
initial.commit09911bf2008-07-26 23:55:291450
petersont@google.comd01b8732008-10-16 02:18:071451void MetricsService::InheritedProperties::OverwriteWhereNeeded(
1452 xmlNodePtr node) {
1453 xmlChar* salt_value = xmlGetProp(node, BAD_CAST "salt");
1454 if (salt_value) // If the property isn't there, xmlGetProp returns NULL.
1455 salt = atoi(reinterpret_cast<char*>(salt_value));
1456 // If the property isn't there, we keep the value the property had before
1457
1458 xmlChar* denominator_value = xmlGetProp(node, BAD_CAST "denominator");
1459 if (denominator_value)
1460 denominator = atoi(reinterpret_cast<char*>(denominator_value));
1461}
1462
1463void MetricsService::GetSettingsFromUploadNode(xmlNodePtr upload_node) {
1464 InheritedProperties props;
1465 GetSettingsFromUploadNodeRecursive(upload_node, props, "", true);
1466}
1467
pkasting@chromium.orgcac78842008-11-27 01:02:201468void MetricsService::GetSettingsFromUploadNodeRecursive(
1469 xmlNodePtr node,
1470 InheritedProperties props,
1471 std::string path_prefix,
1472 bool uploadOn) {
petersont@google.comd01b8732008-10-16 02:18:071473 props.OverwriteWhereNeeded(node);
1474
1475 // The bool uploadOn is set to true if the data represented by current
1476 // node should be uploaded. This gets inherited in the tree; the children
1477 // of a node that has already been rejected for upload get rejected for
1478 // upload.
1479 uploadOn = uploadOn && NodeProbabilityTest(node, props);
1480
1481 // The path is a / separated list of the node names ancestral to the current
1482 // one. So, if you want to check if the current node has a certain name,
1483 // compare to name. If you want to check if it is a certan tag at a certain
1484 // place in the tree, compare to the whole path.
1485 std::string name = std::string(reinterpret_cast<const char*>(node->name));
1486 std::string path = path_prefix + "/" + name;
1487
1488 if (path == "/upload") {
1489 xmlChar* upload_interval_val = xmlGetProp(node, BAD_CAST "interval");
1490 if (upload_interval_val) {
1491 interlog_duration_ = TimeDelta::FromSeconds(
1492 atoi(reinterpret_cast<char*>(upload_interval_val)));
1493 }
1494
1495 server_permits_upload_ = uploadOn;
1496 }
1497 if (path == "/upload/logs") {
1498 xmlChar* log_event_limit_val = xmlGetProp(node, BAD_CAST "event_limit");
1499 if (log_event_limit_val)
1500 log_event_limit_ = atoi(reinterpret_cast<char*>(log_event_limit_val));
1501 }
1502 if (name == "histogram") {
1503 xmlChar* type_value = xmlGetProp(node, BAD_CAST "type");
1504 if (type_value) {
1505 std::string type = (reinterpret_cast<char*>(type_value));
1506 if (uploadOn)
1507 histograms_to_upload_.insert(type);
1508 else
1509 histograms_to_omit_.insert(type);
1510 }
1511 }
1512 if (name == "log") {
1513 xmlChar* type_value = xmlGetProp(node, BAD_CAST "type");
1514 if (type_value) {
1515 std::string type = (reinterpret_cast<char*>(type_value));
1516 if (uploadOn)
1517 logs_to_upload_.insert(type);
1518 else
1519 logs_to_omit_.insert(type);
1520 }
1521 }
1522
1523 // Recursive call. If the node is a leaf i.e. if it ends in a "/>", then it
1524 // doesn't have children, so node->children is NULL, and this loop doesn't
1525 // call (that's how the recursion ends).
1526 for (xmlNodePtr child_node = node->children;
pkasting@chromium.orgcac78842008-11-27 01:02:201527 child_node;
1528 child_node = child_node->next) {
petersont@google.comd01b8732008-10-16 02:18:071529 GetSettingsFromUploadNodeRecursive(child_node, props, path, uploadOn);
1530 }
1531}
1532
1533bool MetricsService::NodeProbabilityTest(xmlNodePtr node,
pkasting@chromium.orgcac78842008-11-27 01:02:201534 InheritedProperties props) const {
petersont@google.comd01b8732008-10-16 02:18:071535 // Default value of probability on any node is 1, but recall that
1536 // its parents can already have been rejected for upload.
1537 double probability = 1;
1538
1539 // If a probability is specified in the node, we use it instead.
1540 xmlChar* probability_value = xmlGetProp(node, BAD_CAST "probability");
1541 if (probability_value)
jar@google.com0b33f80b2008-12-17 21:34:361542 probability = atoi(reinterpret_cast<char*>(probability_value));
petersont@google.comd01b8732008-10-16 02:18:071543
1544 return ProbabilityTest(probability, props.salt, props.denominator);
1545}
1546
1547bool MetricsService::ProbabilityTest(double probability,
1548 int salt,
1549 int denominator) const {
1550 // Okay, first we figure out how many of the digits of the
1551 // client_id_ we need in order to make a nice pseudorandomish
1552 // number in the range [0,denominator). Too many digits is
1553 // fine.
petersont@google.comd01b8732008-10-16 02:18:071554
1555 // n is the length of the client_id_ string
1556 size_t n = client_id_.size();
1557
1558 // idnumber is a positive integer generated from the client_id_.
1559 // It plus salt is going to give us our pseudorandom number.
1560 int idnumber = 0;
1561 const char* client_id_c_str = client_id_.c_str();
1562
1563 // Here we hash the relevant digits of the client_id_
1564 // string somehow to get a big integer idnumber (could be negative
1565 // from wraparound)
1566 int big = 1;
robertshield@google.com5ed73342009-03-18 17:39:431567 int last_pos = n - 1;
1568 for (size_t j = 0; j < n; ++j) {
1569 idnumber += static_cast<int>(client_id_c_str[last_pos - j]) * big;
petersont@google.comd01b8732008-10-16 02:18:071570 big *= 10;
1571 }
1572
1573 // Mod id number by denominator making sure to get a non-negative
1574 // answer.
pkasting@chromium.orgcac78842008-11-27 01:02:201575 idnumber = ((idnumber % denominator) + denominator) % denominator;
petersont@google.comd01b8732008-10-16 02:18:071576
pkasting@chromium.orgcac78842008-11-27 01:02:201577 // ((idnumber + salt) % denominator) / denominator is in the range [0,1]
petersont@google.comd01b8732008-10-16 02:18:071578 // if it's less than probability we call that an affirmative coin
1579 // toss.
pkasting@chromium.orgcac78842008-11-27 01:02:201580 return static_cast<double>((idnumber + salt) % denominator) <
1581 probability * denominator;
petersont@google.comd01b8732008-10-16 02:18:071582}
1583
initial.commit09911bf2008-07-26 23:55:291584void MetricsService::LogWindowChange(NotificationType type,
1585 const NotificationSource& source,
1586 const NotificationDetails& details) {
brettw@google.com534e54b2008-08-13 15:40:091587 int controller_id = -1;
1588 uintptr_t window_or_tab = source.map_key();
initial.commit09911bf2008-07-26 23:55:291589 MetricsLog::WindowEventType window_type;
1590
1591 // Note: since we stop all logging when a single OTR session is active, it is
1592 // possible that we start getting notifications about a window that we don't
1593 // know about.
brettw@google.com534e54b2008-08-13 15:40:091594 if (window_map_.find(window_or_tab) == window_map_.end()) {
1595 controller_id = next_window_id_++;
1596 window_map_[window_or_tab] = controller_id;
initial.commit09911bf2008-07-26 23:55:291597 } else {
brettw@google.com534e54b2008-08-13 15:40:091598 controller_id = window_map_[window_or_tab];
initial.commit09911bf2008-07-26 23:55:291599 }
jar@chromium.org92745242009-06-12 16:52:211600 DCHECK_NE(controller_id, -1);
initial.commit09911bf2008-07-26 23:55:291601
brettw@chromium.orgbfd04a62009-02-01 18:16:561602 switch (type.value) {
1603 case NotificationType::TAB_PARENTED:
1604 case NotificationType::BROWSER_OPENED:
initial.commit09911bf2008-07-26 23:55:291605 window_type = MetricsLog::WINDOW_CREATE;
1606 break;
1607
brettw@chromium.orgbfd04a62009-02-01 18:16:561608 case NotificationType::TAB_CLOSING:
1609 case NotificationType::BROWSER_CLOSED:
brettw@google.com534e54b2008-08-13 15:40:091610 window_map_.erase(window_map_.find(window_or_tab));
initial.commit09911bf2008-07-26 23:55:291611 window_type = MetricsLog::WINDOW_DESTROY;
1612 break;
1613
1614 default:
jar@chromium.orgb42c5e42010-06-03 20:43:251615 LOG(DFATAL);
paul@chromium.org68d74f02009-02-13 01:36:501616 return;
initial.commit09911bf2008-07-26 23:55:291617 }
1618
brettw@google.com534e54b2008-08-13 15:40:091619 // TODO(brettw) we should have some kind of ID for the parent.
1620 current_log_->RecordWindowEvent(window_type, controller_id, 0);
initial.commit09911bf2008-07-26 23:55:291621}
1622
1623void MetricsService::LogLoadComplete(NotificationType type,
1624 const NotificationSource& source,
1625 const NotificationDetails& details) {
1626 if (details == NotificationService::NoDetails())
1627 return;
1628
jar@google.com68475e602008-08-22 03:21:151629 // TODO(jar): There is a bug causing this to be called too many times, and
1630 // the log overflows. For now, we won't record these events.
dsh@google.com553dba62009-02-24 19:08:231631 UMA_HISTOGRAM_COUNTS("UMA.LogLoadComplete called", 1);
jar@google.com68475e602008-08-22 03:21:151632 return;
1633
initial.commit09911bf2008-07-26 23:55:291634 const Details<LoadNotificationDetails> load_details(details);
brettw@google.com534e54b2008-08-13 15:40:091635 int controller_id = window_map_[details.map_key()];
1636 current_log_->RecordLoadEvent(controller_id,
initial.commit09911bf2008-07-26 23:55:291637 load_details->url(),
1638 load_details->origin(),
1639 load_details->session_index(),
1640 load_details->load_time());
1641}
1642
cpu@google.come73c01972008-08-13 00:18:241643void MetricsService::IncrementPrefValue(const wchar_t* path) {
1644 PrefService* pref = g_browser_process->local_state();
1645 DCHECK(pref);
1646 int value = pref->GetInteger(path);
1647 pref->SetInteger(path, value + 1);
1648}
1649
robertshield@google.com0bb1a622009-03-04 03:22:321650void MetricsService::IncrementLongPrefsValue(const wchar_t* path) {
1651 PrefService* pref = g_browser_process->local_state();
1652 DCHECK(pref);
1653 int64 value = pref->GetInt64(path);
jar@chromium.orgb42c5e42010-06-03 20:43:251654 pref->SetInt64(path, value + 1);
robertshield@google.com0bb1a622009-03-04 03:22:321655}
1656
initial.commit09911bf2008-07-26 23:55:291657void MetricsService::LogLoadStarted() {
cpu@google.come73c01972008-08-13 00:18:241658 IncrementPrefValue(prefs::kStabilityPageLoadCount);
robertshield@google.com0bb1a622009-03-04 03:22:321659 IncrementLongPrefsValue(prefs::kUninstallMetricsPageLoadCount);
jar@google.com0b33f80b2008-12-17 21:34:361660 // We need to save the prefs, as page load count is a critical stat, and it
1661 // might be lost due to a crash :-(.
initial.commit09911bf2008-07-26 23:55:291662}
1663
initial.commit09911bf2008-07-26 23:55:291664void MetricsService::LogRendererCrash() {
cpu@google.come73c01972008-08-13 00:18:241665 IncrementPrefValue(prefs::kStabilityRendererCrashCount);
initial.commit09911bf2008-07-26 23:55:291666}
1667
asargent@chromium.org1f085622009-12-04 05:33:451668void MetricsService::LogExtensionRendererCrash() {
1669 IncrementPrefValue(prefs::kStabilityExtensionRendererCrashCount);
1670}
1671
initial.commit09911bf2008-07-26 23:55:291672void MetricsService::LogRendererHang() {
cpu@google.come73c01972008-08-13 00:18:241673 IncrementPrefValue(prefs::kStabilityRendererHangCount);
initial.commit09911bf2008-07-26 23:55:291674}
1675
jam@chromium.orga27a9382009-02-11 23:55:101676void MetricsService::LogChildProcessChange(
1677 NotificationType type,
1678 const NotificationSource& source,
1679 const NotificationDetails& details) {
gregoryd@google.com0d84c5d2009-10-09 01:10:421680 Details<ChildProcessInfo> child_details(details);
1681 const std::wstring& child_name = child_details->name();
1682
jam@chromium.orga27a9382009-02-11 23:55:101683 if (child_process_stats_buffer_.find(child_name) ==
1684 child_process_stats_buffer_.end()) {
gregoryd@google.com0d84c5d2009-10-09 01:10:421685 child_process_stats_buffer_[child_name] =
1686 ChildProcessStats(child_details->type());
initial.commit09911bf2008-07-26 23:55:291687 }
1688
jam@chromium.orga27a9382009-02-11 23:55:101689 ChildProcessStats& stats = child_process_stats_buffer_[child_name];
brettw@chromium.orgbfd04a62009-02-01 18:16:561690 switch (type.value) {
jam@chromium.orga27a9382009-02-11 23:55:101691 case NotificationType::CHILD_PROCESS_HOST_CONNECTED:
initial.commit09911bf2008-07-26 23:55:291692 stats.process_launches++;
1693 break;
1694
jam@chromium.orga27a9382009-02-11 23:55:101695 case NotificationType::CHILD_INSTANCE_CREATED:
initial.commit09911bf2008-07-26 23:55:291696 stats.instances++;
1697 break;
1698
jam@chromium.orga27a9382009-02-11 23:55:101699 case NotificationType::CHILD_PROCESS_CRASHED:
initial.commit09911bf2008-07-26 23:55:291700 stats.process_crashes++;
asargent@chromium.org1f085622009-12-04 05:33:451701 // Exclude plugin crashes from the count below because we report them via
1702 // a separate UMA metric.
1703 if (child_details->type() != ChildProcessInfo::PLUGIN_PROCESS) {
1704 IncrementPrefValue(prefs::kStabilityChildProcessCrashCount);
1705 }
initial.commit09911bf2008-07-26 23:55:291706 break;
1707
1708 default:
jar@chromium.orgb42c5e42010-06-03 20:43:251709 LOG(DFATAL) << "Unexpected notification type " << type.value;
initial.commit09911bf2008-07-26 23:55:291710 return;
1711 }
1712}
1713
1714// Recursively counts the number of bookmarks and folders in node.
munjal@chromium.orgb3c33d462009-06-26 22:29:201715static void CountBookmarks(const BookmarkNode* node,
1716 int* bookmarks,
1717 int* folders) {
sky@chromium.org037db002009-10-19 20:06:081718 if (node->type() == BookmarkNode::URL)
initial.commit09911bf2008-07-26 23:55:291719 (*bookmarks)++;
1720 else
1721 (*folders)++;
1722 for (int i = 0; i < node->GetChildCount(); ++i)
1723 CountBookmarks(node->GetChild(i), bookmarks, folders);
1724}
1725
munjal@chromium.orgb3c33d462009-06-26 22:29:201726void MetricsService::LogBookmarks(const BookmarkNode* node,
initial.commit09911bf2008-07-26 23:55:291727 const wchar_t* num_bookmarks_key,
1728 const wchar_t* num_folders_key) {
1729 DCHECK(node);
1730 int num_bookmarks = 0;
1731 int num_folders = 0;
1732 CountBookmarks(node, &num_bookmarks, &num_folders);
1733 num_folders--; // Don't include the root folder in the count.
1734
1735 PrefService* pref = g_browser_process->local_state();
1736 DCHECK(pref);
1737 pref->SetInteger(num_bookmarks_key, num_bookmarks);
1738 pref->SetInteger(num_folders_key, num_folders);
1739}
1740
sky@google.comd8e41ed2008-09-11 15:22:321741void MetricsService::LogBookmarks(BookmarkModel* model) {
initial.commit09911bf2008-07-26 23:55:291742 DCHECK(model);
1743 LogBookmarks(model->GetBookmarkBarNode(),
1744 prefs::kNumBookmarksOnBookmarkBar,
1745 prefs::kNumFoldersOnBookmarkBar);
1746 LogBookmarks(model->other_node(),
1747 prefs::kNumBookmarksInOtherBookmarkFolder,
1748 prefs::kNumFoldersInOtherBookmarkFolder);
1749 ScheduleNextStateSave();
1750}
1751
1752void MetricsService::LogKeywords(const TemplateURLModel* url_model) {
1753 DCHECK(url_model);
1754
1755 PrefService* pref = g_browser_process->local_state();
1756 DCHECK(pref);
1757 pref->SetInteger(prefs::kNumKeywords,
1758 static_cast<int>(url_model->GetTemplateURLs().size()));
1759 ScheduleNextStateSave();
1760}
1761
1762void MetricsService::RecordPluginChanges(PrefService* pref) {
1763 ListValue* plugins = pref->GetMutableList(prefs::kStabilityPluginStats);
1764 DCHECK(plugins);
1765
1766 for (ListValue::iterator value_iter = plugins->begin();
1767 value_iter != plugins->end(); ++value_iter) {
1768 if (!(*value_iter)->IsType(Value::TYPE_DICTIONARY)) {
jar@chromium.orgb42c5e42010-06-03 20:43:251769 LOG(DFATAL);
initial.commit09911bf2008-07-26 23:55:291770 continue;
1771 }
1772
1773 DictionaryValue* plugin_dict = static_cast<DictionaryValue*>(*value_iter);
nsylvain@chromium.org8e50b602009-03-03 22:59:431774 std::wstring plugin_name;
1775 plugin_dict->GetString(prefs::kStabilityPluginName, &plugin_name);
nsylvain@chromium.org6470ee8f2009-03-03 20:46:401776 if (plugin_name.empty()) {
jar@chromium.orgb42c5e42010-06-03 20:43:251777 LOG(DFATAL);
initial.commit09911bf2008-07-26 23:55:291778 continue;
1779 }
1780
nsylvain@chromium.org8e50b602009-03-03 22:59:431781 if (child_process_stats_buffer_.find(plugin_name) ==
jam@chromium.orga27a9382009-02-11 23:55:101782 child_process_stats_buffer_.end())
initial.commit09911bf2008-07-26 23:55:291783 continue;
1784
nsylvain@chromium.org8e50b602009-03-03 22:59:431785 ChildProcessStats stats = child_process_stats_buffer_[plugin_name];
initial.commit09911bf2008-07-26 23:55:291786 if (stats.process_launches) {
1787 int launches = 0;
nsylvain@chromium.org8e50b602009-03-03 22:59:431788 plugin_dict->GetInteger(prefs::kStabilityPluginLaunches, &launches);
initial.commit09911bf2008-07-26 23:55:291789 launches += stats.process_launches;
nsylvain@chromium.org8e50b602009-03-03 22:59:431790 plugin_dict->SetInteger(prefs::kStabilityPluginLaunches, launches);
initial.commit09911bf2008-07-26 23:55:291791 }
1792 if (stats.process_crashes) {
1793 int crashes = 0;
nsylvain@chromium.org8e50b602009-03-03 22:59:431794 plugin_dict->GetInteger(prefs::kStabilityPluginCrashes, &crashes);
initial.commit09911bf2008-07-26 23:55:291795 crashes += stats.process_crashes;
nsylvain@chromium.org8e50b602009-03-03 22:59:431796 plugin_dict->SetInteger(prefs::kStabilityPluginCrashes, crashes);
initial.commit09911bf2008-07-26 23:55:291797 }
1798 if (stats.instances) {
1799 int instances = 0;
nsylvain@chromium.org8e50b602009-03-03 22:59:431800 plugin_dict->GetInteger(prefs::kStabilityPluginInstances, &instances);
initial.commit09911bf2008-07-26 23:55:291801 instances += stats.instances;
nsylvain@chromium.org8e50b602009-03-03 22:59:431802 plugin_dict->SetInteger(prefs::kStabilityPluginInstances, instances);
initial.commit09911bf2008-07-26 23:55:291803 }
1804
nsylvain@chromium.org8e50b602009-03-03 22:59:431805 child_process_stats_buffer_.erase(plugin_name);
initial.commit09911bf2008-07-26 23:55:291806 }
1807
1808 // Now go through and add dictionaries for plugins that didn't already have
1809 // reports in Local State.
jam@chromium.orga27a9382009-02-11 23:55:101810 for (std::map<std::wstring, ChildProcessStats>::iterator cache_iter =
1811 child_process_stats_buffer_.begin();
1812 cache_iter != child_process_stats_buffer_.end(); ++cache_iter) {
jam@chromium.orga27a9382009-02-11 23:55:101813 ChildProcessStats stats = cache_iter->second;
gregoryd@google.com0d84c5d2009-10-09 01:10:421814
1815 // Insert only plugins information into the plugins list.
1816 if (ChildProcessInfo::PLUGIN_PROCESS != stats.process_type)
1817 continue;
1818
1819 std::wstring plugin_name = cache_iter->first;
1820
initial.commit09911bf2008-07-26 23:55:291821 DictionaryValue* plugin_dict = new DictionaryValue;
1822
nsylvain@chromium.org8e50b602009-03-03 22:59:431823 plugin_dict->SetString(prefs::kStabilityPluginName, plugin_name);
1824 plugin_dict->SetInteger(prefs::kStabilityPluginLaunches,
initial.commit09911bf2008-07-26 23:55:291825 stats.process_launches);
nsylvain@chromium.org8e50b602009-03-03 22:59:431826 plugin_dict->SetInteger(prefs::kStabilityPluginCrashes,
initial.commit09911bf2008-07-26 23:55:291827 stats.process_crashes);
nsylvain@chromium.org8e50b602009-03-03 22:59:431828 plugin_dict->SetInteger(prefs::kStabilityPluginInstances,
initial.commit09911bf2008-07-26 23:55:291829 stats.instances);
1830 plugins->Append(plugin_dict);
1831 }
jam@chromium.orga27a9382009-02-11 23:55:101832 child_process_stats_buffer_.clear();
initial.commit09911bf2008-07-26 23:55:291833}
1834
1835bool MetricsService::CanLogNotification(NotificationType type,
1836 const NotificationSource& source,
1837 const NotificationDetails& details) {
1838 // We simply don't log anything to UMA if there is a single off the record
1839 // session visible. The problem is that we always notify using the orginal
1840 // profile in order to simplify notification processing.
1841 return !BrowserList::IsOffTheRecordSessionActive();
1842}
1843
1844void MetricsService::RecordBooleanPrefValue(const wchar_t* path, bool value) {
1845 DCHECK(IsSingleThreaded());
1846
1847 PrefService* pref = g_browser_process->local_state();
1848 DCHECK(pref);
1849
1850 pref->SetBoolean(path, value);
1851 RecordCurrentState(pref);
1852}
1853
1854void MetricsService::RecordCurrentState(PrefService* pref) {
robertshield@google.com0bb1a622009-03-04 03:22:321855 pref->SetInt64(prefs::kStabilityLastTimestampSec, Time::Now().ToTimeT());
initial.commit09911bf2008-07-26 23:55:291856
1857 RecordPluginChanges(pref);
1858}
1859
1860void MetricsService::RecordCurrentHistograms() {
1861 DCHECK(current_log_);
1862
1863 StatisticsRecorder::Histograms histograms;
1864 StatisticsRecorder::GetHistograms(&histograms);
1865 for (StatisticsRecorder::Histograms::iterator it = histograms.begin();
1866 histograms.end() != it;
pkasting@chromium.orgcac78842008-11-27 01:02:201867 ++it) {
jar@chromium.org2753b392009-12-28 06:59:521868 if ((*it)->flags() & Histogram::kUmaTargetedHistogramFlag)
jar@google.com0b33f80b2008-12-17 21:34:361869 // TODO(petersont): Only record historgrams if they are not precluded by
1870 // the UMA response data.
petersont@google.comd01b8732008-10-16 02:18:071871 // Bug http://code.google.com/p/chromium/issues/detail?id=2739.
initial.commit09911bf2008-07-26 23:55:291872 RecordHistogram(**it);
1873 }
1874}
1875
1876void MetricsService::RecordHistogram(const Histogram& histogram) {
1877 // Get up-to-date snapshot of sample stats.
1878 Histogram::SampleSet snapshot;
1879 histogram.SnapshotSample(&snapshot);
1880
1881 const std::string& histogram_name = histogram.histogram_name();
1882
1883 // Find the already sent stats, or create an empty set.
1884 LoggedSampleMap::iterator it = logged_samples_.find(histogram_name);
1885 Histogram::SampleSet* already_logged;
1886 if (logged_samples_.end() == it) {
1887 // Add new entry
1888 already_logged = &logged_samples_[histogram.histogram_name()];
1889 already_logged->Resize(histogram); // Complete initialization.
1890 } else {
1891 already_logged = &(it->second);
1892 // Deduct any stats we've already logged from our snapshot.
1893 snapshot.Subtract(*already_logged);
1894 }
1895
1896 // snapshot now contains only a delta to what we've already_logged.
1897
1898 if (snapshot.TotalCount() > 0) {
1899 current_log_->RecordHistogramDelta(histogram, snapshot);
1900 // Add new data into our running total.
1901 already_logged->Add(snapshot);
1902 }
1903}
1904
initial.commit09911bf2008-07-26 23:55:291905static bool IsSingleThreaded() {
paul@chromium.orgdc6f4962009-02-13 01:25:501906 static PlatformThreadId thread_id = 0;
initial.commit09911bf2008-07-26 23:55:291907 if (!thread_id)
paul@chromium.orgdc6f4962009-02-13 01:25:501908 thread_id = PlatformThread::CurrentId();
1909 return PlatformThread::CurrentId() == thread_id;
initial.commit09911bf2008-07-26 23:55:291910}
rvargas@google.com5ccaa412009-11-13 22:00:161911
1912#if defined(OS_CHROMEOS)
sky@chromium.org29cf16772010-04-21 15:13:471913void MetricsService::StartExternalMetrics() {
rvargas@google.com5ccaa412009-11-13 22:00:161914 external_metrics_ = new chromeos::ExternalMetrics;
sky@chromium.org29cf16772010-04-21 15:13:471915 external_metrics_->Start();
rvargas@google.com5ccaa412009-11-13 22:00:161916}
1917#endif