blob: 64fdd67981c5e49e4dc86eccc7aa307b8739b9a8 [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.
zelidrag@chromium.org85ed9d42010-06-08 22:37:4485// INIT_TASK_SCHEDULED, // Waiting for deferred init tasks to complete.
86// INIT_TASK_DONE, // Waiting for timer to send initial log.
initial.commit09911bf2008-07-26 23:55:2987// 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//
zelidrag@chromium.org85ed9d42010-06-08 22:37:4498// INIT_TASK_SCHEDULED, // Waiting for deferred init tasks to complete.
initial.commit09911bf2008-07-26 23:55:2999// Typically about 30 seconds after startup, a task is sent to a second thread
zelidrag@chromium.org85ed9d42010-06-08 22:37:44100// (the file thread) to perform deferred (lower priority and slower)
101// initialization steps such as getting the list of plugins. That task will
102// (when complete) make an async callback (via a Task) to indicate the
103// completion.
initial.commit09911bf2008-07-26 23:55:29104//
zelidrag@chromium.org85ed9d42010-06-08 22:37:44105// INIT_TASK_DONE, // Waiting for timer to send initial log.
initial.commit09911bf2008-07-26 23:55:29106// The callback has arrived, and it is now possible for an initial log to be
107// created. This callback typically arrives back less than one second after
zelidrag@chromium.org85ed9d42010-06-08 22:37:44108// the deferred init task is dispatched.
initial.commit09911bf2008-07-26 23:55:29109//
110// INITIAL_LOG_READY, // Initial log generated, and waiting for reply.
111// This state is entered only after an initial log has been composed, and
112// prepared for transmission. It is also the case that any previously unsent
113// logs have been loaded into instance variables for possible transmission.
114//
115// SEND_OLD_INITIAL_LOGS, // Sending unsent logs from previous session.
116// This state indicates that the initial log for this session has been
117// successfully sent and it is now time to send any "initial logs" that were
118// saved from previous sessions. Most commonly, there are none, but all old
119// logs that were "initial logs" must be sent before this state is exited.
120//
121// SENDING_OLD_LOGS, // Sending unsent logs from previous session.
122// This state indicates that there are no more unsent initial logs, and now any
123// ongoing logs from previous sessions should be transmitted. All such logs
124// will be transmitted before exiting this state, and proceeding with ongoing
125// logs from the current session (see next state).
126//
127// SENDING_CURRENT_LOGS, // Sending standard current logs as they accrue.
jar@google.com0b33f80b2008-12-17 21:34:36128// Current logs are being accumulated. Typically every 20 minutes a log is
initial.commit09911bf2008-07-26 23:55:29129// closed and finalized for transmission, at the same time as a new log is
130// started.
131//
132// The progression through the above states is simple, and sequential, in the
133// most common use cases. States proceed from INITIAL to SENDING_CURRENT_LOGS,
134// and remain in the latter until shutdown.
135//
136// The one unusual case is when the user asks that we stop logging. When that
137// happens, any pending (transmission in progress) log is pushed into the list
138// of old unsent logs (the appropriate list, depending on whether it is an
139// initial log, or an ongoing log). An addition, any log that is currently
140// accumulating is also finalized, and pushed into the unsent log list. With
jar@chromium.org281d2882009-01-20 20:32:42141// those pushes performed, we regress back to the SEND_OLD_INITIAL_LOGS state in
initial.commit09911bf2008-07-26 23:55:29142// case the user enables log recording again during this session. This way
143// anything we have "pushed back" will be sent automatically if/when we progress
144// back to SENDING_CURRENT_LOG state.
145//
146// Also note that whenever the member variables containing unsent logs are
147// modified (i.e., when we send an old log), we mirror the list of logs into
148// the PrefServices. This ensures that IF we crash, we won't start up and
149// retransmit our old logs again.
150//
151// Due to race conditions, it is always possible that a log file could be sent
152// twice. For example, if a log file is sent, but not yet acknowledged by
153// the external server, and the user shuts down, then a copy of the log may be
154// saved for re-transmission. These duplicates could be filtered out server
jar@chromium.org281d2882009-01-20 20:32:42155// side, but are not expected to be a significant problem.
initial.commit09911bf2008-07-26 23:55:29156//
157//
158//------------------------------------------------------------------------------
159
maruel@chromium.org40bcc302009-03-02 20:50:39160#include "chrome/browser/metrics/metrics_service.h"
161
paul@chromium.orgdc6f4962009-02-13 01:25:50162#if defined(OS_WIN)
initial.commit09911bf2008-07-26 23:55:29163#include <windows.h>
maruel@chromium.org40bcc302009-03-02 20:50:39164#include <objbase.h>
paul@chromium.orgdc6f4962009-02-13 01:25:50165#endif
initial.commit09911bf2008-07-26 23:55:29166
agl@chromium.org7ef52bf2009-08-06 19:04:50167#if defined(USE_SYSTEM_LIBBZ2)
168#include <bzlib.h>
169#else
170#include "third_party/bzip2/bzlib.h"
171#endif
172
pkasting@chromium.org4d022ff2009-10-23 18:47:09173#include "base/thread.h"
sky@google.comd8e41ed2008-09-11 15:22:32174#include "chrome/browser/bookmarks/bookmark_model.h"
initial.commit09911bf2008-07-26 23:55:29175#include "chrome/browser/browser_list.h"
176#include "chrome/browser/browser_process.h"
177#include "chrome/browser/load_notification_details.h"
178#include "chrome/browser/memory_details.h"
phajdan.jr@chromium.org7c927b62010-02-24 09:54:13179#include "chrome/browser/metrics/histogram_synchronizer.h"
phajdan.jr@chromium.org052313b2010-02-19 09:43:08180#include "chrome/browser/pref_service.h"
initial.commit09911bf2008-07-26 23:55:29181#include "chrome/browser/profile.h"
brettw@chromium.org8c8657d62009-01-16 18:31:26182#include "chrome/browser/renderer_host/render_process_host.h"
ben@chromium.orgd54e03a52009-01-16 00:31:04183#include "chrome/browser/search_engines/template_url_model.h"
kuchhal@chromium.org157d5472009-11-05 22:31:03184#include "chrome/common/child_process_logging.h"
jar@chromium.org92745242009-06-12 16:52:21185#include "chrome/common/chrome_switches.h"
brettw@chromium.orgbfd04a62009-02-01 18:16:56186#include "chrome/common/notification_service.h"
initial.commit09911bf2008-07-26 23:55:29187#include "chrome/common/pref_names.h"
jam@chromium.orge09ba552009-02-05 03:26:29188#include "chrome/common/render_messages.h"
jam@chromium.org35fa6a22009-08-15 00:04:01189#include "webkit/glue/plugins/plugin_list.h"
mad@google.comae393ec702010-06-27 16:23:14190#include "libxml/xmlwriter.h"
initial.commit09911bf2008-07-26 23:55:29191
pkasting@chromium.org4d022ff2009-10-23 18:47:09192#if !defined(OS_WIN)
193#include "base/rand_util.h"
194#endif
195
phajdan.jr@chromium.orge06131d2010-02-10 18:40:33196// TODO(port): port browser_distribution.h.
197#if !defined(OS_POSIX)
kuchhal@chromium.org79bf0b72009-04-27 21:30:55198#include "chrome/installer/util/browser_distribution.h"
paul@chromium.orgdc6f4962009-02-13 01:25:50199#endif
200
rvargas@google.com5ccaa412009-11-13 22:00:16201#if defined(OS_CHROMEOS)
202#include "chrome/browser/chromeos/external_metrics.h"
zelidrag@chromium.org85ed9d42010-06-08 22:37:44203
204static const char kHardwareClassTool[] = "/usr/bin/hardware_class";
205static const char kUnknownHardwareClass[] = "unknown";
rvargas@google.com5ccaa412009-11-13 22:00:16206#endif
207
dsh@google.come1acf6f2008-10-27 20:43:33208using base::Time;
209using base::TimeDelta;
210
initial.commit09911bf2008-07-26 23:55:29211// Check to see that we're being called on only one thread.
212static bool IsSingleThreaded();
213
initial.commit09911bf2008-07-26 23:55:29214static const char kMetricsType[] = "application/vnd.mozilla.metrics.bz2";
215
216// The delay, in seconds, after startup before sending the first log message.
petersont@google.com252873ef2008-08-04 21:59:45217static const int kInitialInterlogDuration = 60; // one minute
218
jar@chromium.orgc9a3ef82009-05-28 22:02:46219// This specifies the amount of time to wait for all renderers to send their
220// data.
221static const int kMaxHistogramGatheringWaitDuration = 60000; // 60 seconds.
222
petersont@google.com252873ef2008-08-04 21:59:45223// The default maximum number of events in a log uploaded to the UMA server.
jar@google.com0b33f80b2008-12-17 21:34:36224static const int kInitialEventLimit = 2400;
jar@google.com68475e602008-08-22 03:21:15225
226// If an upload fails, and the transmission was over this byte count, then we
227// will discard the log, and not try to retransmit it. We also don't persist
228// the log to the prefs for transmission during the next chrome session if this
229// limit is exceeded.
230static const int kUploadLogAvoidRetransmitSize = 50000;
initial.commit09911bf2008-07-26 23:55:29231
232// When we have logs from previous Chrome sessions to send, how long should we
233// delay (in seconds) between each log transmission.
234static const int kUnsentLogDelay = 15; // 15 seconds
235
236// Minimum time a log typically exists before sending, in seconds.
237// This number is supplied by the server, but until we parse it out of a server
238// response, we use this duration to specify how long we should wait before
239// sending the next log. If the channel is busy, such as when there is a
240// failure during an attempt to transmit a previous log, then a log may wait
jar@chromium.org2fe42fe2010-05-07 19:22:39241// (and continue to accrue new log entries) for a much greater period of time.
242static const int kMinSecondsPerLog = 30 * 60; // Thirty minutes.
initial.commit09911bf2008-07-26 23:55:29243
initial.commit09911bf2008-07-26 23:55:29244// When we don't succeed at transmitting a log to a server, we progressively
245// wait longer and longer before sending the next log. This backoff process
246// help reduce load on the server, and makes the amount of backoff vary between
247// clients so that a collision (server overload?) on retransmit is less likely.
248// The following is the constant we use to expand that inter-log duration.
249static const double kBackoff = 1.1;
250// We limit the maximum backoff to be no greater than some multiple of the
251// default kMinSecondsPerLog. The following is that maximum ratio.
252static const int kMaxBackoff = 10;
253
254// Interval, in seconds, between state saves.
255static const int kSaveStateInterval = 5 * 60; // five minutes
256
257// The number of "initial" logs we're willing to save, and hope to send during
258// a future Chrome session. Initial logs contain crash stats, and are pretty
259// small.
260static const size_t kMaxInitialLogsPersisted = 20;
261
262// The number of ongoing logs we're willing to save persistently, and hope to
jar@chromium.org281d2882009-01-20 20:32:42263// send during a this or future sessions. Note that each log may be pretty
initial.commit09911bf2008-07-26 23:55:29264// large, as presumably the related "initial" log wasn't sent (probably nothing
265// was, as the user was probably off-line). As a result, the log probably kept
266// accumulating while the "initial" log was stalled (pending_), and couldn't be
267// sent. As a result, we don't want to save too many of these mega-logs.
268// A "standard shutdown" will create a small log, including just the data that
269// was not yet been transmitted, and that is normal (to have exactly one
270// ongoing_log_ at startup).
jar@chromium.org281d2882009-01-20 20:32:42271static const size_t kMaxOngoingLogsPersisted = 8;
initial.commit09911bf2008-07-26 23:55:29272
273
274// Handles asynchronous fetching of memory details.
275// Will run the provided task after finished.
276class MetricsMemoryDetails : public MemoryDetails {
277 public:
278 explicit MetricsMemoryDetails(Task* completion) : completion_(completion) {}
279
280 virtual void OnDetailsAvailable() {
281 MessageLoop::current()->PostTask(FROM_HERE, completion_);
282 }
283
284 private:
jam@chromium.orge6e6ba42009-11-07 01:56:19285 ~MetricsMemoryDetails() {}
286
initial.commit09911bf2008-07-26 23:55:29287 Task* completion_;
tfarina@chromium.org4d818fee2010-06-06 13:32:27288 DISALLOW_COPY_AND_ASSIGN(MetricsMemoryDetails);
initial.commit09911bf2008-07-26 23:55:29289};
290
zelidrag@chromium.org85ed9d42010-06-08 22:37:44291class MetricsService::InitTaskComplete : public Task {
jam@chromium.org35fa6a22009-08-15 00:04:01292 public:
zelidrag@chromium.org85ed9d42010-06-08 22:37:44293 explicit InitTaskComplete(const std::string& hardware_class,
294 const std::vector<WebPluginInfo>& plugins)
295 : hardware_class_(hardware_class), plugins_(plugins) {}
296
jamesr@chromium.org7f2e792e2009-11-30 23:18:29297 virtual void Run() {
zelidrag@chromium.org85ed9d42010-06-08 22:37:44298 g_browser_process->metrics_service()->OnInitTaskComplete(
299 hardware_class_, plugins_);
initial.commit09911bf2008-07-26 23:55:29300 }
jam@chromium.org35fa6a22009-08-15 00:04:01301
jamesr@chromium.org7f2e792e2009-11-30 23:18:29302 private:
zelidrag@chromium.org85ed9d42010-06-08 22:37:44303 std::string hardware_class_;
jamesr@chromium.org7f2e792e2009-11-30 23:18:29304 std::vector<WebPluginInfo> plugins_;
initial.commit09911bf2008-07-26 23:55:29305};
306
zelidrag@chromium.org85ed9d42010-06-08 22:37:44307class MetricsService::InitTask : public Task {
jamesr@chromium.org7f2e792e2009-11-30 23:18:29308 public:
zelidrag@chromium.org85ed9d42010-06-08 22:37:44309 explicit InitTask(MessageLoop* callback_loop)
jamesr@chromium.org7f2e792e2009-11-30 23:18:29310 : callback_loop_(callback_loop) {}
311
312 virtual void Run() {
313 std::vector<WebPluginInfo> plugins;
314 NPAPI::PluginList::Singleton()->GetPlugins(false, &plugins);
zelidrag@chromium.org85ed9d42010-06-08 22:37:44315 std::string hardware_class; // Empty string by default.
316#if defined(OS_CHROMEOS)
317 hardware_class = MetricsService::GetHardwareClass();
318#endif // OS_CHROMEOS
319 callback_loop_->PostTask(FROM_HERE, new InitTaskComplete(
320 hardware_class, plugins));
jamesr@chromium.org7f2e792e2009-11-30 23:18:29321 }
322
323 private:
324 MessageLoop* callback_loop_;
325};
evan@chromium.org90d41372009-11-30 21:52:32326
initial.commit09911bf2008-07-26 23:55:29327// static
328void MetricsService::RegisterPrefs(PrefService* local_state) {
329 DCHECK(IsSingleThreaded());
estade@chromium.org20ce516d2010-06-18 02:20:04330 local_state->RegisterStringPref(prefs::kMetricsClientID, "");
robertshield@google.com0bb1a622009-03-04 03:22:32331 local_state->RegisterInt64Pref(prefs::kMetricsClientIDTimestamp, 0);
332 local_state->RegisterInt64Pref(prefs::kStabilityLaunchTimeSec, 0);
333 local_state->RegisterInt64Pref(prefs::kStabilityLastTimestampSec, 0);
estade@chromium.org20ce516d2010-06-18 02:20:04334 local_state->RegisterStringPref(prefs::kStabilityStatsVersion, "");
jar@chromium.org225c50842010-01-19 21:19:13335 local_state->RegisterInt64Pref(prefs::kStabilityStatsBuildTime, 0);
initial.commit09911bf2008-07-26 23:55:29336 local_state->RegisterBooleanPref(prefs::kStabilityExitedCleanly, true);
337 local_state->RegisterBooleanPref(prefs::kStabilitySessionEndCompleted, true);
338 local_state->RegisterIntegerPref(prefs::kMetricsSessionID, -1);
339 local_state->RegisterIntegerPref(prefs::kStabilityLaunchCount, 0);
340 local_state->RegisterIntegerPref(prefs::kStabilityCrashCount, 0);
341 local_state->RegisterIntegerPref(prefs::kStabilityIncompleteSessionEndCount,
342 0);
343 local_state->RegisterIntegerPref(prefs::kStabilityPageLoadCount, 0);
initial.commit09911bf2008-07-26 23:55:29344 local_state->RegisterIntegerPref(prefs::kStabilityRendererCrashCount, 0);
asargent@chromium.org1f085622009-12-04 05:33:45345 local_state->RegisterIntegerPref(prefs::kStabilityExtensionRendererCrashCount,
346 0);
initial.commit09911bf2008-07-26 23:55:29347 local_state->RegisterIntegerPref(prefs::kStabilityRendererHangCount, 0);
asargent@chromium.org1f085622009-12-04 05:33:45348 local_state->RegisterIntegerPref(prefs::kStabilityChildProcessCrashCount, 0);
cpu@google.come73c01972008-08-13 00:18:24349 local_state->RegisterIntegerPref(prefs::kStabilityBreakpadRegistrationFail,
350 0);
351 local_state->RegisterIntegerPref(prefs::kStabilityBreakpadRegistrationSuccess,
352 0);
353 local_state->RegisterIntegerPref(prefs::kStabilityDebuggerPresent, 0);
354 local_state->RegisterIntegerPref(prefs::kStabilityDebuggerNotPresent, 0);
355
initial.commit09911bf2008-07-26 23:55:29356 local_state->RegisterDictionaryPref(prefs::kProfileMetrics);
357 local_state->RegisterIntegerPref(prefs::kNumBookmarksOnBookmarkBar, 0);
358 local_state->RegisterIntegerPref(prefs::kNumFoldersOnBookmarkBar, 0);
359 local_state->RegisterIntegerPref(prefs::kNumBookmarksInOtherBookmarkFolder,
360 0);
361 local_state->RegisterIntegerPref(prefs::kNumFoldersInOtherBookmarkFolder, 0);
362 local_state->RegisterIntegerPref(prefs::kNumKeywords, 0);
363 local_state->RegisterListPref(prefs::kMetricsInitialLogs);
364 local_state->RegisterListPref(prefs::kMetricsOngoingLogs);
robertshield@google.com0bb1a622009-03-04 03:22:32365
366 local_state->RegisterInt64Pref(prefs::kUninstallMetricsPageLoadCount, 0);
367 local_state->RegisterInt64Pref(prefs::kUninstallLaunchCount, 0);
robertshield@google.com6b5f21d2009-04-13 17:01:35368 local_state->RegisterInt64Pref(prefs::kUninstallMetricsInstallDate, 0);
robertshield@google.com0bb1a622009-03-04 03:22:32369 local_state->RegisterInt64Pref(prefs::kUninstallMetricsUptimeSec, 0);
370 local_state->RegisterInt64Pref(prefs::kUninstallLastLaunchTimeSec, 0);
371 local_state->RegisterInt64Pref(prefs::kUninstallLastObservedRunTimeSec, 0);
initial.commit09911bf2008-07-26 23:55:29372}
373
jar@chromium.org541f77922009-02-23 21:14:38374// static
375void MetricsService::DiscardOldStabilityStats(PrefService* local_state) {
376 local_state->SetBoolean(prefs::kStabilityExitedCleanly, true);
jar@chromium.orgc9abf242009-07-18 06:00:38377 local_state->SetBoolean(prefs::kStabilitySessionEndCompleted, true);
jar@chromium.org541f77922009-02-23 21:14:38378
379 local_state->SetInteger(prefs::kStabilityIncompleteSessionEndCount, 0);
380 local_state->SetInteger(prefs::kStabilityBreakpadRegistrationSuccess, 0);
381 local_state->SetInteger(prefs::kStabilityBreakpadRegistrationFail, 0);
382 local_state->SetInteger(prefs::kStabilityDebuggerPresent, 0);
383 local_state->SetInteger(prefs::kStabilityDebuggerNotPresent, 0);
384
385 local_state->SetInteger(prefs::kStabilityLaunchCount, 0);
386 local_state->SetInteger(prefs::kStabilityCrashCount, 0);
387
388 local_state->SetInteger(prefs::kStabilityPageLoadCount, 0);
389 local_state->SetInteger(prefs::kStabilityRendererCrashCount, 0);
390 local_state->SetInteger(prefs::kStabilityRendererHangCount, 0);
391
jar@chromium.org9165f742010-03-10 22:55:01392 local_state->SetInt64(prefs::kStabilityLaunchTimeSec, 0);
393 local_state->SetInt64(prefs::kStabilityLastTimestampSec, 0);
jar@chromium.org541f77922009-02-23 21:14:38394
395 local_state->ClearPref(prefs::kStabilityPluginStats);
jar@chromium.orgae155cb92009-06-19 06:10:37396
397 ListValue* unsent_initial_logs = local_state->GetMutableList(
398 prefs::kMetricsInitialLogs);
399 unsent_initial_logs->Clear();
400
401 ListValue* unsent_ongoing_logs = local_state->GetMutableList(
402 prefs::kMetricsOngoingLogs);
403 unsent_ongoing_logs->Clear();
jar@chromium.org541f77922009-02-23 21:14:38404}
405
initial.commit09911bf2008-07-26 23:55:29406MetricsService::MetricsService()
petersont@google.comd01b8732008-10-16 02:18:07407 : recording_active_(false),
408 reporting_active_(false),
409 user_permits_upload_(false),
410 server_permits_upload_(true),
411 state_(INITIALIZED),
initial.commit09911bf2008-07-26 23:55:29412 current_fetch_(NULL),
petersont@google.comd01b8732008-10-16 02:18:07413 idle_since_last_transmission_(false),
initial.commit09911bf2008-07-26 23:55:29414 next_window_id_(0),
maruel@chromium.org40bcc302009-03-02 20:50:39415 ALLOW_THIS_IN_INITIALIZER_LIST(log_sender_factory_(this)),
416 ALLOW_THIS_IN_INITIALIZER_LIST(state_saver_factory_(this)),
petersont@google.com252873ef2008-08-04 21:59:45417 interlog_duration_(TimeDelta::FromSeconds(kInitialInterlogDuration)),
petersont@google.comd01b8732008-10-16 02:18:07418 log_event_limit_(kInitialEventLimit),
initial.commit09911bf2008-07-26 23:55:29419 timer_pending_(false) {
420 DCHECK(IsSingleThreaded());
421 InitializeMetricsState();
422}
423
424MetricsService::~MetricsService() {
425 SetRecording(false);
426}
427
petersont@google.comd01b8732008-10-16 02:18:07428void MetricsService::SetUserPermitsUpload(bool enabled) {
429 HandleIdleSinceLastTransmission(false);
430 user_permits_upload_ = enabled;
431}
432
433void MetricsService::Start() {
434 SetRecording(true);
435 SetReporting(true);
436}
437
438void MetricsService::StartRecordingOnly() {
439 SetRecording(true);
440 SetReporting(false);
441}
442
443void MetricsService::Stop() {
444 SetReporting(false);
445 SetRecording(false);
446}
447
initial.commit09911bf2008-07-26 23:55:29448void MetricsService::SetRecording(bool enabled) {
449 DCHECK(IsSingleThreaded());
450
petersont@google.comd01b8732008-10-16 02:18:07451 if (enabled == recording_active_)
initial.commit09911bf2008-07-26 23:55:29452 return;
453
454 if (enabled) {
jar@chromium.orgb0c819f2009-03-08 04:52:15455 if (client_id_.empty()) {
456 PrefService* pref = g_browser_process->local_state();
457 DCHECK(pref);
estade@chromium.orgddd231e2010-06-29 20:35:19458 client_id_ = pref->GetString(prefs::kMetricsClientID);
jar@chromium.orgb0c819f2009-03-08 04:52:15459 if (client_id_.empty()) {
460 client_id_ = GenerateClientID();
estade@chromium.orgddd231e2010-06-29 20:35:19461 pref->SetString(prefs::kMetricsClientID, client_id_);
jar@chromium.orgb0c819f2009-03-08 04:52:15462
463 // Might as well make a note of how long this ID has existed
464 pref->SetString(prefs::kMetricsClientIDTimestamp,
estade@chromium.orgddd231e2010-06-29 20:35:19465 Int64ToString(Time::Now().ToTimeT()));
jar@chromium.orgb0c819f2009-03-08 04:52:15466 }
467 }
kuchhal@chromium.org157d5472009-11-05 22:31:03468 child_process_logging::SetClientId(client_id_);
initial.commit09911bf2008-07-26 23:55:29469 StartRecording();
pkasting@chromium.org005ef3e2009-05-22 20:55:46470
471 registrar_.Add(this, NotificationType::BROWSER_OPENED,
472 NotificationService::AllSources());
473 registrar_.Add(this, NotificationType::BROWSER_CLOSED,
474 NotificationService::AllSources());
475 registrar_.Add(this, NotificationType::USER_ACTION,
476 NotificationService::AllSources());
477 registrar_.Add(this, NotificationType::TAB_PARENTED,
478 NotificationService::AllSources());
479 registrar_.Add(this, NotificationType::TAB_CLOSING,
480 NotificationService::AllSources());
481 registrar_.Add(this, NotificationType::LOAD_START,
482 NotificationService::AllSources());
483 registrar_.Add(this, NotificationType::LOAD_STOP,
484 NotificationService::AllSources());
kkania@chromium.orgcd69619b2010-05-05 02:41:38485 registrar_.Add(this, NotificationType::RENDERER_PROCESS_CLOSED,
pkasting@chromium.org005ef3e2009-05-22 20:55:46486 NotificationService::AllSources());
487 registrar_.Add(this, NotificationType::RENDERER_PROCESS_HANG,
488 NotificationService::AllSources());
489 registrar_.Add(this, NotificationType::CHILD_PROCESS_HOST_CONNECTED,
490 NotificationService::AllSources());
491 registrar_.Add(this, NotificationType::CHILD_INSTANCE_CREATED,
492 NotificationService::AllSources());
493 registrar_.Add(this, NotificationType::CHILD_PROCESS_CRASHED,
494 NotificationService::AllSources());
495 registrar_.Add(this, NotificationType::TEMPLATE_URL_MODEL_LOADED,
496 NotificationService::AllSources());
497 registrar_.Add(this, NotificationType::OMNIBOX_OPENED_URL,
498 NotificationService::AllSources());
499 registrar_.Add(this, NotificationType::BOOKMARK_MODEL_LOADED,
500 NotificationService::AllSources());
initial.commit09911bf2008-07-26 23:55:29501 } else {
pkasting@chromium.org005ef3e2009-05-22 20:55:46502 registrar_.RemoveAll();
initial.commit09911bf2008-07-26 23:55:29503 PushPendingLogsToUnsentLists();
504 DCHECK(!pending_log());
505 if (state_ > INITIAL_LOG_READY && unsent_logs())
506 state_ = SEND_OLD_INITIAL_LOGS;
507 }
petersont@google.comd01b8732008-10-16 02:18:07508 recording_active_ = enabled;
initial.commit09911bf2008-07-26 23:55:29509}
510
petersont@google.comd01b8732008-10-16 02:18:07511bool MetricsService::recording_active() const {
initial.commit09911bf2008-07-26 23:55:29512 DCHECK(IsSingleThreaded());
petersont@google.comd01b8732008-10-16 02:18:07513 return recording_active_;
initial.commit09911bf2008-07-26 23:55:29514}
515
petersont@google.comd01b8732008-10-16 02:18:07516void MetricsService::SetReporting(bool enable) {
517 if (reporting_active_ != enable) {
518 reporting_active_ = enable;
519 if (reporting_active_)
initial.commit09911bf2008-07-26 23:55:29520 StartLogTransmissionTimer();
521 }
petersont@google.comd01b8732008-10-16 02:18:07522}
523
524bool MetricsService::reporting_active() const {
525 DCHECK(IsSingleThreaded());
526 return reporting_active_;
initial.commit09911bf2008-07-26 23:55:29527}
528
529void MetricsService::Observe(NotificationType type,
530 const NotificationSource& source,
531 const NotificationDetails& details) {
532 DCHECK(current_log_);
533 DCHECK(IsSingleThreaded());
534
535 if (!CanLogNotification(type, source, details))
536 return;
537
brettw@chromium.orgbfd04a62009-02-01 18:16:56538 switch (type.value) {
539 case NotificationType::USER_ACTION:
evan@chromium.orgafe3a1672009-11-17 19:04:12540 current_log_->RecordUserAction(*Details<const char*>(details).ptr());
initial.commit09911bf2008-07-26 23:55:29541 break;
542
brettw@chromium.orgbfd04a62009-02-01 18:16:56543 case NotificationType::BROWSER_OPENED:
544 case NotificationType::BROWSER_CLOSED:
initial.commit09911bf2008-07-26 23:55:29545 LogWindowChange(type, source, details);
546 break;
547
brettw@chromium.orgbfd04a62009-02-01 18:16:56548 case NotificationType::TAB_PARENTED:
549 case NotificationType::TAB_CLOSING:
initial.commit09911bf2008-07-26 23:55:29550 LogWindowChange(type, source, details);
551 break;
552
brettw@chromium.orgbfd04a62009-02-01 18:16:56553 case NotificationType::LOAD_STOP:
initial.commit09911bf2008-07-26 23:55:29554 LogLoadComplete(type, source, details);
555 break;
556
brettw@chromium.orgbfd04a62009-02-01 18:16:56557 case NotificationType::LOAD_START:
initial.commit09911bf2008-07-26 23:55:29558 LogLoadStarted();
559 break;
560
kkania@chromium.orgcd69619b2010-05-05 02:41:38561 case NotificationType::RENDERER_PROCESS_CLOSED:
asargent@chromium.org1f085622009-12-04 05:33:45562 {
kkania@chromium.orgcd69619b2010-05-05 02:41:38563 RenderProcessHost::RendererClosedDetails* process_details =
564 Details<RenderProcessHost::RendererClosedDetails>(details).ptr();
565 if (process_details->did_crash) {
566 if (process_details->was_extension_renderer) {
567 LogExtensionRendererCrash();
568 } else {
569 LogRendererCrash();
570 }
571 }
asargent@chromium.org1f085622009-12-04 05:33:45572 }
initial.commit09911bf2008-07-26 23:55:29573 break;
574
brettw@chromium.orgbfd04a62009-02-01 18:16:56575 case NotificationType::RENDERER_PROCESS_HANG:
initial.commit09911bf2008-07-26 23:55:29576 LogRendererHang();
577 break;
578
jam@chromium.orga27a9382009-02-11 23:55:10579 case NotificationType::CHILD_PROCESS_HOST_CONNECTED:
580 case NotificationType::CHILD_PROCESS_CRASHED:
581 case NotificationType::CHILD_INSTANCE_CREATED:
582 LogChildProcessChange(type, source, details);
initial.commit09911bf2008-07-26 23:55:29583 break;
584
brettw@chromium.orgbfd04a62009-02-01 18:16:56585 case NotificationType::TEMPLATE_URL_MODEL_LOADED:
initial.commit09911bf2008-07-26 23:55:29586 LogKeywords(Source<TemplateURLModel>(source).ptr());
587 break;
588
ananta@chromium.org1226abb2010-06-10 18:01:28589 case NotificationType::OMNIBOX_OPENED_URL: {
590 MetricsLog* current_log = current_log_->AsMetricsLog();
591 DCHECK(current_log);
592 current_log->RecordOmniboxOpenedURL(
initial.commit09911bf2008-07-26 23:55:29593 *Details<AutocompleteLog>(details).ptr());
594 break;
ananta@chromium.org1226abb2010-06-10 18:01:28595 }
initial.commit09911bf2008-07-26 23:55:29596
tim@chromium.orgb61236c62009-04-09 22:43:55597 case NotificationType::BOOKMARK_MODEL_LOADED: {
598 Profile* p = Source<Profile>(source).ptr();
599 if (p)
600 LogBookmarks(p->GetBookmarkModel());
initial.commit09911bf2008-07-26 23:55:29601 break;
tim@chromium.orgb61236c62009-04-09 22:43:55602 }
initial.commit09911bf2008-07-26 23:55:29603 default:
jar@chromium.orgb42c5e42010-06-03 20:43:25604 LOG(DFATAL);
initial.commit09911bf2008-07-26 23:55:29605 break;
606 }
petersont@google.comd01b8732008-10-16 02:18:07607
608 HandleIdleSinceLastTransmission(false);
609
610 if (current_log_)
jar@chromium.org281d2882009-01-20 20:32:42611 DLOG(INFO) << "METRICS: NUMBER OF EVENTS = " << current_log_->num_events();
petersont@google.comd01b8732008-10-16 02:18:07612}
613
614void MetricsService::HandleIdleSinceLastTransmission(bool in_idle) {
615 // If there wasn't a lot of action, maybe the computer was asleep, in which
616 // case, the log transmissions should have stopped. Here we start them up
617 // again.
pkasting@chromium.orgcac78842008-11-27 01:02:20618 if (!in_idle && idle_since_last_transmission_)
619 StartLogTransmissionTimer();
620 idle_since_last_transmission_ = in_idle;
initial.commit09911bf2008-07-26 23:55:29621}
622
623void MetricsService::RecordCleanShutdown() {
624 RecordBooleanPrefValue(prefs::kStabilityExitedCleanly, true);
625}
626
627void MetricsService::RecordStartOfSessionEnd() {
628 RecordBooleanPrefValue(prefs::kStabilitySessionEndCompleted, false);
629}
630
631void MetricsService::RecordCompletedSessionEnd() {
632 RecordBooleanPrefValue(prefs::kStabilitySessionEndCompleted, true);
633}
634
cpu@google.come73c01972008-08-13 00:18:24635void MetricsService:: RecordBreakpadRegistration(bool success) {
jar@google.com68475e602008-08-22 03:21:15636 if (!success)
cpu@google.come73c01972008-08-13 00:18:24637 IncrementPrefValue(prefs::kStabilityBreakpadRegistrationFail);
638 else
639 IncrementPrefValue(prefs::kStabilityBreakpadRegistrationSuccess);
640}
641
642void MetricsService::RecordBreakpadHasDebugger(bool has_debugger) {
643 if (!has_debugger)
644 IncrementPrefValue(prefs::kStabilityDebuggerNotPresent);
645 else
jar@google.com68475e602008-08-22 03:21:15646 IncrementPrefValue(prefs::kStabilityDebuggerPresent);
cpu@google.come73c01972008-08-13 00:18:24647}
648
initial.commit09911bf2008-07-26 23:55:29649//------------------------------------------------------------------------------
650// private methods
651//------------------------------------------------------------------------------
652
653
654//------------------------------------------------------------------------------
655// Initialization methods
656
657void MetricsService::InitializeMetricsState() {
kuchhal@chromium.org79bf0b72009-04-27 21:30:55658#if defined(OS_POSIX)
659 server_url_ = L"https://clients4.google.com/firefox/metrics/collect";
660#else
661 BrowserDistribution* dist = BrowserDistribution::GetDistribution();
662 server_url_ = dist->GetStatsServerURL();
663#endif
664
initial.commit09911bf2008-07-26 23:55:29665 PrefService* pref = g_browser_process->local_state();
666 DCHECK(pref);
667
jar@chromium.org225c50842010-01-19 21:19:13668 if ((pref->GetInt64(prefs::kStabilityStatsBuildTime)
669 != MetricsLog::GetBuildTime()) ||
estade@chromium.orgddd231e2010-06-29 20:35:19670 (pref->GetString(prefs::kStabilityStatsVersion)
jar@chromium.org225c50842010-01-19 21:19:13671 != MetricsLog::GetVersionString())) {
jar@chromium.org541f77922009-02-23 21:14:38672 // This is a new version, so we don't want to confuse the stats about the
673 // old version with info that we upload.
674 DiscardOldStabilityStats(pref);
675 pref->SetString(prefs::kStabilityStatsVersion,
estade@chromium.orgddd231e2010-06-29 20:35:19676 MetricsLog::GetVersionString());
jar@chromium.org225c50842010-01-19 21:19:13677 pref->SetInt64(prefs::kStabilityStatsBuildTime,
678 MetricsLog::GetBuildTime());
jar@chromium.org541f77922009-02-23 21:14:38679 }
680
initial.commit09911bf2008-07-26 23:55:29681 // Update session ID
682 session_id_ = pref->GetInteger(prefs::kMetricsSessionID);
683 ++session_id_;
684 pref->SetInteger(prefs::kMetricsSessionID, session_id_);
685
initial.commit09911bf2008-07-26 23:55:29686 // Stability bookkeeping
cpu@google.come73c01972008-08-13 00:18:24687 IncrementPrefValue(prefs::kStabilityLaunchCount);
initial.commit09911bf2008-07-26 23:55:29688
cpu@google.come73c01972008-08-13 00:18:24689 if (!pref->GetBoolean(prefs::kStabilityExitedCleanly)) {
690 IncrementPrefValue(prefs::kStabilityCrashCount);
initial.commit09911bf2008-07-26 23:55:29691 }
cpu@google.come73c01972008-08-13 00:18:24692
693 // This will be set to 'true' if we exit cleanly.
initial.commit09911bf2008-07-26 23:55:29694 pref->SetBoolean(prefs::kStabilityExitedCleanly, false);
695
cpu@google.come73c01972008-08-13 00:18:24696 if (!pref->GetBoolean(prefs::kStabilitySessionEndCompleted)) {
697 IncrementPrefValue(prefs::kStabilityIncompleteSessionEndCount);
jar@chromium.orgc9abf242009-07-18 06:00:38698 // This is marked false when we get a WM_ENDSESSION.
699 pref->SetBoolean(prefs::kStabilitySessionEndCompleted, true);
initial.commit09911bf2008-07-26 23:55:29700 }
initial.commit09911bf2008-07-26 23:55:29701
jar@chromium.org9165f742010-03-10 22:55:01702 // Initialize uptime counters.
703 int64 startup_uptime = MetricsLog::GetIncrementalUptime(pref);
mad@google.comae393ec702010-06-27 16:23:14704 DCHECK_EQ(0, startup_uptime);
jar@chromium.org9165f742010-03-10 22:55:01705 // For backwards compatibility, leave this intact in case Omaha is checking
706 // them. prefs::kStabilityLastTimestampSec may also be useless now.
707 // TODO(jar): Delete these if they have no uses.
robertshield@google.com0bb1a622009-03-04 03:22:32708 pref->SetInt64(prefs::kStabilityLaunchTimeSec, Time::Now().ToTimeT());
709
710 // Bookkeeping for the uninstall metrics.
711 IncrementLongPrefsValue(prefs::kUninstallLaunchCount);
initial.commit09911bf2008-07-26 23:55:29712
713 // Save profile metrics.
714 PrefService* prefs = g_browser_process->local_state();
715 if (prefs) {
716 // Remove the current dictionary and store it for use when sending data to
717 // server. By removing the value we prune potentially dead profiles
718 // (and keys). All valid values are added back once services startup.
719 const DictionaryValue* profile_dictionary =
720 prefs->GetDictionary(prefs::kProfileMetrics);
721 if (profile_dictionary) {
722 // Do a deep copy of profile_dictionary since ClearPref will delete it.
723 profile_dictionary_.reset(static_cast<DictionaryValue*>(
724 profile_dictionary->DeepCopy()));
725 prefs->ClearPref(prefs::kProfileMetrics);
726 }
727 }
728
jar@chromium.org92745242009-06-12 16:52:21729 // Get stats on use of command line.
730 const CommandLine* command_line(CommandLine::ForCurrentProcess());
731 size_t common_commands = 0;
732 if (command_line->HasSwitch(switches::kUserDataDir)) {
733 ++common_commands;
734 UMA_HISTOGRAM_COUNTS_100("Chrome.CommandLineDatDirCount", 1);
735 }
736
737 if (command_line->HasSwitch(switches::kApp)) {
738 ++common_commands;
739 UMA_HISTOGRAM_COUNTS_100("Chrome.CommandLineAppModeCount", 1);
740 }
741
742 UMA_HISTOGRAM_COUNTS_100("Chrome.CommandLineFlagCount",
743 command_line->GetSwitchCount());
744 UMA_HISTOGRAM_COUNTS_100("Chrome.CommandLineUncommonFlagCount",
745 command_line->GetSwitchCount() - common_commands);
746
initial.commit09911bf2008-07-26 23:55:29747 // Kick off the process of saving the state (so the uptime numbers keep
748 // getting updated) every n minutes.
749 ScheduleNextStateSave();
750}
751
zelidrag@chromium.org85ed9d42010-06-08 22:37:44752void MetricsService::OnInitTaskComplete(
753 const std::string& hardware_class,
jam@chromium.org35fa6a22009-08-15 00:04:01754 const std::vector<WebPluginInfo>& plugins) {
zelidrag@chromium.org85ed9d42010-06-08 22:37:44755 DCHECK(state_ == INIT_TASK_SCHEDULED);
756 hardware_class_ = hardware_class;
jam@chromium.org35fa6a22009-08-15 00:04:01757 plugins_ = plugins;
zelidrag@chromium.org85ed9d42010-06-08 22:37:44758 if (state_ == INIT_TASK_SCHEDULED)
759 state_ = INIT_TASK_DONE;
initial.commit09911bf2008-07-26 23:55:29760}
761
762std::string MetricsService::GenerateClientID() {
paul@chromium.orgdc6f4962009-02-13 01:25:50763#if defined(OS_WIN)
initial.commit09911bf2008-07-26 23:55:29764 const int kGUIDSize = 39;
765
766 GUID guid;
767 HRESULT guid_result = CoCreateGuid(&guid);
768 DCHECK(SUCCEEDED(guid_result));
769
770 std::wstring guid_string;
771 int result = StringFromGUID2(guid,
772 WriteInto(&guid_string, kGUIDSize), kGUIDSize);
773 DCHECK(result == kGUIDSize);
774
775 return WideToUTF8(guid_string.substr(1, guid_string.length() - 2));
evan@chromium.org271b24f2009-07-28 16:05:51776#else
sky@chromium.org06aaac22009-07-08 20:54:13777 uint64 sixteen_bytes[2] = { base::RandUint64(), base::RandUint64() };
778 return RandomBytesToGUIDString(sixteen_bytes);
paul@chromium.orgdc6f4962009-02-13 01:25:50779#endif
initial.commit09911bf2008-07-26 23:55:29780}
781
sky@chromium.org06aaac22009-07-08 20:54:13782#if defined(OS_POSIX)
783// TODO(cmasone): Once we're comfortable this works, migrate Windows code to
784// use this as well.
785std::string MetricsService::RandomBytesToGUIDString(const uint64 bytes[2]) {
evan@chromium.org34b2b002009-11-20 06:53:28786 return StringPrintf("%08X-%04X-%04X-%04X-%012llX",
787 static_cast<unsigned int>(bytes[0] >> 32),
788 static_cast<unsigned int>((bytes[0] >> 16) & 0x0000ffff),
789 static_cast<unsigned int>(bytes[0] & 0x0000ffff),
790 static_cast<unsigned int>(bytes[1] >> 48),
sky@chromium.org06aaac22009-07-08 20:54:13791 bytes[1] & 0x0000ffffffffffffULL);
792}
793#endif
initial.commit09911bf2008-07-26 23:55:29794
795//------------------------------------------------------------------------------
796// State save methods
797
798void MetricsService::ScheduleNextStateSave() {
799 state_saver_factory_.RevokeAll();
800
801 MessageLoop::current()->PostDelayedTask(FROM_HERE,
802 state_saver_factory_.NewRunnableMethod(&MetricsService::SaveLocalState),
803 kSaveStateInterval * 1000);
804}
805
806void MetricsService::SaveLocalState() {
807 PrefService* pref = g_browser_process->local_state();
808 if (!pref) {
jar@chromium.orgb42c5e42010-06-03 20:43:25809 LOG(DFATAL);
initial.commit09911bf2008-07-26 23:55:29810 return;
811 }
812
813 RecordCurrentState(pref);
phajdan.jr@chromium.org6faa0e0d2009-04-28 06:50:36814 pref->ScheduleSavePersistentPrefs();
initial.commit09911bf2008-07-26 23:55:29815
jar@chromium.org281d2882009-01-20 20:32:42816 // TODO(jar): Does this run down the batteries????
initial.commit09911bf2008-07-26 23:55:29817 ScheduleNextStateSave();
818}
819
820
821//------------------------------------------------------------------------------
822// Recording control methods
823
824void MetricsService::StartRecording() {
825 if (current_log_)
826 return;
827
828 current_log_ = new MetricsLog(client_id_, session_id_);
829 if (state_ == INITIALIZED) {
830 // We only need to schedule that run once.
zelidrag@chromium.org85ed9d42010-06-08 22:37:44831 state_ = INIT_TASK_SCHEDULED;
initial.commit09911bf2008-07-26 23:55:29832
zelidrag@chromium.org85ed9d42010-06-08 22:37:44833 // Schedules a task on the file thread for execution of slower
834 // initialization steps (such as plugin list generation) necessary
835 // for sending the initial log. This avoids blocking the main UI
836 // thread.
jamesr@chromium.org7f2e792e2009-11-30 23:18:29837 g_browser_process->file_thread()->message_loop()->PostDelayedTask(FROM_HERE,
zelidrag@chromium.org85ed9d42010-06-08 22:37:44838 new InitTask(MessageLoop::current()),
petersont@google.com252873ef2008-08-04 21:59:45839 kInitialInterlogDuration * 1000 / 2);
initial.commit09911bf2008-07-26 23:55:29840 }
841}
842
ananta@chromium.org1226abb2010-06-10 18:01:28843void MetricsService::StopRecording(MetricsLogBase** log) {
initial.commit09911bf2008-07-26 23:55:29844 if (!current_log_)
845 return;
846
ananta@chromium.org1226abb2010-06-10 18:01:28847 MetricsLog* current_log = current_log_->AsMetricsLog();
848 DCHECK(current_log);
849 current_log->set_hardware_class(hardware_class_); // Adds to ongoing logs.
zelidrag@chromium.org85ed9d42010-06-08 22:37:44850
jar@google.com68475e602008-08-22 03:21:15851 // TODO(jar): Integrate bounds on log recording more consistently, so that we
852 // can stop recording logs that are too big much sooner.
petersont@google.comd01b8732008-10-16 02:18:07853 if (current_log_->num_events() > log_event_limit_) {
dsh@google.com553dba62009-02-24 19:08:23854 UMA_HISTOGRAM_COUNTS("UMA.Discarded Log Events",
jar@google.com68475e602008-08-22 03:21:15855 current_log_->num_events());
856 current_log_->CloseLog();
857 delete current_log_;
jar@google.com294638782008-09-24 00:22:41858 current_log_ = NULL;
jar@google.com68475e602008-08-22 03:21:15859 StartRecording(); // Start trivial log to hold our histograms.
860 }
861
jar@google.com0b33f80b2008-12-17 21:34:36862 // Put incremental data (histogram deltas, and realtime stats deltas) at the
jar@google.com147bbc0b2009-01-06 19:37:40863 // end of all log transmissions (initial log handles this separately).
initial.commit09911bf2008-07-26 23:55:29864 // Don't bother if we're going to discard current_log_.
jar@google.com0b33f80b2008-12-17 21:34:36865 if (log) {
ananta@chromium.org1226abb2010-06-10 18:01:28866 current_log->RecordIncrementalStabilityElements();
initial.commit09911bf2008-07-26 23:55:29867 RecordCurrentHistograms();
jar@google.com0b33f80b2008-12-17 21:34:36868 }
initial.commit09911bf2008-07-26 23:55:29869
870 current_log_->CloseLog();
pkasting@chromium.orgcac78842008-11-27 01:02:20871 if (log)
ananta@chromium.org1226abb2010-06-10 18:01:28872 *log = current_log;
pkasting@chromium.orgcac78842008-11-27 01:02:20873 else
initial.commit09911bf2008-07-26 23:55:29874 delete current_log_;
initial.commit09911bf2008-07-26 23:55:29875 current_log_ = NULL;
876}
877
initial.commit09911bf2008-07-26 23:55:29878void MetricsService::PushPendingLogsToUnsentLists() {
879 if (state_ < INITIAL_LOG_READY)
avi@google.com28ab7f92009-01-06 21:39:04880 return; // We didn't and still don't have time to get plugin list etc.
initial.commit09911bf2008-07-26 23:55:29881
882 if (pending_log()) {
883 PreparePendingLogText();
884 if (state_ == INITIAL_LOG_READY) {
885 // We may race here, and send second copy of initial log later.
886 unsent_initial_logs_.push_back(pending_log_text_);
petersont@google.comd01b8732008-10-16 02:18:07887 state_ = SEND_OLD_INITIAL_LOGS;
initial.commit09911bf2008-07-26 23:55:29888 } else {
jar@chromium.org281d2882009-01-20 20:32:42889 // TODO(jar): Verify correctness in other states, including sending unsent
jar@chromium.org541f77922009-02-23 21:14:38890 // initial logs.
jar@google.com68475e602008-08-22 03:21:15891 PushPendingLogTextToUnsentOngoingLogs();
initial.commit09911bf2008-07-26 23:55:29892 }
893 DiscardPendingLog();
894 }
895 DCHECK(!pending_log());
896 StopRecording(&pending_log_);
897 PreparePendingLogText();
jar@google.com68475e602008-08-22 03:21:15898 PushPendingLogTextToUnsentOngoingLogs();
initial.commit09911bf2008-07-26 23:55:29899 DiscardPendingLog();
900 StoreUnsentLogs();
901}
902
jar@google.com68475e602008-08-22 03:21:15903void MetricsService::PushPendingLogTextToUnsentOngoingLogs() {
petersont@google.comd01b8732008-10-16 02:18:07904 // If UMA response told us not to upload, there's no need to save the pending
905 // log. It wasn't supposed to be uploaded anyway.
906 if (!server_permits_upload_)
907 return;
908
paul@chromium.orgdc6f4962009-02-13 01:25:50909 if (pending_log_text_.length() >
910 static_cast<size_t>(kUploadLogAvoidRetransmitSize)) {
dsh@google.com553dba62009-02-24 19:08:23911 UMA_HISTOGRAM_COUNTS("UMA.Large Accumulated Log Not Persisted",
jar@google.com68475e602008-08-22 03:21:15912 static_cast<int>(pending_log_text_.length()));
913 return;
914 }
915 unsent_ongoing_logs_.push_back(pending_log_text_);
916}
917
initial.commit09911bf2008-07-26 23:55:29918//------------------------------------------------------------------------------
919// Transmission of logs methods
920
921void MetricsService::StartLogTransmissionTimer() {
petersont@google.comd01b8732008-10-16 02:18:07922 // If we're not reporting, there's no point in starting a log transmission
923 // timer.
924 if (!reporting_active())
925 return;
926
initial.commit09911bf2008-07-26 23:55:29927 if (!current_log_)
928 return; // Recorder is shutdown.
petersont@google.comd01b8732008-10-16 02:18:07929
930 // If there is already a timer running, we leave it running.
931 // If timer_pending is true because the fetch is waiting for a response,
932 // we return for now and let the response handler start the timer.
933 if (timer_pending_)
initial.commit09911bf2008-07-26 23:55:29934 return;
petersont@google.comd01b8732008-10-16 02:18:07935
petersont@google.comd01b8732008-10-16 02:18:07936 // Before starting the timer, set timer_pending_ to true.
initial.commit09911bf2008-07-26 23:55:29937 timer_pending_ = true;
petersont@google.comd01b8732008-10-16 02:18:07938
939 // Right before the UMA transmission gets started, there's one more thing we'd
940 // like to record: the histogram of memory usage, so we spawn a task to
jar@chromium.orgc9a3ef82009-05-28 22:02:46941 // collect the memory details and when that task is finished, it will call
942 // OnMemoryDetailCollectionDone, which will call HistogramSynchronization to
943 // collect histograms from all renderers and then we will call
944 // OnHistogramSynchronizationDone to continue processing.
initial.commit09911bf2008-07-26 23:55:29945 MessageLoop::current()->PostDelayedTask(FROM_HERE,
946 log_sender_factory_.
jar@chromium.orgc9a3ef82009-05-28 22:02:46947 NewRunnableMethod(&MetricsService::LogTransmissionTimerDone),
phajdan.jr@chromium.org743ace42009-06-17 17:23:51948 interlog_duration_.InMilliseconds());
initial.commit09911bf2008-07-26 23:55:29949}
950
jar@chromium.orgc9a3ef82009-05-28 22:02:46951void MetricsService::LogTransmissionTimerDone() {
952 Task* task = log_sender_factory_.
953 NewRunnableMethod(&MetricsService::OnMemoryDetailCollectionDone);
954
jam@chromium.orge9adedb2009-12-01 22:23:59955 scoped_refptr<MetricsMemoryDetails> details = new MetricsMemoryDetails(task);
jar@chromium.orgc9a3ef82009-05-28 22:02:46956 details->StartFetch();
957
958 // Collect WebCore cache information to put into a histogram.
pkasting@chromium.org019191a2009-10-02 20:37:27959 for (RenderProcessHost::iterator i(RenderProcessHost::AllHostsIterator());
960 !i.IsAtEnd(); i.Advance())
961 i.GetCurrentValue()->Send(new ViewMsg_GetCacheResourceStats());
jar@chromium.orgc9a3ef82009-05-28 22:02:46962}
963
964void MetricsService::OnMemoryDetailCollectionDone() {
965 DCHECK(IsSingleThreaded());
966
967 // HistogramSynchronizer will Collect histograms from all renderers and it
968 // will call OnHistogramSynchronizationDone (if wait time elapses before it
969 // heard from all renderers, then also it will call
970 // OnHistogramSynchronizationDone).
971
972 // Create a callback_task for OnHistogramSynchronizationDone.
973 Task* callback_task = log_sender_factory_.NewRunnableMethod(
974 &MetricsService::OnHistogramSynchronizationDone);
975
976 // Set up the callback to task to call after we receive histograms from all
977 // renderer processes. Wait time specifies how long to wait before absolutely
978 // calling us back on the task.
979 HistogramSynchronizer::FetchRendererHistogramsAsynchronously(
980 MessageLoop::current(), callback_task,
981 kMaxHistogramGatheringWaitDuration);
982}
983
984void MetricsService::OnHistogramSynchronizationDone() {
initial.commit09911bf2008-07-26 23:55:29985 DCHECK(IsSingleThreaded());
986
petersont@google.comd01b8732008-10-16 02:18:07987 // This function should only be called via timer, so timer_pending_
988 // should be true.
989 DCHECK(timer_pending_);
990 timer_pending_ = false;
initial.commit09911bf2008-07-26 23:55:29991
992 DCHECK(!current_fetch_.get());
initial.commit09911bf2008-07-26 23:55:29993
petersont@google.comd01b8732008-10-16 02:18:07994 // If we're getting no notifications, then the log won't have much in it, and
995 // it's possible the computer is about to go to sleep, so don't upload and
996 // don't restart the transmission timer.
997 if (idle_since_last_transmission_)
998 return;
999
1000 // If somehow there is a fetch in progress, we return setting timer_pending_
1001 // to true and hope things work out.
1002 if (current_fetch_.get()) {
1003 timer_pending_ = true;
1004 return;
1005 }
1006
1007 // If uploads are forbidden by UMA response, there's no point in keeping
1008 // the current_log_, and the more often we delete it, the less likely it is
1009 // to expand forever.
1010 if (!server_permits_upload_ && current_log_) {
1011 StopRecording(NULL);
1012 StartRecording();
1013 }
initial.commit09911bf2008-07-26 23:55:291014
1015 if (!current_log_)
1016 return; // Logging was disabled.
petersont@google.comd01b8732008-10-16 02:18:071017 if (!reporting_active())
initial.commit09911bf2008-07-26 23:55:291018 return; // Don't do work if we're not going to send anything now.
1019
petersont@google.comd01b8732008-10-16 02:18:071020 MakePendingLog();
initial.commit09911bf2008-07-26 23:55:291021
petersont@google.comd01b8732008-10-16 02:18:071022 // MakePendingLog should have put something in the pending log, if it didn't,
1023 // we start the timer again, return and hope things work out.
1024 if (!pending_log()) {
1025 StartLogTransmissionTimer();
1026 return;
1027 }
initial.commit09911bf2008-07-26 23:55:291028
petersont@google.comd01b8732008-10-16 02:18:071029 // If we're not supposed to upload any UMA data because the response or the
1030 // user said so, cancel the upload at this point, but start the timer.
1031 if (!TransmissionPermitted()) {
1032 DiscardPendingLog();
1033 StartLogTransmissionTimer();
1034 return;
1035 }
initial.commit09911bf2008-07-26 23:55:291036
petersont@google.comd01b8732008-10-16 02:18:071037 PrepareFetchWithPendingLog();
1038
1039 if (!current_fetch_.get()) {
1040 // Compression failed, and log discarded :-/.
1041 DiscardPendingLog();
1042 StartLogTransmissionTimer(); // Maybe we'll do better next time
1043 // TODO(jar): If compression failed, we should have created a tiny log and
1044 // compressed that, so that we can signal that we're losing logs.
1045 return;
1046 }
1047
1048 DCHECK(!timer_pending_);
1049
1050 // The URL fetch is a like timer in that after a while we get called back
1051 // so we set timer_pending_ true just as we start the url fetch.
1052 timer_pending_ = true;
1053 current_fetch_->Start();
1054
1055 HandleIdleSinceLastTransmission(true);
1056}
1057
1058
1059void MetricsService::MakePendingLog() {
1060 if (pending_log())
1061 return;
1062
1063 switch (state_) {
1064 case INITIALIZED:
zelidrag@chromium.org85ed9d42010-06-08 22:37:441065 case INIT_TASK_SCHEDULED: // We should be further along by now.
petersont@google.comd01b8732008-10-16 02:18:071066 DCHECK(false);
1067 return;
1068
zelidrag@chromium.org85ed9d42010-06-08 22:37:441069 case INIT_TASK_DONE:
petersont@google.comd01b8732008-10-16 02:18:071070 // We need to wait for the initial log to be ready before sending
1071 // anything, because the server will tell us whether it wants to hear
1072 // from us.
1073 PrepareInitialLog();
zelidrag@chromium.org85ed9d42010-06-08 22:37:441074 DCHECK(state_ == INIT_TASK_DONE);
petersont@google.comd01b8732008-10-16 02:18:071075 RecallUnsentLogs();
1076 state_ = INITIAL_LOG_READY;
1077 break;
1078
1079 case SEND_OLD_INITIAL_LOGS:
pkasting@chromium.orgcac78842008-11-27 01:02:201080 if (!unsent_initial_logs_.empty()) {
1081 pending_log_text_ = unsent_initial_logs_.back();
1082 break;
1083 }
petersont@google.comd01b8732008-10-16 02:18:071084 state_ = SENDING_OLD_LOGS;
1085 // Fall through.
initial.commit09911bf2008-07-26 23:55:291086
petersont@google.comd01b8732008-10-16 02:18:071087 case SENDING_OLD_LOGS:
1088 if (!unsent_ongoing_logs_.empty()) {
1089 pending_log_text_ = unsent_ongoing_logs_.back();
1090 break;
1091 }
1092 state_ = SENDING_CURRENT_LOGS;
1093 // Fall through.
1094
1095 case SENDING_CURRENT_LOGS:
1096 StopRecording(&pending_log_);
1097 StartRecording();
1098 break;
1099
1100 default:
jar@chromium.orgb42c5e42010-06-03 20:43:251101 LOG(DFATAL);
petersont@google.comd01b8732008-10-16 02:18:071102 return;
1103 }
1104
1105 DCHECK(pending_log());
1106}
1107
1108bool MetricsService::TransmissionPermitted() const {
1109 // If the user forbids uploading that's they're business, and we don't upload
1110 // anything. If the server forbids uploading, that's our business, so we take
1111 // that to mean it forbids current logs, but we still send up the inital logs
1112 // and any old logs.
petersont@google.comd01b8732008-10-16 02:18:071113 if (!user_permits_upload_)
1114 return false;
pkasting@chromium.orgcac78842008-11-27 01:02:201115 if (server_permits_upload_)
petersont@google.comd01b8732008-10-16 02:18:071116 return true;
initial.commit09911bf2008-07-26 23:55:291117
pkasting@chromium.orgcac78842008-11-27 01:02:201118 switch (state_) {
1119 case INITIAL_LOG_READY:
1120 case SEND_OLD_INITIAL_LOGS:
1121 case SENDING_OLD_LOGS:
1122 return true;
1123
1124 case SENDING_CURRENT_LOGS:
1125 default:
1126 return false;
nsylvain@chromium.org8c8824b2008-09-20 01:55:501127 }
initial.commit09911bf2008-07-26 23:55:291128}
1129
initial.commit09911bf2008-07-26 23:55:291130void MetricsService::PrepareInitialLog() {
zelidrag@chromium.org85ed9d42010-06-08 22:37:441131 DCHECK(state_ == INIT_TASK_DONE);
initial.commit09911bf2008-07-26 23:55:291132
1133 MetricsLog* log = new MetricsLog(client_id_, session_id_);
zelidrag@chromium.org85ed9d42010-06-08 22:37:441134 log->set_hardware_class(hardware_class_); // Adds to initial log.
jam@chromium.org35fa6a22009-08-15 00:04:011135 log->RecordEnvironment(plugins_, profile_dictionary_.get());
initial.commit09911bf2008-07-26 23:55:291136
1137 // Histograms only get written to current_log_, so setup for the write.
ananta@chromium.org1226abb2010-06-10 18:01:281138 MetricsLogBase* save_log = current_log_;
initial.commit09911bf2008-07-26 23:55:291139 current_log_ = log;
1140 RecordCurrentHistograms(); // Into current_log_... which is really log.
1141 current_log_ = save_log;
1142
1143 log->CloseLog();
1144 DCHECK(!pending_log());
1145 pending_log_ = log;
1146}
1147
1148void MetricsService::RecallUnsentLogs() {
1149 DCHECK(unsent_initial_logs_.empty());
1150 DCHECK(unsent_ongoing_logs_.empty());
1151
1152 PrefService* local_state = g_browser_process->local_state();
1153 DCHECK(local_state);
1154
1155 ListValue* unsent_initial_logs = local_state->GetMutableList(
1156 prefs::kMetricsInitialLogs);
1157 for (ListValue::iterator it = unsent_initial_logs->begin();
1158 it != unsent_initial_logs->end(); ++it) {
scherkus@chromium.org5e324b72008-12-18 00:07:591159 std::string log;
1160 (*it)->GetAsString(&log);
1161 unsent_initial_logs_.push_back(log);
initial.commit09911bf2008-07-26 23:55:291162 }
1163
1164 ListValue* unsent_ongoing_logs = local_state->GetMutableList(
1165 prefs::kMetricsOngoingLogs);
1166 for (ListValue::iterator it = unsent_ongoing_logs->begin();
1167 it != unsent_ongoing_logs->end(); ++it) {
scherkus@chromium.org5e324b72008-12-18 00:07:591168 std::string log;
1169 (*it)->GetAsString(&log);
1170 unsent_ongoing_logs_.push_back(log);
initial.commit09911bf2008-07-26 23:55:291171 }
1172}
1173
1174void MetricsService::StoreUnsentLogs() {
1175 if (state_ < INITIAL_LOG_READY)
1176 return; // We never Recalled the prior unsent logs.
1177
1178 PrefService* local_state = g_browser_process->local_state();
1179 DCHECK(local_state);
1180
1181 ListValue* unsent_initial_logs = local_state->GetMutableList(
1182 prefs::kMetricsInitialLogs);
1183 unsent_initial_logs->Clear();
1184 size_t start = 0;
1185 if (unsent_initial_logs_.size() > kMaxInitialLogsPersisted)
1186 start = unsent_initial_logs_.size() - kMaxInitialLogsPersisted;
1187 for (size_t i = start; i < unsent_initial_logs_.size(); ++i)
1188 unsent_initial_logs->Append(
scherkus@chromium.org5e324b72008-12-18 00:07:591189 Value::CreateStringValue(unsent_initial_logs_[i]));
initial.commit09911bf2008-07-26 23:55:291190
1191 ListValue* unsent_ongoing_logs = local_state->GetMutableList(
1192 prefs::kMetricsOngoingLogs);
1193 unsent_ongoing_logs->Clear();
1194 start = 0;
1195 if (unsent_ongoing_logs_.size() > kMaxOngoingLogsPersisted)
1196 start = unsent_ongoing_logs_.size() - kMaxOngoingLogsPersisted;
1197 for (size_t i = start; i < unsent_ongoing_logs_.size(); ++i)
1198 unsent_ongoing_logs->Append(
scherkus@chromium.org5e324b72008-12-18 00:07:591199 Value::CreateStringValue(unsent_ongoing_logs_[i]));
initial.commit09911bf2008-07-26 23:55:291200}
1201
1202void MetricsService::PreparePendingLogText() {
1203 DCHECK(pending_log());
1204 if (!pending_log_text_.empty())
1205 return;
mark@chromium.org9ffcccf42009-09-15 22:19:181206 int text_size = pending_log_->GetEncodedLogSize();
1207
1208 // Leave room for the NUL terminator.
1209 pending_log_->GetEncodedLog(WriteInto(&pending_log_text_, text_size + 1),
1210 text_size);
initial.commit09911bf2008-07-26 23:55:291211}
1212
petersont@google.comd01b8732008-10-16 02:18:071213void MetricsService::PrepareFetchWithPendingLog() {
initial.commit09911bf2008-07-26 23:55:291214 DCHECK(pending_log());
1215 DCHECK(!current_fetch_.get());
1216 PreparePendingLogText();
1217 DCHECK(!pending_log_text_.empty());
1218
1219 // Allow security conscious users to see all metrics logs that we send.
1220 LOG(INFO) << "METRICS LOG: " << pending_log_text_;
1221
1222 std::string compressed_log;
pkasting@chromium.orgcac78842008-11-27 01:02:201223 if (!Bzip2Compress(pending_log_text_, &compressed_log)) {
jar@chromium.orgb42c5e42010-06-03 20:43:251224 LOG(DFATAL) << "Failed to compress log for transmission.";
initial.commit09911bf2008-07-26 23:55:291225 DiscardPendingLog();
1226 StartLogTransmissionTimer(); // Maybe we'll do better on next log :-/.
1227 return;
1228 }
pkasting@chromium.orgcac78842008-11-27 01:02:201229
kuchhal@chromium.org79bf0b72009-04-27 21:30:551230 current_fetch_.reset(new URLFetcher(GURL(WideToUTF16(server_url_)),
1231 URLFetcher::POST,
initial.commit09911bf2008-07-26 23:55:291232 this));
1233 current_fetch_->set_request_context(Profile::GetDefaultRequestContext());
1234 current_fetch_->set_upload_data(kMetricsType, compressed_log);
initial.commit09911bf2008-07-26 23:55:291235}
1236
initial.commit09911bf2008-07-26 23:55:291237static const char* StatusToString(const URLRequestStatus& status) {
1238 switch (status.status()) {
1239 case URLRequestStatus::SUCCESS:
1240 return "SUCCESS";
1241
1242 case URLRequestStatus::IO_PENDING:
1243 return "IO_PENDING";
1244
1245 case URLRequestStatus::HANDLED_EXTERNALLY:
1246 return "HANDLED_EXTERNALLY";
1247
1248 case URLRequestStatus::CANCELED:
1249 return "CANCELED";
1250
1251 case URLRequestStatus::FAILED:
1252 return "FAILED";
1253
1254 default:
jar@chromium.orgb42c5e42010-06-03 20:43:251255 LOG(DFATAL);
initial.commit09911bf2008-07-26 23:55:291256 return "Unknown";
1257 }
1258}
1259
1260void MetricsService::OnURLFetchComplete(const URLFetcher* source,
1261 const GURL& url,
1262 const URLRequestStatus& status,
1263 int response_code,
1264 const ResponseCookies& cookies,
1265 const std::string& data) {
1266 DCHECK(timer_pending_);
1267 timer_pending_ = false;
1268 DCHECK(current_fetch_.get());
1269 current_fetch_.reset(NULL); // We're not allowed to re-use it.
1270
1271 // Confirm send so that we can move on.
jar@chromium.org281d2882009-01-20 20:32:421272 LOG(INFO) << "METRICS RESPONSE CODE: " << response_code << " status=" <<
pkasting@chromium.orgcac78842008-11-27 01:02:201273 StatusToString(status);
petersont@google.com252873ef2008-08-04 21:59:451274
jar@chromium.org0eb34fee2009-01-21 08:04:381275 // Provide boolean for error recovery (allow us to ignore response_code).
paul@chromium.orgdc6f4962009-02-13 01:25:501276 bool discard_log = false;
jar@chromium.org0eb34fee2009-01-21 08:04:381277
jar@google.com68475e602008-08-22 03:21:151278 if (response_code != 200 &&
paul@chromium.orgdc6f4962009-02-13 01:25:501279 pending_log_text_.length() >
1280 static_cast<size_t>(kUploadLogAvoidRetransmitSize)) {
dsh@google.com553dba62009-02-24 19:08:231281 UMA_HISTOGRAM_COUNTS("UMA.Large Rejected Log was Discarded",
jar@google.com68475e602008-08-22 03:21:151282 static_cast<int>(pending_log_text_.length()));
jar@chromium.org0eb34fee2009-01-21 08:04:381283 discard_log = true;
1284 } else if (response_code == 400) {
1285 // Bad syntax. Retransmission won't work.
dsh@google.com553dba62009-02-24 19:08:231286 UMA_HISTOGRAM_COUNTS("UMA.Unacceptable_Log_Discarded", state_);
jar@chromium.org0eb34fee2009-01-21 08:04:381287 discard_log = true;
jar@google.com68475e602008-08-22 03:21:151288 }
1289
jar@chromium.org0eb34fee2009-01-21 08:04:381290 if (response_code != 200 && !discard_log) {
jar@chromium.org281d2882009-01-20 20:32:421291 LOG(INFO) << "METRICS: transmission attempt returned a failure code: "
1292 << response_code << ". Verify network connectivity";
petersont@google.com252873ef2008-08-04 21:59:451293 HandleBadResponseCode();
jar@chromium.org0eb34fee2009-01-21 08:04:381294 } else { // Successful receipt (or we are discarding log).
jar@chromium.org281d2882009-01-20 20:32:421295 LOG(INFO) << "METRICS RESPONSE DATA: " << data;
initial.commit09911bf2008-07-26 23:55:291296 switch (state_) {
1297 case INITIAL_LOG_READY:
1298 state_ = SEND_OLD_INITIAL_LOGS;
1299 break;
1300
1301 case SEND_OLD_INITIAL_LOGS:
1302 DCHECK(!unsent_initial_logs_.empty());
1303 unsent_initial_logs_.pop_back();
1304 StoreUnsentLogs();
1305 break;
1306
1307 case SENDING_OLD_LOGS:
1308 DCHECK(!unsent_ongoing_logs_.empty());
1309 unsent_ongoing_logs_.pop_back();
1310 StoreUnsentLogs();
1311 break;
1312
1313 case SENDING_CURRENT_LOGS:
1314 break;
1315
1316 default:
jar@chromium.orgb42c5e42010-06-03 20:43:251317 LOG(DFATAL);
initial.commit09911bf2008-07-26 23:55:291318 break;
1319 }
petersont@google.comd01b8732008-10-16 02:18:071320
initial.commit09911bf2008-07-26 23:55:291321 DiscardPendingLog();
jar@google.com29be92552008-08-07 22:49:271322 // Since we sent a log, make sure our in-memory state is recorded to disk.
1323 PrefService* local_state = g_browser_process->local_state();
1324 DCHECK(local_state);
1325 if (local_state)
phajdan.jr@chromium.org6faa0e0d2009-04-28 06:50:361326 local_state->ScheduleSavePersistentPrefs();
petersont@google.com252873ef2008-08-04 21:59:451327
jar@google.com147bbc0b2009-01-06 19:37:401328 // Provide a default (free of exponetial backoff, other varances) in case
1329 // the server does not specify a value.
1330 interlog_duration_ = TimeDelta::FromSeconds(kMinSecondsPerLog);
1331
petersont@google.com252873ef2008-08-04 21:59:451332 GetSettingsFromResponseData(data);
petersont@google.com252873ef2008-08-04 21:59:451333 // Override server specified interlog delay if there are unsent logs to
jar@google.com29be92552008-08-07 22:49:271334 // transmit.
initial.commit09911bf2008-07-26 23:55:291335 if (unsent_logs()) {
1336 DCHECK(state_ < SENDING_CURRENT_LOGS);
1337 interlog_duration_ = TimeDelta::FromSeconds(kUnsentLogDelay);
initial.commit09911bf2008-07-26 23:55:291338 }
1339 }
petersont@google.com252873ef2008-08-04 21:59:451340
initial.commit09911bf2008-07-26 23:55:291341 StartLogTransmissionTimer();
1342}
1343
petersont@google.com252873ef2008-08-04 21:59:451344void MetricsService::HandleBadResponseCode() {
jar@chromium.org281d2882009-01-20 20:32:421345 LOG(INFO) << "Verify your metrics logs are formatted correctly. "
kuchhal@chromium.org79bf0b72009-04-27 21:30:551346 "Verify server is active at " << server_url_;
petersont@google.com252873ef2008-08-04 21:59:451347 if (!pending_log()) {
jar@chromium.org281d2882009-01-20 20:32:421348 LOG(INFO) << "METRICS: Recorder shutdown during log transmission.";
petersont@google.com252873ef2008-08-04 21:59:451349 } else {
1350 // Send progressively less frequently.
1351 DCHECK(kBackoff > 1.0);
1352 interlog_duration_ = TimeDelta::FromMicroseconds(
1353 static_cast<int64>(kBackoff * interlog_duration_.InMicroseconds()));
1354
1355 if (kMaxBackoff * TimeDelta::FromSeconds(kMinSecondsPerLog) <
pkasting@chromium.orgcac78842008-11-27 01:02:201356 interlog_duration_) {
petersont@google.com252873ef2008-08-04 21:59:451357 interlog_duration_ = kMaxBackoff *
1358 TimeDelta::FromSeconds(kMinSecondsPerLog);
pkasting@chromium.orgcac78842008-11-27 01:02:201359 }
petersont@google.com252873ef2008-08-04 21:59:451360
jar@chromium.org281d2882009-01-20 20:32:421361 LOG(INFO) << "METRICS: transmission retry being scheduled in " <<
petersont@google.com252873ef2008-08-04 21:59:451362 interlog_duration_.InSeconds() << " seconds for " <<
1363 pending_log_text_;
initial.commit09911bf2008-07-26 23:55:291364 }
initial.commit09911bf2008-07-26 23:55:291365}
1366
petersont@google.com252873ef2008-08-04 21:59:451367void MetricsService::GetSettingsFromResponseData(const std::string& data) {
1368 // We assume that the file is structured as a block opened by <response>
petersont@google.comd01b8732008-10-16 02:18:071369 // and that inside response, there is a block opened by tag <chrome_config>
1370 // other tags are ignored for now except the content of <chrome_config>.
jar@chromium.org281d2882009-01-20 20:32:421371 LOG(INFO) << "METRICS: getting settings from response data: " << data;
petersont@google.comd01b8732008-10-16 02:18:071372
petersont@google.com252873ef2008-08-04 21:59:451373 int data_size = static_cast<int>(data.size());
1374 if (data_size < 0) {
jar@chromium.org281d2882009-01-20 20:32:421375 LOG(INFO) << "METRICS: server response data bad size: " << data_size <<
pkasting@chromium.orgcac78842008-11-27 01:02:201376 "; aborting extraction of settings";
petersont@google.com252873ef2008-08-04 21:59:451377 return;
1378 }
pkasting@chromium.orgcac78842008-11-27 01:02:201379 xmlDocPtr doc = xmlReadMemory(data.c_str(), data_size, "", NULL, 0);
petersont@google.com252873ef2008-08-04 21:59:451380 DCHECK(doc);
petersont@google.comd01b8732008-10-16 02:18:071381 // If the document is malformed, we just use the settings that were there.
1382 if (!doc) {
jar@chromium.org281d2882009-01-20 20:32:421383 LOG(INFO) << "METRICS: reading xml from server response data failed";
petersont@google.com252873ef2008-08-04 21:59:451384 return;
petersont@google.comd01b8732008-10-16 02:18:071385 }
petersont@google.com252873ef2008-08-04 21:59:451386
petersont@google.comd01b8732008-10-16 02:18:071387 xmlNodePtr top_node = xmlDocGetRootElement(doc), chrome_config_node = NULL;
1388 // Here, we find the chrome_config node by name.
petersont@google.com252873ef2008-08-04 21:59:451389 for (xmlNodePtr p = top_node->children; p; p = p->next) {
petersont@google.comd01b8732008-10-16 02:18:071390 if (xmlStrEqual(p->name, BAD_CAST "chrome_config")) {
1391 chrome_config_node = p;
petersont@google.com252873ef2008-08-04 21:59:451392 break;
1393 }
1394 }
1395 // If the server data is formatted wrong and there is no
1396 // config node where we expect, we just drop out.
petersont@google.comd01b8732008-10-16 02:18:071397 if (chrome_config_node != NULL)
1398 GetSettingsFromChromeConfigNode(chrome_config_node);
petersont@google.com252873ef2008-08-04 21:59:451399 xmlFreeDoc(doc);
1400}
1401
petersont@google.comd01b8732008-10-16 02:18:071402void MetricsService::GetSettingsFromChromeConfigNode(
1403 xmlNodePtr chrome_config_node) {
1404 // Iterate through all children of the config node.
1405 for (xmlNodePtr current_node = chrome_config_node->children;
1406 current_node;
1407 current_node = current_node->next) {
1408 // If we find the upload tag, we appeal to another function
1409 // GetSettingsFromUploadNode to read all the data in it.
petersont@google.com252873ef2008-08-04 21:59:451410 if (xmlStrEqual(current_node->name, BAD_CAST "upload")) {
petersont@google.comd01b8732008-10-16 02:18:071411 GetSettingsFromUploadNode(current_node);
petersont@google.com252873ef2008-08-04 21:59:451412 continue;
1413 }
1414 }
1415}
initial.commit09911bf2008-07-26 23:55:291416
petersont@google.comd01b8732008-10-16 02:18:071417void MetricsService::InheritedProperties::OverwriteWhereNeeded(
1418 xmlNodePtr node) {
1419 xmlChar* salt_value = xmlGetProp(node, BAD_CAST "salt");
1420 if (salt_value) // If the property isn't there, xmlGetProp returns NULL.
1421 salt = atoi(reinterpret_cast<char*>(salt_value));
1422 // If the property isn't there, we keep the value the property had before
1423
1424 xmlChar* denominator_value = xmlGetProp(node, BAD_CAST "denominator");
1425 if (denominator_value)
1426 denominator = atoi(reinterpret_cast<char*>(denominator_value));
1427}
1428
1429void MetricsService::GetSettingsFromUploadNode(xmlNodePtr upload_node) {
1430 InheritedProperties props;
1431 GetSettingsFromUploadNodeRecursive(upload_node, props, "", true);
1432}
1433
pkasting@chromium.orgcac78842008-11-27 01:02:201434void MetricsService::GetSettingsFromUploadNodeRecursive(
1435 xmlNodePtr node,
1436 InheritedProperties props,
1437 std::string path_prefix,
1438 bool uploadOn) {
petersont@google.comd01b8732008-10-16 02:18:071439 props.OverwriteWhereNeeded(node);
1440
1441 // The bool uploadOn is set to true if the data represented by current
1442 // node should be uploaded. This gets inherited in the tree; the children
1443 // of a node that has already been rejected for upload get rejected for
1444 // upload.
1445 uploadOn = uploadOn && NodeProbabilityTest(node, props);
1446
1447 // The path is a / separated list of the node names ancestral to the current
1448 // one. So, if you want to check if the current node has a certain name,
1449 // compare to name. If you want to check if it is a certan tag at a certain
1450 // place in the tree, compare to the whole path.
1451 std::string name = std::string(reinterpret_cast<const char*>(node->name));
1452 std::string path = path_prefix + "/" + name;
1453
1454 if (path == "/upload") {
1455 xmlChar* upload_interval_val = xmlGetProp(node, BAD_CAST "interval");
1456 if (upload_interval_val) {
1457 interlog_duration_ = TimeDelta::FromSeconds(
1458 atoi(reinterpret_cast<char*>(upload_interval_val)));
1459 }
1460
1461 server_permits_upload_ = uploadOn;
1462 }
1463 if (path == "/upload/logs") {
1464 xmlChar* log_event_limit_val = xmlGetProp(node, BAD_CAST "event_limit");
1465 if (log_event_limit_val)
1466 log_event_limit_ = atoi(reinterpret_cast<char*>(log_event_limit_val));
1467 }
1468 if (name == "histogram") {
1469 xmlChar* type_value = xmlGetProp(node, BAD_CAST "type");
1470 if (type_value) {
1471 std::string type = (reinterpret_cast<char*>(type_value));
1472 if (uploadOn)
1473 histograms_to_upload_.insert(type);
1474 else
1475 histograms_to_omit_.insert(type);
1476 }
1477 }
1478 if (name == "log") {
1479 xmlChar* type_value = xmlGetProp(node, BAD_CAST "type");
1480 if (type_value) {
1481 std::string type = (reinterpret_cast<char*>(type_value));
1482 if (uploadOn)
1483 logs_to_upload_.insert(type);
1484 else
1485 logs_to_omit_.insert(type);
1486 }
1487 }
1488
1489 // Recursive call. If the node is a leaf i.e. if it ends in a "/>", then it
1490 // doesn't have children, so node->children is NULL, and this loop doesn't
1491 // call (that's how the recursion ends).
1492 for (xmlNodePtr child_node = node->children;
pkasting@chromium.orgcac78842008-11-27 01:02:201493 child_node;
1494 child_node = child_node->next) {
petersont@google.comd01b8732008-10-16 02:18:071495 GetSettingsFromUploadNodeRecursive(child_node, props, path, uploadOn);
1496 }
1497}
1498
1499bool MetricsService::NodeProbabilityTest(xmlNodePtr node,
pkasting@chromium.orgcac78842008-11-27 01:02:201500 InheritedProperties props) const {
petersont@google.comd01b8732008-10-16 02:18:071501 // Default value of probability on any node is 1, but recall that
1502 // its parents can already have been rejected for upload.
1503 double probability = 1;
1504
1505 // If a probability is specified in the node, we use it instead.
1506 xmlChar* probability_value = xmlGetProp(node, BAD_CAST "probability");
1507 if (probability_value)
jar@google.com0b33f80b2008-12-17 21:34:361508 probability = atoi(reinterpret_cast<char*>(probability_value));
petersont@google.comd01b8732008-10-16 02:18:071509
1510 return ProbabilityTest(probability, props.salt, props.denominator);
1511}
1512
1513bool MetricsService::ProbabilityTest(double probability,
1514 int salt,
1515 int denominator) const {
1516 // Okay, first we figure out how many of the digits of the
1517 // client_id_ we need in order to make a nice pseudorandomish
1518 // number in the range [0,denominator). Too many digits is
1519 // fine.
petersont@google.comd01b8732008-10-16 02:18:071520
1521 // n is the length of the client_id_ string
1522 size_t n = client_id_.size();
1523
1524 // idnumber is a positive integer generated from the client_id_.
1525 // It plus salt is going to give us our pseudorandom number.
1526 int idnumber = 0;
1527 const char* client_id_c_str = client_id_.c_str();
1528
1529 // Here we hash the relevant digits of the client_id_
1530 // string somehow to get a big integer idnumber (could be negative
1531 // from wraparound)
1532 int big = 1;
robertshield@google.com5ed73342009-03-18 17:39:431533 int last_pos = n - 1;
1534 for (size_t j = 0; j < n; ++j) {
1535 idnumber += static_cast<int>(client_id_c_str[last_pos - j]) * big;
petersont@google.comd01b8732008-10-16 02:18:071536 big *= 10;
1537 }
1538
1539 // Mod id number by denominator making sure to get a non-negative
1540 // answer.
pkasting@chromium.orgcac78842008-11-27 01:02:201541 idnumber = ((idnumber % denominator) + denominator) % denominator;
petersont@google.comd01b8732008-10-16 02:18:071542
pkasting@chromium.orgcac78842008-11-27 01:02:201543 // ((idnumber + salt) % denominator) / denominator is in the range [0,1]
petersont@google.comd01b8732008-10-16 02:18:071544 // if it's less than probability we call that an affirmative coin
1545 // toss.
pkasting@chromium.orgcac78842008-11-27 01:02:201546 return static_cast<double>((idnumber + salt) % denominator) <
1547 probability * denominator;
petersont@google.comd01b8732008-10-16 02:18:071548}
1549
initial.commit09911bf2008-07-26 23:55:291550void MetricsService::LogWindowChange(NotificationType type,
1551 const NotificationSource& source,
1552 const NotificationDetails& details) {
brettw@google.com534e54b2008-08-13 15:40:091553 int controller_id = -1;
1554 uintptr_t window_or_tab = source.map_key();
initial.commit09911bf2008-07-26 23:55:291555 MetricsLog::WindowEventType window_type;
1556
1557 // Note: since we stop all logging when a single OTR session is active, it is
1558 // possible that we start getting notifications about a window that we don't
1559 // know about.
brettw@google.com534e54b2008-08-13 15:40:091560 if (window_map_.find(window_or_tab) == window_map_.end()) {
1561 controller_id = next_window_id_++;
1562 window_map_[window_or_tab] = controller_id;
initial.commit09911bf2008-07-26 23:55:291563 } else {
brettw@google.com534e54b2008-08-13 15:40:091564 controller_id = window_map_[window_or_tab];
initial.commit09911bf2008-07-26 23:55:291565 }
jar@chromium.org92745242009-06-12 16:52:211566 DCHECK_NE(controller_id, -1);
initial.commit09911bf2008-07-26 23:55:291567
brettw@chromium.orgbfd04a62009-02-01 18:16:561568 switch (type.value) {
1569 case NotificationType::TAB_PARENTED:
1570 case NotificationType::BROWSER_OPENED:
initial.commit09911bf2008-07-26 23:55:291571 window_type = MetricsLog::WINDOW_CREATE;
1572 break;
1573
brettw@chromium.orgbfd04a62009-02-01 18:16:561574 case NotificationType::TAB_CLOSING:
1575 case NotificationType::BROWSER_CLOSED:
brettw@google.com534e54b2008-08-13 15:40:091576 window_map_.erase(window_map_.find(window_or_tab));
initial.commit09911bf2008-07-26 23:55:291577 window_type = MetricsLog::WINDOW_DESTROY;
1578 break;
1579
1580 default:
jar@chromium.orgb42c5e42010-06-03 20:43:251581 LOG(DFATAL);
paul@chromium.org68d74f02009-02-13 01:36:501582 return;
initial.commit09911bf2008-07-26 23:55:291583 }
1584
brettw@google.com534e54b2008-08-13 15:40:091585 // TODO(brettw) we should have some kind of ID for the parent.
1586 current_log_->RecordWindowEvent(window_type, controller_id, 0);
initial.commit09911bf2008-07-26 23:55:291587}
1588
1589void MetricsService::LogLoadComplete(NotificationType type,
1590 const NotificationSource& source,
1591 const NotificationDetails& details) {
1592 if (details == NotificationService::NoDetails())
1593 return;
1594
jar@google.com68475e602008-08-22 03:21:151595 // TODO(jar): There is a bug causing this to be called too many times, and
1596 // the log overflows. For now, we won't record these events.
dsh@google.com553dba62009-02-24 19:08:231597 UMA_HISTOGRAM_COUNTS("UMA.LogLoadComplete called", 1);
jar@google.com68475e602008-08-22 03:21:151598 return;
1599
initial.commit09911bf2008-07-26 23:55:291600 const Details<LoadNotificationDetails> load_details(details);
brettw@google.com534e54b2008-08-13 15:40:091601 int controller_id = window_map_[details.map_key()];
1602 current_log_->RecordLoadEvent(controller_id,
initial.commit09911bf2008-07-26 23:55:291603 load_details->url(),
1604 load_details->origin(),
1605 load_details->session_index(),
1606 load_details->load_time());
1607}
1608
cpu@google.come73c01972008-08-13 00:18:241609void MetricsService::IncrementPrefValue(const wchar_t* path) {
1610 PrefService* pref = g_browser_process->local_state();
1611 DCHECK(pref);
1612 int value = pref->GetInteger(path);
1613 pref->SetInteger(path, value + 1);
1614}
1615
robertshield@google.com0bb1a622009-03-04 03:22:321616void MetricsService::IncrementLongPrefsValue(const wchar_t* path) {
1617 PrefService* pref = g_browser_process->local_state();
1618 DCHECK(pref);
1619 int64 value = pref->GetInt64(path);
jar@chromium.orgb42c5e42010-06-03 20:43:251620 pref->SetInt64(path, value + 1);
robertshield@google.com0bb1a622009-03-04 03:22:321621}
1622
initial.commit09911bf2008-07-26 23:55:291623void MetricsService::LogLoadStarted() {
cpu@google.come73c01972008-08-13 00:18:241624 IncrementPrefValue(prefs::kStabilityPageLoadCount);
robertshield@google.com0bb1a622009-03-04 03:22:321625 IncrementLongPrefsValue(prefs::kUninstallMetricsPageLoadCount);
jar@google.com0b33f80b2008-12-17 21:34:361626 // We need to save the prefs, as page load count is a critical stat, and it
1627 // might be lost due to a crash :-(.
initial.commit09911bf2008-07-26 23:55:291628}
1629
initial.commit09911bf2008-07-26 23:55:291630void MetricsService::LogRendererCrash() {
cpu@google.come73c01972008-08-13 00:18:241631 IncrementPrefValue(prefs::kStabilityRendererCrashCount);
initial.commit09911bf2008-07-26 23:55:291632}
1633
asargent@chromium.org1f085622009-12-04 05:33:451634void MetricsService::LogExtensionRendererCrash() {
1635 IncrementPrefValue(prefs::kStabilityExtensionRendererCrashCount);
1636}
1637
initial.commit09911bf2008-07-26 23:55:291638void MetricsService::LogRendererHang() {
cpu@google.come73c01972008-08-13 00:18:241639 IncrementPrefValue(prefs::kStabilityRendererHangCount);
initial.commit09911bf2008-07-26 23:55:291640}
1641
jam@chromium.orga27a9382009-02-11 23:55:101642void MetricsService::LogChildProcessChange(
1643 NotificationType type,
1644 const NotificationSource& source,
1645 const NotificationDetails& details) {
gregoryd@google.com0d84c5d2009-10-09 01:10:421646 Details<ChildProcessInfo> child_details(details);
1647 const std::wstring& child_name = child_details->name();
1648
jam@chromium.orga27a9382009-02-11 23:55:101649 if (child_process_stats_buffer_.find(child_name) ==
1650 child_process_stats_buffer_.end()) {
gregoryd@google.com0d84c5d2009-10-09 01:10:421651 child_process_stats_buffer_[child_name] =
1652 ChildProcessStats(child_details->type());
initial.commit09911bf2008-07-26 23:55:291653 }
1654
jam@chromium.orga27a9382009-02-11 23:55:101655 ChildProcessStats& stats = child_process_stats_buffer_[child_name];
brettw@chromium.orgbfd04a62009-02-01 18:16:561656 switch (type.value) {
jam@chromium.orga27a9382009-02-11 23:55:101657 case NotificationType::CHILD_PROCESS_HOST_CONNECTED:
initial.commit09911bf2008-07-26 23:55:291658 stats.process_launches++;
1659 break;
1660
jam@chromium.orga27a9382009-02-11 23:55:101661 case NotificationType::CHILD_INSTANCE_CREATED:
initial.commit09911bf2008-07-26 23:55:291662 stats.instances++;
1663 break;
1664
jam@chromium.orga27a9382009-02-11 23:55:101665 case NotificationType::CHILD_PROCESS_CRASHED:
initial.commit09911bf2008-07-26 23:55:291666 stats.process_crashes++;
asargent@chromium.org1f085622009-12-04 05:33:451667 // Exclude plugin crashes from the count below because we report them via
1668 // a separate UMA metric.
1669 if (child_details->type() != ChildProcessInfo::PLUGIN_PROCESS) {
1670 IncrementPrefValue(prefs::kStabilityChildProcessCrashCount);
1671 }
initial.commit09911bf2008-07-26 23:55:291672 break;
1673
1674 default:
jar@chromium.orgb42c5e42010-06-03 20:43:251675 LOG(DFATAL) << "Unexpected notification type " << type.value;
initial.commit09911bf2008-07-26 23:55:291676 return;
1677 }
1678}
1679
1680// Recursively counts the number of bookmarks and folders in node.
munjal@chromium.orgb3c33d462009-06-26 22:29:201681static void CountBookmarks(const BookmarkNode* node,
1682 int* bookmarks,
1683 int* folders) {
sky@chromium.org037db002009-10-19 20:06:081684 if (node->type() == BookmarkNode::URL)
initial.commit09911bf2008-07-26 23:55:291685 (*bookmarks)++;
1686 else
1687 (*folders)++;
1688 for (int i = 0; i < node->GetChildCount(); ++i)
1689 CountBookmarks(node->GetChild(i), bookmarks, folders);
1690}
1691
munjal@chromium.orgb3c33d462009-06-26 22:29:201692void MetricsService::LogBookmarks(const BookmarkNode* node,
initial.commit09911bf2008-07-26 23:55:291693 const wchar_t* num_bookmarks_key,
1694 const wchar_t* num_folders_key) {
1695 DCHECK(node);
1696 int num_bookmarks = 0;
1697 int num_folders = 0;
1698 CountBookmarks(node, &num_bookmarks, &num_folders);
1699 num_folders--; // Don't include the root folder in the count.
1700
1701 PrefService* pref = g_browser_process->local_state();
1702 DCHECK(pref);
1703 pref->SetInteger(num_bookmarks_key, num_bookmarks);
1704 pref->SetInteger(num_folders_key, num_folders);
1705}
1706
sky@google.comd8e41ed2008-09-11 15:22:321707void MetricsService::LogBookmarks(BookmarkModel* model) {
initial.commit09911bf2008-07-26 23:55:291708 DCHECK(model);
1709 LogBookmarks(model->GetBookmarkBarNode(),
1710 prefs::kNumBookmarksOnBookmarkBar,
1711 prefs::kNumFoldersOnBookmarkBar);
1712 LogBookmarks(model->other_node(),
1713 prefs::kNumBookmarksInOtherBookmarkFolder,
1714 prefs::kNumFoldersInOtherBookmarkFolder);
1715 ScheduleNextStateSave();
1716}
1717
1718void MetricsService::LogKeywords(const TemplateURLModel* url_model) {
1719 DCHECK(url_model);
1720
1721 PrefService* pref = g_browser_process->local_state();
1722 DCHECK(pref);
1723 pref->SetInteger(prefs::kNumKeywords,
1724 static_cast<int>(url_model->GetTemplateURLs().size()));
1725 ScheduleNextStateSave();
1726}
1727
1728void MetricsService::RecordPluginChanges(PrefService* pref) {
1729 ListValue* plugins = pref->GetMutableList(prefs::kStabilityPluginStats);
1730 DCHECK(plugins);
1731
1732 for (ListValue::iterator value_iter = plugins->begin();
1733 value_iter != plugins->end(); ++value_iter) {
1734 if (!(*value_iter)->IsType(Value::TYPE_DICTIONARY)) {
jar@chromium.orgb42c5e42010-06-03 20:43:251735 LOG(DFATAL);
initial.commit09911bf2008-07-26 23:55:291736 continue;
1737 }
1738
1739 DictionaryValue* plugin_dict = static_cast<DictionaryValue*>(*value_iter);
nsylvain@chromium.org8e50b602009-03-03 22:59:431740 std::wstring plugin_name;
1741 plugin_dict->GetString(prefs::kStabilityPluginName, &plugin_name);
nsylvain@chromium.org6470ee8f2009-03-03 20:46:401742 if (plugin_name.empty()) {
jar@chromium.orgb42c5e42010-06-03 20:43:251743 LOG(DFATAL);
initial.commit09911bf2008-07-26 23:55:291744 continue;
1745 }
1746
nsylvain@chromium.org8e50b602009-03-03 22:59:431747 if (child_process_stats_buffer_.find(plugin_name) ==
jam@chromium.orga27a9382009-02-11 23:55:101748 child_process_stats_buffer_.end())
initial.commit09911bf2008-07-26 23:55:291749 continue;
1750
nsylvain@chromium.org8e50b602009-03-03 22:59:431751 ChildProcessStats stats = child_process_stats_buffer_[plugin_name];
initial.commit09911bf2008-07-26 23:55:291752 if (stats.process_launches) {
1753 int launches = 0;
nsylvain@chromium.org8e50b602009-03-03 22:59:431754 plugin_dict->GetInteger(prefs::kStabilityPluginLaunches, &launches);
initial.commit09911bf2008-07-26 23:55:291755 launches += stats.process_launches;
nsylvain@chromium.org8e50b602009-03-03 22:59:431756 plugin_dict->SetInteger(prefs::kStabilityPluginLaunches, launches);
initial.commit09911bf2008-07-26 23:55:291757 }
1758 if (stats.process_crashes) {
1759 int crashes = 0;
nsylvain@chromium.org8e50b602009-03-03 22:59:431760 plugin_dict->GetInteger(prefs::kStabilityPluginCrashes, &crashes);
initial.commit09911bf2008-07-26 23:55:291761 crashes += stats.process_crashes;
nsylvain@chromium.org8e50b602009-03-03 22:59:431762 plugin_dict->SetInteger(prefs::kStabilityPluginCrashes, crashes);
initial.commit09911bf2008-07-26 23:55:291763 }
1764 if (stats.instances) {
1765 int instances = 0;
nsylvain@chromium.org8e50b602009-03-03 22:59:431766 plugin_dict->GetInteger(prefs::kStabilityPluginInstances, &instances);
initial.commit09911bf2008-07-26 23:55:291767 instances += stats.instances;
nsylvain@chromium.org8e50b602009-03-03 22:59:431768 plugin_dict->SetInteger(prefs::kStabilityPluginInstances, instances);
initial.commit09911bf2008-07-26 23:55:291769 }
1770
nsylvain@chromium.org8e50b602009-03-03 22:59:431771 child_process_stats_buffer_.erase(plugin_name);
initial.commit09911bf2008-07-26 23:55:291772 }
1773
1774 // Now go through and add dictionaries for plugins that didn't already have
1775 // reports in Local State.
jam@chromium.orga27a9382009-02-11 23:55:101776 for (std::map<std::wstring, ChildProcessStats>::iterator cache_iter =
1777 child_process_stats_buffer_.begin();
1778 cache_iter != child_process_stats_buffer_.end(); ++cache_iter) {
jam@chromium.orga27a9382009-02-11 23:55:101779 ChildProcessStats stats = cache_iter->second;
gregoryd@google.com0d84c5d2009-10-09 01:10:421780
1781 // Insert only plugins information into the plugins list.
1782 if (ChildProcessInfo::PLUGIN_PROCESS != stats.process_type)
1783 continue;
1784
1785 std::wstring plugin_name = cache_iter->first;
1786
initial.commit09911bf2008-07-26 23:55:291787 DictionaryValue* plugin_dict = new DictionaryValue;
1788
nsylvain@chromium.org8e50b602009-03-03 22:59:431789 plugin_dict->SetString(prefs::kStabilityPluginName, plugin_name);
1790 plugin_dict->SetInteger(prefs::kStabilityPluginLaunches,
initial.commit09911bf2008-07-26 23:55:291791 stats.process_launches);
nsylvain@chromium.org8e50b602009-03-03 22:59:431792 plugin_dict->SetInteger(prefs::kStabilityPluginCrashes,
initial.commit09911bf2008-07-26 23:55:291793 stats.process_crashes);
nsylvain@chromium.org8e50b602009-03-03 22:59:431794 plugin_dict->SetInteger(prefs::kStabilityPluginInstances,
initial.commit09911bf2008-07-26 23:55:291795 stats.instances);
1796 plugins->Append(plugin_dict);
1797 }
jam@chromium.orga27a9382009-02-11 23:55:101798 child_process_stats_buffer_.clear();
initial.commit09911bf2008-07-26 23:55:291799}
1800
1801bool MetricsService::CanLogNotification(NotificationType type,
1802 const NotificationSource& source,
1803 const NotificationDetails& details) {
1804 // We simply don't log anything to UMA if there is a single off the record
1805 // session visible. The problem is that we always notify using the orginal
1806 // profile in order to simplify notification processing.
1807 return !BrowserList::IsOffTheRecordSessionActive();
1808}
1809
1810void MetricsService::RecordBooleanPrefValue(const wchar_t* path, bool value) {
1811 DCHECK(IsSingleThreaded());
1812
1813 PrefService* pref = g_browser_process->local_state();
1814 DCHECK(pref);
1815
1816 pref->SetBoolean(path, value);
1817 RecordCurrentState(pref);
1818}
1819
1820void MetricsService::RecordCurrentState(PrefService* pref) {
robertshield@google.com0bb1a622009-03-04 03:22:321821 pref->SetInt64(prefs::kStabilityLastTimestampSec, Time::Now().ToTimeT());
initial.commit09911bf2008-07-26 23:55:291822
1823 RecordPluginChanges(pref);
1824}
1825
initial.commit09911bf2008-07-26 23:55:291826static bool IsSingleThreaded() {
paul@chromium.orgdc6f4962009-02-13 01:25:501827 static PlatformThreadId thread_id = 0;
initial.commit09911bf2008-07-26 23:55:291828 if (!thread_id)
paul@chromium.orgdc6f4962009-02-13 01:25:501829 thread_id = PlatformThread::CurrentId();
1830 return PlatformThread::CurrentId() == thread_id;
initial.commit09911bf2008-07-26 23:55:291831}
rvargas@google.com5ccaa412009-11-13 22:00:161832
1833#if defined(OS_CHROMEOS)
zelidrag@chromium.org85ed9d42010-06-08 22:37:441834// static
1835std::string MetricsService::GetHardwareClass() {
1836 DCHECK(!ChromeThread::CurrentlyOn(ChromeThread::UI));
1837 std::string hardware_class;
1838 FilePath tool(kHardwareClassTool);
1839 CommandLine command(tool);
1840 if (base::GetAppOutput(command, &hardware_class)) {
1841 TrimWhitespaceASCII(hardware_class, TRIM_ALL, &hardware_class);
1842 } else {
1843 hardware_class = kUnknownHardwareClass;
1844 }
1845 return hardware_class;
1846}
1847
sky@chromium.org29cf16772010-04-21 15:13:471848void MetricsService::StartExternalMetrics() {
rvargas@google.com5ccaa412009-11-13 22:00:161849 external_metrics_ = new chromeos::ExternalMetrics;
sky@chromium.org29cf16772010-04-21 15:13:471850 external_metrics_->Start();
rvargas@google.com5ccaa412009-11-13 22:00:161851}
1852#endif