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