blob: 4d34ebb072a9a8c75666a0e3e3bc8600f0b3b216 [file] [log] [blame]
license.botbf09a502008-08-24 00:55:551// Copyright (c) 2006-2008 The Chromium Authors. All rights reserved.
2// 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
[email protected]281d2882009-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//
[email protected]281d2882009-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
[email protected]281d2882009-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)
[email protected]0b33f80b2008-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
[email protected]281d2882009-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
[email protected]281d2882009-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.
[email protected]28ab7f92009-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//
[email protected]28ab7f92009-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.
[email protected]0b33f80b2008-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
[email protected]281d2882009-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
[email protected]281d2882009-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
[email protected]dc6f4962009-02-13 01:25:50158#if defined(OS_WIN)
initial.commit09911bf2008-07-26 23:55:29159#include <windows.h>
[email protected]dc6f4962009-02-13 01:25:50160#endif
initial.commit09911bf2008-07-26 23:55:29161
[email protected]cd1adc22009-01-16 01:29:22162#include "chrome/browser/metrics/metrics_service.h"
initial.commit09911bf2008-07-26 23:55:29163
[email protected]690a99c2009-01-06 16:48:45164#include "base/file_path.h"
initial.commit09911bf2008-07-26 23:55:29165#include "base/histogram.h"
166#include "base/path_service.h"
[email protected]dc6f4962009-02-13 01:25:50167#include "base/platform_thread.h"
initial.commit09911bf2008-07-26 23:55:29168#include "base/string_util.h"
169#include "base/task.h"
[email protected]d8e41ed2008-09-11 15:22:32170#include "chrome/browser/bookmarks/bookmark_model.h"
initial.commit09911bf2008-07-26 23:55:29171#include "chrome/browser/browser.h"
172#include "chrome/browser/browser_list.h"
173#include "chrome/browser/browser_process.h"
174#include "chrome/browser/load_notification_details.h"
175#include "chrome/browser/memory_details.h"
[email protected]fd49e2d2009-02-20 17:21:30176#include "chrome/browser/plugin_service.h"
initial.commit09911bf2008-07-26 23:55:29177#include "chrome/browser/profile.h"
[email protected]8c8657d62009-01-16 18:31:26178#include "chrome/browser/renderer_host/render_process_host.h"
[email protected]d54e03a52009-01-16 00:31:04179#include "chrome/browser/search_engines/template_url.h"
180#include "chrome/browser/search_engines/template_url_model.h"
[email protected]a27a9382009-02-11 23:55:10181#include "chrome/common/child_process_info.h"
initial.commit09911bf2008-07-26 23:55:29182#include "chrome/common/chrome_paths.h"
[email protected]252873ef2008-08-04 21:59:45183#include "chrome/common/libxml_utils.h"
[email protected]bfd04a62009-02-01 18:16:56184#include "chrome/common/notification_service.h"
initial.commit09911bf2008-07-26 23:55:29185#include "chrome/common/pref_names.h"
186#include "chrome/common/pref_service.h"
[email protected]e09ba552009-02-05 03:26:29187#include "chrome/common/render_messages.h"
initial.commit09911bf2008-07-26 23:55:29188#include "googleurl/src/gurl.h"
189#include "net/base/load_flags.h"
190#include "third_party/bzip2/bzlib.h"
191
[email protected]dc6f4962009-02-13 01:25:50192#if defined(OS_POSIX)
193// TODO(port): Move these headers above as they are ported.
194#include "chrome/common/temp_scaffolding_stubs.h"
195#else
[email protected]dc6f4962009-02-13 01:25:50196#include "chrome/installer/util/google_update_settings.h"
197#endif
198
[email protected]e1acf6f2008-10-27 20:43:33199using base::Time;
200using base::TimeDelta;
201
initial.commit09911bf2008-07-26 23:55:29202// Check to see that we're being called on only one thread.
203static bool IsSingleThreaded();
204
205static const char kMetricsURL[] =
[email protected]0acdfc42009-01-30 01:13:22206 "https://clients4.google.com/firefox/metrics/collect";
initial.commit09911bf2008-07-26 23:55:29207
208static const char kMetricsType[] = "application/vnd.mozilla.metrics.bz2";
209
210// The delay, in seconds, after startup before sending the first log message.
[email protected]252873ef2008-08-04 21:59:45211static const int kInitialInterlogDuration = 60; // one minute
212
213// The default maximum number of events in a log uploaded to the UMA server.
[email protected]0b33f80b2008-12-17 21:34:36214static const int kInitialEventLimit = 2400;
[email protected]68475e602008-08-22 03:21:15215
216// If an upload fails, and the transmission was over this byte count, then we
217// will discard the log, and not try to retransmit it. We also don't persist
218// the log to the prefs for transmission during the next chrome session if this
219// limit is exceeded.
220static const int kUploadLogAvoidRetransmitSize = 50000;
initial.commit09911bf2008-07-26 23:55:29221
222// When we have logs from previous Chrome sessions to send, how long should we
223// delay (in seconds) between each log transmission.
224static const int kUnsentLogDelay = 15; // 15 seconds
225
226// Minimum time a log typically exists before sending, in seconds.
227// This number is supplied by the server, but until we parse it out of a server
228// response, we use this duration to specify how long we should wait before
229// sending the next log. If the channel is busy, such as when there is a
230// failure during an attempt to transmit a previous log, then a log may wait
231// (and continue to accrue now log entries) for a much greater period of time.
[email protected]0eb34fee2009-01-21 08:04:38232static const int kMinSecondsPerLog = 20 * 60; // Twenty minutes.
initial.commit09911bf2008-07-26 23:55:29233
initial.commit09911bf2008-07-26 23:55:29234// When we don't succeed at transmitting a log to a server, we progressively
235// wait longer and longer before sending the next log. This backoff process
236// help reduce load on the server, and makes the amount of backoff vary between
237// clients so that a collision (server overload?) on retransmit is less likely.
238// The following is the constant we use to expand that inter-log duration.
239static const double kBackoff = 1.1;
240// We limit the maximum backoff to be no greater than some multiple of the
241// default kMinSecondsPerLog. The following is that maximum ratio.
242static const int kMaxBackoff = 10;
243
244// Interval, in seconds, between state saves.
245static const int kSaveStateInterval = 5 * 60; // five minutes
246
247// The number of "initial" logs we're willing to save, and hope to send during
248// a future Chrome session. Initial logs contain crash stats, and are pretty
249// small.
250static const size_t kMaxInitialLogsPersisted = 20;
251
252// The number of ongoing logs we're willing to save persistently, and hope to
[email protected]281d2882009-01-20 20:32:42253// send during a this or future sessions. Note that each log may be pretty
initial.commit09911bf2008-07-26 23:55:29254// large, as presumably the related "initial" log wasn't sent (probably nothing
255// was, as the user was probably off-line). As a result, the log probably kept
256// accumulating while the "initial" log was stalled (pending_), and couldn't be
257// sent. As a result, we don't want to save too many of these mega-logs.
258// A "standard shutdown" will create a small log, including just the data that
259// was not yet been transmitted, and that is normal (to have exactly one
260// ongoing_log_ at startup).
[email protected]281d2882009-01-20 20:32:42261static const size_t kMaxOngoingLogsPersisted = 8;
initial.commit09911bf2008-07-26 23:55:29262
263
264// Handles asynchronous fetching of memory details.
265// Will run the provided task after finished.
266class MetricsMemoryDetails : public MemoryDetails {
267 public:
268 explicit MetricsMemoryDetails(Task* completion) : completion_(completion) {}
269
270 virtual void OnDetailsAvailable() {
271 MessageLoop::current()->PostTask(FROM_HERE, completion_);
272 }
273
274 private:
275 Task* completion_;
276 DISALLOW_EVIL_CONSTRUCTORS(MetricsMemoryDetails);
277};
278
279class MetricsService::GetPluginListTaskComplete : public Task {
280 virtual void Run() {
281 g_browser_process->metrics_service()->OnGetPluginListTaskComplete();
282 }
283};
284
285class MetricsService::GetPluginListTask : public Task {
286 public:
287 explicit GetPluginListTask(MessageLoop* callback_loop)
288 : callback_loop_(callback_loop) {}
289
290 virtual void Run() {
291 std::vector<WebPluginInfo> plugins;
292 PluginService::GetInstance()->GetPlugins(false, &plugins);
293
294 callback_loop_->PostTask(FROM_HERE, new GetPluginListTaskComplete());
295 }
296
297 private:
298 MessageLoop* callback_loop_;
299};
300
301// static
302void MetricsService::RegisterPrefs(PrefService* local_state) {
303 DCHECK(IsSingleThreaded());
304 local_state->RegisterStringPref(prefs::kMetricsClientID, L"");
305 local_state->RegisterStringPref(prefs::kMetricsClientIDTimestamp, L"0");
306 local_state->RegisterStringPref(prefs::kStabilityLaunchTimeSec, L"0");
307 local_state->RegisterStringPref(prefs::kStabilityLastTimestampSec, L"0");
308 local_state->RegisterStringPref(prefs::kStabilityUptimeSec, L"0");
[email protected]541f77922009-02-23 21:14:38309 local_state->RegisterStringPref(prefs::kStabilityStatsVersion, L"");
initial.commit09911bf2008-07-26 23:55:29310 local_state->RegisterBooleanPref(prefs::kStabilityExitedCleanly, true);
311 local_state->RegisterBooleanPref(prefs::kStabilitySessionEndCompleted, true);
312 local_state->RegisterIntegerPref(prefs::kMetricsSessionID, -1);
313 local_state->RegisterIntegerPref(prefs::kStabilityLaunchCount, 0);
314 local_state->RegisterIntegerPref(prefs::kStabilityCrashCount, 0);
315 local_state->RegisterIntegerPref(prefs::kStabilityIncompleteSessionEndCount,
316 0);
317 local_state->RegisterIntegerPref(prefs::kStabilityPageLoadCount, 0);
318 local_state->RegisterIntegerPref(prefs::kSecurityRendererOnSboxDesktop, 0);
319 local_state->RegisterIntegerPref(prefs::kSecurityRendererOnDefaultDesktop, 0);
320 local_state->RegisterIntegerPref(prefs::kStabilityRendererCrashCount, 0);
321 local_state->RegisterIntegerPref(prefs::kStabilityRendererHangCount, 0);
[email protected]e73c01972008-08-13 00:18:24322 local_state->RegisterIntegerPref(prefs::kStabilityBreakpadRegistrationFail,
323 0);
324 local_state->RegisterIntegerPref(prefs::kStabilityBreakpadRegistrationSuccess,
325 0);
326 local_state->RegisterIntegerPref(prefs::kStabilityDebuggerPresent, 0);
327 local_state->RegisterIntegerPref(prefs::kStabilityDebuggerNotPresent, 0);
328
initial.commit09911bf2008-07-26 23:55:29329 local_state->RegisterDictionaryPref(prefs::kProfileMetrics);
330 local_state->RegisterIntegerPref(prefs::kNumBookmarksOnBookmarkBar, 0);
331 local_state->RegisterIntegerPref(prefs::kNumFoldersOnBookmarkBar, 0);
332 local_state->RegisterIntegerPref(prefs::kNumBookmarksInOtherBookmarkFolder,
333 0);
334 local_state->RegisterIntegerPref(prefs::kNumFoldersInOtherBookmarkFolder, 0);
335 local_state->RegisterIntegerPref(prefs::kNumKeywords, 0);
336 local_state->RegisterListPref(prefs::kMetricsInitialLogs);
337 local_state->RegisterListPref(prefs::kMetricsOngoingLogs);
338}
339
[email protected]541f77922009-02-23 21:14:38340// static
341void MetricsService::DiscardOldStabilityStats(PrefService* local_state) {
342 local_state->SetBoolean(prefs::kStabilityExitedCleanly, true);
343
344 local_state->SetInteger(prefs::kStabilityIncompleteSessionEndCount, 0);
345 local_state->SetInteger(prefs::kStabilityBreakpadRegistrationSuccess, 0);
346 local_state->SetInteger(prefs::kStabilityBreakpadRegistrationFail, 0);
347 local_state->SetInteger(prefs::kStabilityDebuggerPresent, 0);
348 local_state->SetInteger(prefs::kStabilityDebuggerNotPresent, 0);
349
350 local_state->SetInteger(prefs::kStabilityLaunchCount, 0);
351 local_state->SetInteger(prefs::kStabilityCrashCount, 0);
352
353 local_state->SetInteger(prefs::kStabilityPageLoadCount, 0);
354 local_state->SetInteger(prefs::kStabilityRendererCrashCount, 0);
355 local_state->SetInteger(prefs::kStabilityRendererHangCount, 0);
356
357 local_state->SetInteger(prefs::kSecurityRendererOnSboxDesktop, 0);
358 local_state->SetInteger(prefs::kSecurityRendererOnDefaultDesktop, 0);
359
360 local_state->SetString(prefs::kStabilityUptimeSec, L"0");
361
362 local_state->ClearPref(prefs::kStabilityPluginStats);
363}
364
initial.commit09911bf2008-07-26 23:55:29365MetricsService::MetricsService()
[email protected]d01b8732008-10-16 02:18:07366 : recording_active_(false),
367 reporting_active_(false),
368 user_permits_upload_(false),
369 server_permits_upload_(true),
370 state_(INITIALIZED),
initial.commit09911bf2008-07-26 23:55:29371 pending_log_(NULL),
372 pending_log_text_(""),
373 current_fetch_(NULL),
374 current_log_(NULL),
[email protected]d01b8732008-10-16 02:18:07375 idle_since_last_transmission_(false),
initial.commit09911bf2008-07-26 23:55:29376 next_window_id_(0),
377 log_sender_factory_(this),
378 state_saver_factory_(this),
379 logged_samples_(),
[email protected]252873ef2008-08-04 21:59:45380 interlog_duration_(TimeDelta::FromSeconds(kInitialInterlogDuration)),
[email protected]d01b8732008-10-16 02:18:07381 log_event_limit_(kInitialEventLimit),
initial.commit09911bf2008-07-26 23:55:29382 timer_pending_(false) {
383 DCHECK(IsSingleThreaded());
384 InitializeMetricsState();
385}
386
387MetricsService::~MetricsService() {
388 SetRecording(false);
[email protected]d8bc79bf2009-01-28 01:17:58389 if (pending_log_) {
390 delete pending_log_;
391 pending_log_ = NULL;
392 }
393 if (current_log_) {
394 delete current_log_;
395 current_log_ = NULL;
396 }
initial.commit09911bf2008-07-26 23:55:29397}
398
[email protected]d01b8732008-10-16 02:18:07399void MetricsService::SetUserPermitsUpload(bool enabled) {
400 HandleIdleSinceLastTransmission(false);
401 user_permits_upload_ = enabled;
402}
403
404void MetricsService::Start() {
405 SetRecording(true);
406 SetReporting(true);
407}
408
409void MetricsService::StartRecordingOnly() {
410 SetRecording(true);
411 SetReporting(false);
412}
413
414void MetricsService::Stop() {
415 SetReporting(false);
416 SetRecording(false);
417}
418
initial.commit09911bf2008-07-26 23:55:29419void MetricsService::SetRecording(bool enabled) {
420 DCHECK(IsSingleThreaded());
421
[email protected]d01b8732008-10-16 02:18:07422 if (enabled == recording_active_)
initial.commit09911bf2008-07-26 23:55:29423 return;
424
425 if (enabled) {
426 StartRecording();
427 ListenerRegistration(true);
428 } else {
429 // Turn off all observers.
430 ListenerRegistration(false);
431 PushPendingLogsToUnsentLists();
432 DCHECK(!pending_log());
433 if (state_ > INITIAL_LOG_READY && unsent_logs())
434 state_ = SEND_OLD_INITIAL_LOGS;
435 }
[email protected]d01b8732008-10-16 02:18:07436 recording_active_ = enabled;
initial.commit09911bf2008-07-26 23:55:29437}
438
[email protected]d01b8732008-10-16 02:18:07439bool MetricsService::recording_active() const {
initial.commit09911bf2008-07-26 23:55:29440 DCHECK(IsSingleThreaded());
[email protected]d01b8732008-10-16 02:18:07441 return recording_active_;
initial.commit09911bf2008-07-26 23:55:29442}
443
[email protected]d01b8732008-10-16 02:18:07444void MetricsService::SetReporting(bool enable) {
445 if (reporting_active_ != enable) {
446 reporting_active_ = enable;
447 if (reporting_active_)
initial.commit09911bf2008-07-26 23:55:29448 StartLogTransmissionTimer();
449 }
[email protected]d01b8732008-10-16 02:18:07450}
451
452bool MetricsService::reporting_active() const {
453 DCHECK(IsSingleThreaded());
454 return reporting_active_;
initial.commit09911bf2008-07-26 23:55:29455}
456
457void MetricsService::Observe(NotificationType type,
458 const NotificationSource& source,
459 const NotificationDetails& details) {
460 DCHECK(current_log_);
461 DCHECK(IsSingleThreaded());
462
463 if (!CanLogNotification(type, source, details))
464 return;
465
[email protected]bfd04a62009-02-01 18:16:56466 switch (type.value) {
467 case NotificationType::USER_ACTION:
initial.commit09911bf2008-07-26 23:55:29468 current_log_->RecordUserAction(*Details<const wchar_t*>(details).ptr());
469 break;
470
[email protected]bfd04a62009-02-01 18:16:56471 case NotificationType::BROWSER_OPENED:
472 case NotificationType::BROWSER_CLOSED:
initial.commit09911bf2008-07-26 23:55:29473 LogWindowChange(type, source, details);
474 break;
475
[email protected]bfd04a62009-02-01 18:16:56476 case NotificationType::TAB_PARENTED:
477 case NotificationType::TAB_CLOSING:
initial.commit09911bf2008-07-26 23:55:29478 LogWindowChange(type, source, details);
479 break;
480
[email protected]bfd04a62009-02-01 18:16:56481 case NotificationType::LOAD_STOP:
initial.commit09911bf2008-07-26 23:55:29482 LogLoadComplete(type, source, details);
483 break;
484
[email protected]bfd04a62009-02-01 18:16:56485 case NotificationType::LOAD_START:
initial.commit09911bf2008-07-26 23:55:29486 LogLoadStarted();
487 break;
488
[email protected]bfd04a62009-02-01 18:16:56489 case NotificationType::RENDERER_PROCESS_TERMINATED:
initial.commit09911bf2008-07-26 23:55:29490 if (!*Details<bool>(details).ptr())
491 LogRendererCrash();
492 break;
493
[email protected]bfd04a62009-02-01 18:16:56494 case NotificationType::RENDERER_PROCESS_HANG:
initial.commit09911bf2008-07-26 23:55:29495 LogRendererHang();
496 break;
497
[email protected]bfd04a62009-02-01 18:16:56498 case NotificationType::RENDERER_PROCESS_IN_SBOX:
initial.commit09911bf2008-07-26 23:55:29499 LogRendererInSandbox(*Details<bool>(details).ptr());
500 break;
501
[email protected]a27a9382009-02-11 23:55:10502 case NotificationType::CHILD_PROCESS_HOST_CONNECTED:
503 case NotificationType::CHILD_PROCESS_CRASHED:
504 case NotificationType::CHILD_INSTANCE_CREATED:
505 LogChildProcessChange(type, source, details);
initial.commit09911bf2008-07-26 23:55:29506 break;
507
[email protected]bfd04a62009-02-01 18:16:56508 case NotificationType::TEMPLATE_URL_MODEL_LOADED:
initial.commit09911bf2008-07-26 23:55:29509 LogKeywords(Source<TemplateURLModel>(source).ptr());
510 break;
511
[email protected]bfd04a62009-02-01 18:16:56512 case NotificationType::OMNIBOX_OPENED_URL:
initial.commit09911bf2008-07-26 23:55:29513 current_log_->RecordOmniboxOpenedURL(
514 *Details<AutocompleteLog>(details).ptr());
515 break;
516
[email protected]bfd04a62009-02-01 18:16:56517 case NotificationType::BOOKMARK_MODEL_LOADED:
[email protected]d8e41ed2008-09-11 15:22:32518 LogBookmarks(Source<Profile>(source)->GetBookmarkModel());
initial.commit09911bf2008-07-26 23:55:29519 break;
520
521 default:
522 NOTREACHED();
523 break;
524 }
[email protected]d01b8732008-10-16 02:18:07525
526 HandleIdleSinceLastTransmission(false);
527
528 if (current_log_)
[email protected]281d2882009-01-20 20:32:42529 DLOG(INFO) << "METRICS: NUMBER OF EVENTS = " << current_log_->num_events();
[email protected]d01b8732008-10-16 02:18:07530}
531
532void MetricsService::HandleIdleSinceLastTransmission(bool in_idle) {
533 // If there wasn't a lot of action, maybe the computer was asleep, in which
534 // case, the log transmissions should have stopped. Here we start them up
535 // again.
[email protected]cac78842008-11-27 01:02:20536 if (!in_idle && idle_since_last_transmission_)
537 StartLogTransmissionTimer();
538 idle_since_last_transmission_ = in_idle;
initial.commit09911bf2008-07-26 23:55:29539}
540
541void MetricsService::RecordCleanShutdown() {
542 RecordBooleanPrefValue(prefs::kStabilityExitedCleanly, true);
543}
544
545void MetricsService::RecordStartOfSessionEnd() {
546 RecordBooleanPrefValue(prefs::kStabilitySessionEndCompleted, false);
547}
548
549void MetricsService::RecordCompletedSessionEnd() {
550 RecordBooleanPrefValue(prefs::kStabilitySessionEndCompleted, true);
551}
552
[email protected]e73c01972008-08-13 00:18:24553void MetricsService:: RecordBreakpadRegistration(bool success) {
[email protected]68475e602008-08-22 03:21:15554 if (!success)
[email protected]e73c01972008-08-13 00:18:24555 IncrementPrefValue(prefs::kStabilityBreakpadRegistrationFail);
556 else
557 IncrementPrefValue(prefs::kStabilityBreakpadRegistrationSuccess);
558}
559
560void MetricsService::RecordBreakpadHasDebugger(bool has_debugger) {
561 if (!has_debugger)
562 IncrementPrefValue(prefs::kStabilityDebuggerNotPresent);
563 else
[email protected]68475e602008-08-22 03:21:15564 IncrementPrefValue(prefs::kStabilityDebuggerPresent);
[email protected]e73c01972008-08-13 00:18:24565}
566
initial.commit09911bf2008-07-26 23:55:29567//------------------------------------------------------------------------------
568// private methods
569//------------------------------------------------------------------------------
570
571
572//------------------------------------------------------------------------------
573// Initialization methods
574
575void MetricsService::InitializeMetricsState() {
576 PrefService* pref = g_browser_process->local_state();
577 DCHECK(pref);
578
[email protected]541f77922009-02-23 21:14:38579 if (WideToUTF8(pref->GetString(prefs::kStabilityStatsVersion)) !=
580 MetricsLog::GetVersionString()) {
581 // This is a new version, so we don't want to confuse the stats about the
582 // old version with info that we upload.
583 DiscardOldStabilityStats(pref);
584 pref->SetString(prefs::kStabilityStatsVersion,
585 UTF8ToWide(MetricsLog::GetVersionString()));
586 }
587
initial.commit09911bf2008-07-26 23:55:29588 client_id_ = WideToUTF8(pref->GetString(prefs::kMetricsClientID));
589 if (client_id_.empty()) {
590 client_id_ = GenerateClientID();
591 pref->SetString(prefs::kMetricsClientID, UTF8ToWide(client_id_));
592
593 // Might as well make a note of how long this ID has existed
594 pref->SetString(prefs::kMetricsClientIDTimestamp,
595 Int64ToWString(Time::Now().ToTimeT()));
596 }
597
598 // Update session ID
599 session_id_ = pref->GetInteger(prefs::kMetricsSessionID);
600 ++session_id_;
601 pref->SetInteger(prefs::kMetricsSessionID, session_id_);
602
initial.commit09911bf2008-07-26 23:55:29603 // Stability bookkeeping
[email protected]e73c01972008-08-13 00:18:24604 IncrementPrefValue(prefs::kStabilityLaunchCount);
initial.commit09911bf2008-07-26 23:55:29605
[email protected]e73c01972008-08-13 00:18:24606 if (!pref->GetBoolean(prefs::kStabilityExitedCleanly)) {
607 IncrementPrefValue(prefs::kStabilityCrashCount);
initial.commit09911bf2008-07-26 23:55:29608 }
[email protected]e73c01972008-08-13 00:18:24609
610 // This will be set to 'true' if we exit cleanly.
initial.commit09911bf2008-07-26 23:55:29611 pref->SetBoolean(prefs::kStabilityExitedCleanly, false);
612
[email protected]e73c01972008-08-13 00:18:24613 if (!pref->GetBoolean(prefs::kStabilitySessionEndCompleted)) {
614 IncrementPrefValue(prefs::kStabilityIncompleteSessionEndCount);
initial.commit09911bf2008-07-26 23:55:29615 }
616 // This is marked false when we get a WM_ENDSESSION.
617 pref->SetBoolean(prefs::kStabilitySessionEndCompleted, true);
618
619 int64 last_start_time =
620 StringToInt64(pref->GetString(prefs::kStabilityLaunchTimeSec));
621 int64 last_end_time =
622 StringToInt64(pref->GetString(prefs::kStabilityLastTimestampSec));
623 int64 uptime =
624 StringToInt64(pref->GetString(prefs::kStabilityUptimeSec));
625
626 if (last_start_time && last_end_time) {
627 // TODO(JAR): Exclude sleep time. ... which must be gathered in UI loop.
628 uptime += last_end_time - last_start_time;
629 pref->SetString(prefs::kStabilityUptimeSec, Int64ToWString(uptime));
630 }
631 pref->SetString(prefs::kStabilityLaunchTimeSec,
632 Int64ToWString(Time::Now().ToTimeT()));
633
634 // Save profile metrics.
635 PrefService* prefs = g_browser_process->local_state();
636 if (prefs) {
637 // Remove the current dictionary and store it for use when sending data to
638 // server. By removing the value we prune potentially dead profiles
639 // (and keys). All valid values are added back once services startup.
640 const DictionaryValue* profile_dictionary =
641 prefs->GetDictionary(prefs::kProfileMetrics);
642 if (profile_dictionary) {
643 // Do a deep copy of profile_dictionary since ClearPref will delete it.
644 profile_dictionary_.reset(static_cast<DictionaryValue*>(
645 profile_dictionary->DeepCopy()));
646 prefs->ClearPref(prefs::kProfileMetrics);
647 }
648 }
649
650 // Kick off the process of saving the state (so the uptime numbers keep
651 // getting updated) every n minutes.
652 ScheduleNextStateSave();
653}
654
655void MetricsService::OnGetPluginListTaskComplete() {
656 DCHECK(state_ == PLUGIN_LIST_REQUESTED);
657 if (state_ == PLUGIN_LIST_REQUESTED)
658 state_ = PLUGIN_LIST_ARRIVED;
659}
660
661std::string MetricsService::GenerateClientID() {
[email protected]dc6f4962009-02-13 01:25:50662#if defined(OS_WIN)
initial.commit09911bf2008-07-26 23:55:29663 const int kGUIDSize = 39;
664
665 GUID guid;
666 HRESULT guid_result = CoCreateGuid(&guid);
667 DCHECK(SUCCEEDED(guid_result));
668
669 std::wstring guid_string;
670 int result = StringFromGUID2(guid,
671 WriteInto(&guid_string, kGUIDSize), kGUIDSize);
672 DCHECK(result == kGUIDSize);
673
674 return WideToUTF8(guid_string.substr(1, guid_string.length() - 2));
[email protected]dc6f4962009-02-13 01:25:50675#else
676 // TODO(port): Implement for Mac and linux.
[email protected]f5d0e152009-02-19 21:54:37677 // Rather than actually implementing a random source, might this be a good
678 // time to implement http://code.google.com/p/chromium/issues/detail?id=2278
679 // ? I think so!
[email protected]dc6f4962009-02-13 01:25:50680 NOTIMPLEMENTED();
681 return std::string();
682#endif
initial.commit09911bf2008-07-26 23:55:29683}
684
685
686//------------------------------------------------------------------------------
687// State save methods
688
689void MetricsService::ScheduleNextStateSave() {
690 state_saver_factory_.RevokeAll();
691
692 MessageLoop::current()->PostDelayedTask(FROM_HERE,
693 state_saver_factory_.NewRunnableMethod(&MetricsService::SaveLocalState),
694 kSaveStateInterval * 1000);
695}
696
697void MetricsService::SaveLocalState() {
698 PrefService* pref = g_browser_process->local_state();
699 if (!pref) {
700 NOTREACHED();
701 return;
702 }
703
704 RecordCurrentState(pref);
705 pref->ScheduleSavePersistentPrefs(g_browser_process->file_thread());
706
[email protected]281d2882009-01-20 20:32:42707 // TODO(jar): Does this run down the batteries????
initial.commit09911bf2008-07-26 23:55:29708 ScheduleNextStateSave();
709}
710
711
712//------------------------------------------------------------------------------
713// Recording control methods
714
715void MetricsService::StartRecording() {
716 if (current_log_)
717 return;
718
719 current_log_ = new MetricsLog(client_id_, session_id_);
720 if (state_ == INITIALIZED) {
721 // We only need to schedule that run once.
722 state_ = PLUGIN_LIST_REQUESTED;
723
724 // Make sure the plugin list is loaded before the inital log is sent, so
725 // that the main thread isn't blocked generating the list.
726 g_browser_process->file_thread()->message_loop()->PostDelayedTask(FROM_HERE,
727 new GetPluginListTask(MessageLoop::current()),
[email protected]252873ef2008-08-04 21:59:45728 kInitialInterlogDuration * 1000 / 2);
initial.commit09911bf2008-07-26 23:55:29729 }
730}
731
732void MetricsService::StopRecording(MetricsLog** log) {
733 if (!current_log_)
734 return;
735
[email protected]68475e602008-08-22 03:21:15736 // TODO(jar): Integrate bounds on log recording more consistently, so that we
737 // can stop recording logs that are too big much sooner.
[email protected]d01b8732008-10-16 02:18:07738 if (current_log_->num_events() > log_event_limit_) {
[email protected]68475e602008-08-22 03:21:15739 UMA_HISTOGRAM_COUNTS(L"UMA.Discarded Log Events",
740 current_log_->num_events());
741 current_log_->CloseLog();
742 delete current_log_;
[email protected]294638782008-09-24 00:22:41743 current_log_ = NULL;
[email protected]68475e602008-08-22 03:21:15744 StartRecording(); // Start trivial log to hold our histograms.
745 }
746
[email protected]0b33f80b2008-12-17 21:34:36747 // Put incremental data (histogram deltas, and realtime stats deltas) at the
[email protected]147bbc0b2009-01-06 19:37:40748 // end of all log transmissions (initial log handles this separately).
initial.commit09911bf2008-07-26 23:55:29749 // Don't bother if we're going to discard current_log_.
[email protected]0b33f80b2008-12-17 21:34:36750 if (log) {
[email protected]54131d252009-02-09 05:49:22751 // TODO(jar): when initial logs and ongoing logs have equal survivability,
752 // uncomment the following line to expedite stability data uploads.
753 // current_log_->RecordIncrementalStabilityElements();
initial.commit09911bf2008-07-26 23:55:29754 RecordCurrentHistograms();
[email protected]0b33f80b2008-12-17 21:34:36755 }
initial.commit09911bf2008-07-26 23:55:29756
757 current_log_->CloseLog();
[email protected]cac78842008-11-27 01:02:20758 if (log)
initial.commit09911bf2008-07-26 23:55:29759 *log = current_log_;
[email protected]cac78842008-11-27 01:02:20760 else
initial.commit09911bf2008-07-26 23:55:29761 delete current_log_;
initial.commit09911bf2008-07-26 23:55:29762 current_log_ = NULL;
763}
764
765void MetricsService::ListenerRegistration(bool start_listening) {
[email protected]bfd04a62009-02-01 18:16:56766 AddOrRemoveObserver(this, NotificationType::BROWSER_OPENED, start_listening);
767 AddOrRemoveObserver(this, NotificationType::BROWSER_CLOSED, start_listening);
768 AddOrRemoveObserver(this, NotificationType::USER_ACTION, start_listening);
769 AddOrRemoveObserver(this, NotificationType::TAB_PARENTED, start_listening);
770 AddOrRemoveObserver(this, NotificationType::TAB_CLOSING, start_listening);
771 AddOrRemoveObserver(this, NotificationType::LOAD_START, start_listening);
772 AddOrRemoveObserver(this, NotificationType::LOAD_STOP, start_listening);
773 AddOrRemoveObserver(this, NotificationType::RENDERER_PROCESS_IN_SBOX,
initial.commit09911bf2008-07-26 23:55:29774 start_listening);
[email protected]bfd04a62009-02-01 18:16:56775 AddOrRemoveObserver(this, NotificationType::RENDERER_PROCESS_TERMINATED,
initial.commit09911bf2008-07-26 23:55:29776 start_listening);
[email protected]bfd04a62009-02-01 18:16:56777 AddOrRemoveObserver(this, NotificationType::RENDERER_PROCESS_HANG,
778 start_listening);
[email protected]a27a9382009-02-11 23:55:10779 AddOrRemoveObserver(this, NotificationType::CHILD_PROCESS_HOST_CONNECTED,
[email protected]bfd04a62009-02-01 18:16:56780 start_listening);
[email protected]a27a9382009-02-11 23:55:10781 AddOrRemoveObserver(this, NotificationType::CHILD_INSTANCE_CREATED,
[email protected]bfd04a62009-02-01 18:16:56782 start_listening);
[email protected]a27a9382009-02-11 23:55:10783 AddOrRemoveObserver(this, NotificationType::CHILD_PROCESS_CRASHED,
[email protected]bfd04a62009-02-01 18:16:56784 start_listening);
785 AddOrRemoveObserver(this, NotificationType::TEMPLATE_URL_MODEL_LOADED,
786 start_listening);
787 AddOrRemoveObserver(this, NotificationType::OMNIBOX_OPENED_URL,
788 start_listening);
789 AddOrRemoveObserver(this, NotificationType::BOOKMARK_MODEL_LOADED,
790 start_listening);
initial.commit09911bf2008-07-26 23:55:29791}
792
793// static
794void MetricsService::AddOrRemoveObserver(NotificationObserver* observer,
[email protected]cac78842008-11-27 01:02:20795 NotificationType type,
796 bool is_add) {
initial.commit09911bf2008-07-26 23:55:29797 NotificationService* service = NotificationService::current();
798
[email protected]cac78842008-11-27 01:02:20799 if (is_add)
initial.commit09911bf2008-07-26 23:55:29800 service->AddObserver(observer, type, NotificationService::AllSources());
[email protected]cac78842008-11-27 01:02:20801 else
initial.commit09911bf2008-07-26 23:55:29802 service->RemoveObserver(observer, type, NotificationService::AllSources());
initial.commit09911bf2008-07-26 23:55:29803}
804
805void MetricsService::PushPendingLogsToUnsentLists() {
806 if (state_ < INITIAL_LOG_READY)
[email protected]28ab7f92009-01-06 21:39:04807 return; // We didn't and still don't have time to get plugin list etc.
initial.commit09911bf2008-07-26 23:55:29808
809 if (pending_log()) {
810 PreparePendingLogText();
811 if (state_ == INITIAL_LOG_READY) {
812 // We may race here, and send second copy of initial log later.
813 unsent_initial_logs_.push_back(pending_log_text_);
[email protected]d01b8732008-10-16 02:18:07814 state_ = SEND_OLD_INITIAL_LOGS;
initial.commit09911bf2008-07-26 23:55:29815 } else {
[email protected]281d2882009-01-20 20:32:42816 // TODO(jar): Verify correctness in other states, including sending unsent
[email protected]541f77922009-02-23 21:14:38817 // initial logs.
[email protected]68475e602008-08-22 03:21:15818 PushPendingLogTextToUnsentOngoingLogs();
initial.commit09911bf2008-07-26 23:55:29819 }
820 DiscardPendingLog();
821 }
822 DCHECK(!pending_log());
823 StopRecording(&pending_log_);
824 PreparePendingLogText();
[email protected]68475e602008-08-22 03:21:15825 PushPendingLogTextToUnsentOngoingLogs();
initial.commit09911bf2008-07-26 23:55:29826 DiscardPendingLog();
827 StoreUnsentLogs();
828}
829
[email protected]68475e602008-08-22 03:21:15830void MetricsService::PushPendingLogTextToUnsentOngoingLogs() {
[email protected]d01b8732008-10-16 02:18:07831 // If UMA response told us not to upload, there's no need to save the pending
832 // log. It wasn't supposed to be uploaded anyway.
833 if (!server_permits_upload_)
834 return;
835
[email protected]dc6f4962009-02-13 01:25:50836 if (pending_log_text_.length() >
837 static_cast<size_t>(kUploadLogAvoidRetransmitSize)) {
[email protected]68475e602008-08-22 03:21:15838 UMA_HISTOGRAM_COUNTS(L"UMA.Large Accumulated Log Not Persisted",
839 static_cast<int>(pending_log_text_.length()));
840 return;
841 }
842 unsent_ongoing_logs_.push_back(pending_log_text_);
843}
844
initial.commit09911bf2008-07-26 23:55:29845//------------------------------------------------------------------------------
846// Transmission of logs methods
847
848void MetricsService::StartLogTransmissionTimer() {
[email protected]d01b8732008-10-16 02:18:07849 // If we're not reporting, there's no point in starting a log transmission
850 // timer.
851 if (!reporting_active())
852 return;
853
initial.commit09911bf2008-07-26 23:55:29854 if (!current_log_)
855 return; // Recorder is shutdown.
[email protected]d01b8732008-10-16 02:18:07856
857 // If there is already a timer running, we leave it running.
858 // If timer_pending is true because the fetch is waiting for a response,
859 // we return for now and let the response handler start the timer.
860 if (timer_pending_)
initial.commit09911bf2008-07-26 23:55:29861 return;
[email protected]d01b8732008-10-16 02:18:07862
[email protected]d01b8732008-10-16 02:18:07863 // Before starting the timer, set timer_pending_ to true.
initial.commit09911bf2008-07-26 23:55:29864 timer_pending_ = true;
[email protected]d01b8732008-10-16 02:18:07865
866 // Right before the UMA transmission gets started, there's one more thing we'd
867 // like to record: the histogram of memory usage, so we spawn a task to
868 // collect the memory details and when that task is finished, we arrange for
869 // TryToStartTransmission to take over.
initial.commit09911bf2008-07-26 23:55:29870 MessageLoop::current()->PostDelayedTask(FROM_HERE,
871 log_sender_factory_.
872 NewRunnableMethod(&MetricsService::CollectMemoryDetails),
873 static_cast<int>(interlog_duration_.InMilliseconds()));
874}
875
876void MetricsService::TryToStartTransmission() {
877 DCHECK(IsSingleThreaded());
878
[email protected]d01b8732008-10-16 02:18:07879 // This function should only be called via timer, so timer_pending_
880 // should be true.
881 DCHECK(timer_pending_);
882 timer_pending_ = false;
initial.commit09911bf2008-07-26 23:55:29883
884 DCHECK(!current_fetch_.get());
initial.commit09911bf2008-07-26 23:55:29885
[email protected]d01b8732008-10-16 02:18:07886 // If we're getting no notifications, then the log won't have much in it, and
887 // it's possible the computer is about to go to sleep, so don't upload and
888 // don't restart the transmission timer.
889 if (idle_since_last_transmission_)
890 return;
891
892 // If somehow there is a fetch in progress, we return setting timer_pending_
893 // to true and hope things work out.
894 if (current_fetch_.get()) {
895 timer_pending_ = true;
896 return;
897 }
898
899 // If uploads are forbidden by UMA response, there's no point in keeping
900 // the current_log_, and the more often we delete it, the less likely it is
901 // to expand forever.
902 if (!server_permits_upload_ && current_log_) {
903 StopRecording(NULL);
904 StartRecording();
905 }
initial.commit09911bf2008-07-26 23:55:29906
907 if (!current_log_)
908 return; // Logging was disabled.
[email protected]d01b8732008-10-16 02:18:07909 if (!reporting_active())
initial.commit09911bf2008-07-26 23:55:29910 return; // Don't do work if we're not going to send anything now.
911
[email protected]d01b8732008-10-16 02:18:07912 MakePendingLog();
initial.commit09911bf2008-07-26 23:55:29913
[email protected]d01b8732008-10-16 02:18:07914 // MakePendingLog should have put something in the pending log, if it didn't,
915 // we start the timer again, return and hope things work out.
916 if (!pending_log()) {
917 StartLogTransmissionTimer();
918 return;
919 }
initial.commit09911bf2008-07-26 23:55:29920
[email protected]d01b8732008-10-16 02:18:07921 // If we're not supposed to upload any UMA data because the response or the
922 // user said so, cancel the upload at this point, but start the timer.
923 if (!TransmissionPermitted()) {
924 DiscardPendingLog();
925 StartLogTransmissionTimer();
926 return;
927 }
initial.commit09911bf2008-07-26 23:55:29928
[email protected]d01b8732008-10-16 02:18:07929 PrepareFetchWithPendingLog();
930
931 if (!current_fetch_.get()) {
932 // Compression failed, and log discarded :-/.
933 DiscardPendingLog();
934 StartLogTransmissionTimer(); // Maybe we'll do better next time
935 // TODO(jar): If compression failed, we should have created a tiny log and
936 // compressed that, so that we can signal that we're losing logs.
937 return;
938 }
939
940 DCHECK(!timer_pending_);
941
942 // The URL fetch is a like timer in that after a while we get called back
943 // so we set timer_pending_ true just as we start the url fetch.
944 timer_pending_ = true;
945 current_fetch_->Start();
946
947 HandleIdleSinceLastTransmission(true);
948}
949
950
951void MetricsService::MakePendingLog() {
952 if (pending_log())
953 return;
954
955 switch (state_) {
956 case INITIALIZED:
957 case PLUGIN_LIST_REQUESTED: // We should be further along by now.
958 DCHECK(false);
959 return;
960
961 case PLUGIN_LIST_ARRIVED:
962 // We need to wait for the initial log to be ready before sending
963 // anything, because the server will tell us whether it wants to hear
964 // from us.
965 PrepareInitialLog();
966 DCHECK(state_ == PLUGIN_LIST_ARRIVED);
967 RecallUnsentLogs();
968 state_ = INITIAL_LOG_READY;
969 break;
970
971 case SEND_OLD_INITIAL_LOGS:
[email protected]cac78842008-11-27 01:02:20972 if (!unsent_initial_logs_.empty()) {
973 pending_log_text_ = unsent_initial_logs_.back();
974 break;
975 }
[email protected]d01b8732008-10-16 02:18:07976 state_ = SENDING_OLD_LOGS;
977 // Fall through.
initial.commit09911bf2008-07-26 23:55:29978
[email protected]d01b8732008-10-16 02:18:07979 case SENDING_OLD_LOGS:
980 if (!unsent_ongoing_logs_.empty()) {
981 pending_log_text_ = unsent_ongoing_logs_.back();
982 break;
983 }
984 state_ = SENDING_CURRENT_LOGS;
985 // Fall through.
986
987 case SENDING_CURRENT_LOGS:
988 StopRecording(&pending_log_);
989 StartRecording();
990 break;
991
992 default:
993 DCHECK(false);
994 return;
995 }
996
997 DCHECK(pending_log());
998}
999
1000bool MetricsService::TransmissionPermitted() const {
1001 // If the user forbids uploading that's they're business, and we don't upload
1002 // anything. If the server forbids uploading, that's our business, so we take
1003 // that to mean it forbids current logs, but we still send up the inital logs
1004 // and any old logs.
[email protected]d01b8732008-10-16 02:18:071005 if (!user_permits_upload_)
1006 return false;
[email protected]cac78842008-11-27 01:02:201007 if (server_permits_upload_)
[email protected]d01b8732008-10-16 02:18:071008 return true;
initial.commit09911bf2008-07-26 23:55:291009
[email protected]cac78842008-11-27 01:02:201010 switch (state_) {
1011 case INITIAL_LOG_READY:
1012 case SEND_OLD_INITIAL_LOGS:
1013 case SENDING_OLD_LOGS:
1014 return true;
1015
1016 case SENDING_CURRENT_LOGS:
1017 default:
1018 return false;
[email protected]8c8824b2008-09-20 01:55:501019 }
initial.commit09911bf2008-07-26 23:55:291020}
1021
1022void MetricsService::CollectMemoryDetails() {
1023 Task* task = log_sender_factory_.
1024 NewRunnableMethod(&MetricsService::TryToStartTransmission);
1025 MetricsMemoryDetails* details = new MetricsMemoryDetails(task);
1026 details->StartFetch();
1027
1028 // Collect WebCore cache information to put into a histogram.
1029 for (RenderProcessHost::iterator it = RenderProcessHost::begin();
1030 it != RenderProcessHost::end(); ++it) {
1031 it->second->Send(new ViewMsg_GetCacheResourceStats());
1032 }
1033}
1034
1035void MetricsService::PrepareInitialLog() {
1036 DCHECK(state_ == PLUGIN_LIST_ARRIVED);
1037 std::vector<WebPluginInfo> plugins;
1038 PluginService::GetInstance()->GetPlugins(false, &plugins);
1039
1040 MetricsLog* log = new MetricsLog(client_id_, session_id_);
1041 log->RecordEnvironment(plugins, profile_dictionary_.get());
1042
1043 // Histograms only get written to current_log_, so setup for the write.
1044 MetricsLog* save_log = current_log_;
1045 current_log_ = log;
1046 RecordCurrentHistograms(); // Into current_log_... which is really log.
1047 current_log_ = save_log;
1048
1049 log->CloseLog();
1050 DCHECK(!pending_log());
1051 pending_log_ = log;
1052}
1053
1054void MetricsService::RecallUnsentLogs() {
1055 DCHECK(unsent_initial_logs_.empty());
1056 DCHECK(unsent_ongoing_logs_.empty());
1057
1058 PrefService* local_state = g_browser_process->local_state();
1059 DCHECK(local_state);
1060
1061 ListValue* unsent_initial_logs = local_state->GetMutableList(
1062 prefs::kMetricsInitialLogs);
1063 for (ListValue::iterator it = unsent_initial_logs->begin();
1064 it != unsent_initial_logs->end(); ++it) {
[email protected]5e324b72008-12-18 00:07:591065 std::string log;
1066 (*it)->GetAsString(&log);
1067 unsent_initial_logs_.push_back(log);
initial.commit09911bf2008-07-26 23:55:291068 }
1069
1070 ListValue* unsent_ongoing_logs = local_state->GetMutableList(
1071 prefs::kMetricsOngoingLogs);
1072 for (ListValue::iterator it = unsent_ongoing_logs->begin();
1073 it != unsent_ongoing_logs->end(); ++it) {
[email protected]5e324b72008-12-18 00:07:591074 std::string log;
1075 (*it)->GetAsString(&log);
1076 unsent_ongoing_logs_.push_back(log);
initial.commit09911bf2008-07-26 23:55:291077 }
1078}
1079
1080void MetricsService::StoreUnsentLogs() {
1081 if (state_ < INITIAL_LOG_READY)
1082 return; // We never Recalled the prior unsent logs.
1083
1084 PrefService* local_state = g_browser_process->local_state();
1085 DCHECK(local_state);
1086
1087 ListValue* unsent_initial_logs = local_state->GetMutableList(
1088 prefs::kMetricsInitialLogs);
1089 unsent_initial_logs->Clear();
1090 size_t start = 0;
1091 if (unsent_initial_logs_.size() > kMaxInitialLogsPersisted)
1092 start = unsent_initial_logs_.size() - kMaxInitialLogsPersisted;
1093 for (size_t i = start; i < unsent_initial_logs_.size(); ++i)
1094 unsent_initial_logs->Append(
[email protected]5e324b72008-12-18 00:07:591095 Value::CreateStringValue(unsent_initial_logs_[i]));
initial.commit09911bf2008-07-26 23:55:291096
1097 ListValue* unsent_ongoing_logs = local_state->GetMutableList(
1098 prefs::kMetricsOngoingLogs);
1099 unsent_ongoing_logs->Clear();
1100 start = 0;
1101 if (unsent_ongoing_logs_.size() > kMaxOngoingLogsPersisted)
1102 start = unsent_ongoing_logs_.size() - kMaxOngoingLogsPersisted;
1103 for (size_t i = start; i < unsent_ongoing_logs_.size(); ++i)
1104 unsent_ongoing_logs->Append(
[email protected]5e324b72008-12-18 00:07:591105 Value::CreateStringValue(unsent_ongoing_logs_[i]));
initial.commit09911bf2008-07-26 23:55:291106}
1107
1108void MetricsService::PreparePendingLogText() {
1109 DCHECK(pending_log());
1110 if (!pending_log_text_.empty())
1111 return;
1112 int original_size = pending_log_->GetEncodedLogSize();
1113 pending_log_->GetEncodedLog(WriteInto(&pending_log_text_, original_size),
1114 original_size);
1115}
1116
[email protected]d01b8732008-10-16 02:18:071117void MetricsService::PrepareFetchWithPendingLog() {
initial.commit09911bf2008-07-26 23:55:291118 DCHECK(pending_log());
1119 DCHECK(!current_fetch_.get());
1120 PreparePendingLogText();
1121 DCHECK(!pending_log_text_.empty());
1122
1123 // Allow security conscious users to see all metrics logs that we send.
1124 LOG(INFO) << "METRICS LOG: " << pending_log_text_;
1125
1126 std::string compressed_log;
[email protected]cac78842008-11-27 01:02:201127 if (!Bzip2Compress(pending_log_text_, &compressed_log)) {
initial.commit09911bf2008-07-26 23:55:291128 NOTREACHED() << "Failed to compress log for transmission.";
1129 DiscardPendingLog();
1130 StartLogTransmissionTimer(); // Maybe we'll do better on next log :-/.
1131 return;
1132 }
[email protected]cac78842008-11-27 01:02:201133
initial.commit09911bf2008-07-26 23:55:291134 current_fetch_.reset(new URLFetcher(GURL(kMetricsURL), URLFetcher::POST,
1135 this));
1136 current_fetch_->set_request_context(Profile::GetDefaultRequestContext());
1137 current_fetch_->set_upload_data(kMetricsType, compressed_log);
initial.commit09911bf2008-07-26 23:55:291138}
1139
1140void MetricsService::DiscardPendingLog() {
1141 if (pending_log_) { // Shutdown might have deleted it!
1142 delete pending_log_;
1143 pending_log_ = NULL;
1144 }
1145 pending_log_text_.clear();
1146}
1147
1148// This implementation is based on the Firefox MetricsService implementation.
1149bool MetricsService::Bzip2Compress(const std::string& input,
1150 std::string* output) {
1151 bz_stream stream = {0};
1152 // As long as our input is smaller than the bzip2 block size, we should get
1153 // the best compression. For example, if your input was 250k, using a block
1154 // size of 300k or 500k should result in the same compression ratio. Since
1155 // our data should be under 100k, using the minimum block size of 100k should
1156 // allocate less temporary memory, but result in the same compression ratio.
1157 int result = BZ2_bzCompressInit(&stream,
1158 1, // 100k (min) block size
1159 0, // quiet
1160 0); // default "work factor"
1161 if (result != BZ_OK) { // out of memory?
1162 return false;
1163 }
1164
1165 output->clear();
1166
1167 stream.next_in = const_cast<char*>(input.data());
1168 stream.avail_in = static_cast<int>(input.size());
1169 // NOTE: we don't need a BZ_RUN phase since our input buffer contains
1170 // the entire input
1171 do {
1172 output->resize(output->size() + 1024);
1173 stream.next_out = &((*output)[stream.total_out_lo32]);
1174 stream.avail_out = static_cast<int>(output->size()) - stream.total_out_lo32;
1175 result = BZ2_bzCompress(&stream, BZ_FINISH);
1176 } while (result == BZ_FINISH_OK);
1177 if (result != BZ_STREAM_END) // unknown failure?
1178 return false;
1179 result = BZ2_bzCompressEnd(&stream);
1180 DCHECK(result == BZ_OK);
1181
1182 output->resize(stream.total_out_lo32);
1183
1184 return true;
1185}
1186
1187static const char* StatusToString(const URLRequestStatus& status) {
1188 switch (status.status()) {
1189 case URLRequestStatus::SUCCESS:
1190 return "SUCCESS";
1191
1192 case URLRequestStatus::IO_PENDING:
1193 return "IO_PENDING";
1194
1195 case URLRequestStatus::HANDLED_EXTERNALLY:
1196 return "HANDLED_EXTERNALLY";
1197
1198 case URLRequestStatus::CANCELED:
1199 return "CANCELED";
1200
1201 case URLRequestStatus::FAILED:
1202 return "FAILED";
1203
1204 default:
1205 NOTREACHED();
1206 return "Unknown";
1207 }
1208}
1209
1210void MetricsService::OnURLFetchComplete(const URLFetcher* source,
1211 const GURL& url,
1212 const URLRequestStatus& status,
1213 int response_code,
1214 const ResponseCookies& cookies,
1215 const std::string& data) {
1216 DCHECK(timer_pending_);
1217 timer_pending_ = false;
1218 DCHECK(current_fetch_.get());
1219 current_fetch_.reset(NULL); // We're not allowed to re-use it.
1220
1221 // Confirm send so that we can move on.
[email protected]281d2882009-01-20 20:32:421222 LOG(INFO) << "METRICS RESPONSE CODE: " << response_code << " status=" <<
[email protected]cac78842008-11-27 01:02:201223 StatusToString(status);
[email protected]252873ef2008-08-04 21:59:451224
[email protected]0eb34fee2009-01-21 08:04:381225 // Provide boolean for error recovery (allow us to ignore response_code).
[email protected]dc6f4962009-02-13 01:25:501226 bool discard_log = false;
[email protected]0eb34fee2009-01-21 08:04:381227
[email protected]68475e602008-08-22 03:21:151228 if (response_code != 200 &&
[email protected]dc6f4962009-02-13 01:25:501229 pending_log_text_.length() >
1230 static_cast<size_t>(kUploadLogAvoidRetransmitSize)) {
[email protected]68475e602008-08-22 03:21:151231 UMA_HISTOGRAM_COUNTS(L"UMA.Large Rejected Log was Discarded",
1232 static_cast<int>(pending_log_text_.length()));
[email protected]0eb34fee2009-01-21 08:04:381233 discard_log = true;
1234 } else if (response_code == 400) {
1235 // Bad syntax. Retransmission won't work.
1236 UMA_HISTOGRAM_COUNTS(L"UMA.Unacceptable_Log_Discarded", state_);
1237 discard_log = true;
[email protected]68475e602008-08-22 03:21:151238 }
1239
[email protected]0eb34fee2009-01-21 08:04:381240 if (response_code != 200 && !discard_log) {
[email protected]281d2882009-01-20 20:32:421241 LOG(INFO) << "METRICS: transmission attempt returned a failure code: "
1242 << response_code << ". Verify network connectivity";
[email protected]252873ef2008-08-04 21:59:451243 HandleBadResponseCode();
[email protected]0eb34fee2009-01-21 08:04:381244 } else { // Successful receipt (or we are discarding log).
[email protected]281d2882009-01-20 20:32:421245 LOG(INFO) << "METRICS RESPONSE DATA: " << data;
initial.commit09911bf2008-07-26 23:55:291246 switch (state_) {
1247 case INITIAL_LOG_READY:
1248 state_ = SEND_OLD_INITIAL_LOGS;
1249 break;
1250
1251 case SEND_OLD_INITIAL_LOGS:
1252 DCHECK(!unsent_initial_logs_.empty());
1253 unsent_initial_logs_.pop_back();
1254 StoreUnsentLogs();
1255 break;
1256
1257 case SENDING_OLD_LOGS:
1258 DCHECK(!unsent_ongoing_logs_.empty());
1259 unsent_ongoing_logs_.pop_back();
1260 StoreUnsentLogs();
1261 break;
1262
1263 case SENDING_CURRENT_LOGS:
1264 break;
1265
1266 default:
1267 DCHECK(false);
1268 break;
1269 }
[email protected]d01b8732008-10-16 02:18:071270
initial.commit09911bf2008-07-26 23:55:291271 DiscardPendingLog();
[email protected]29be92552008-08-07 22:49:271272 // Since we sent a log, make sure our in-memory state is recorded to disk.
1273 PrefService* local_state = g_browser_process->local_state();
1274 DCHECK(local_state);
1275 if (local_state)
1276 local_state->ScheduleSavePersistentPrefs(
1277 g_browser_process->file_thread());
[email protected]252873ef2008-08-04 21:59:451278
[email protected]147bbc0b2009-01-06 19:37:401279 // Provide a default (free of exponetial backoff, other varances) in case
1280 // the server does not specify a value.
1281 interlog_duration_ = TimeDelta::FromSeconds(kMinSecondsPerLog);
1282
[email protected]252873ef2008-08-04 21:59:451283 GetSettingsFromResponseData(data);
[email protected]252873ef2008-08-04 21:59:451284 // Override server specified interlog delay if there are unsent logs to
[email protected]29be92552008-08-07 22:49:271285 // transmit.
initial.commit09911bf2008-07-26 23:55:291286 if (unsent_logs()) {
1287 DCHECK(state_ < SENDING_CURRENT_LOGS);
1288 interlog_duration_ = TimeDelta::FromSeconds(kUnsentLogDelay);
initial.commit09911bf2008-07-26 23:55:291289 }
1290 }
[email protected]252873ef2008-08-04 21:59:451291
initial.commit09911bf2008-07-26 23:55:291292 StartLogTransmissionTimer();
1293}
1294
[email protected]252873ef2008-08-04 21:59:451295void MetricsService::HandleBadResponseCode() {
[email protected]281d2882009-01-20 20:32:421296 LOG(INFO) << "Verify your metrics logs are formatted correctly. "
[email protected]cac78842008-11-27 01:02:201297 "Verify server is active at " << kMetricsURL;
[email protected]252873ef2008-08-04 21:59:451298 if (!pending_log()) {
[email protected]281d2882009-01-20 20:32:421299 LOG(INFO) << "METRICS: Recorder shutdown during log transmission.";
[email protected]252873ef2008-08-04 21:59:451300 } else {
1301 // Send progressively less frequently.
1302 DCHECK(kBackoff > 1.0);
1303 interlog_duration_ = TimeDelta::FromMicroseconds(
1304 static_cast<int64>(kBackoff * interlog_duration_.InMicroseconds()));
1305
1306 if (kMaxBackoff * TimeDelta::FromSeconds(kMinSecondsPerLog) <
[email protected]cac78842008-11-27 01:02:201307 interlog_duration_) {
[email protected]252873ef2008-08-04 21:59:451308 interlog_duration_ = kMaxBackoff *
1309 TimeDelta::FromSeconds(kMinSecondsPerLog);
[email protected]cac78842008-11-27 01:02:201310 }
[email protected]252873ef2008-08-04 21:59:451311
[email protected]281d2882009-01-20 20:32:421312 LOG(INFO) << "METRICS: transmission retry being scheduled in " <<
[email protected]252873ef2008-08-04 21:59:451313 interlog_duration_.InSeconds() << " seconds for " <<
1314 pending_log_text_;
initial.commit09911bf2008-07-26 23:55:291315 }
initial.commit09911bf2008-07-26 23:55:291316}
1317
[email protected]252873ef2008-08-04 21:59:451318void MetricsService::GetSettingsFromResponseData(const std::string& data) {
1319 // We assume that the file is structured as a block opened by <response>
[email protected]d01b8732008-10-16 02:18:071320 // and that inside response, there is a block opened by tag <chrome_config>
1321 // other tags are ignored for now except the content of <chrome_config>.
[email protected]281d2882009-01-20 20:32:421322 LOG(INFO) << "METRICS: getting settings from response data: " << data;
[email protected]d01b8732008-10-16 02:18:071323
[email protected]252873ef2008-08-04 21:59:451324 int data_size = static_cast<int>(data.size());
1325 if (data_size < 0) {
[email protected]281d2882009-01-20 20:32:421326 LOG(INFO) << "METRICS: server response data bad size: " << data_size <<
[email protected]cac78842008-11-27 01:02:201327 "; aborting extraction of settings";
[email protected]252873ef2008-08-04 21:59:451328 return;
1329 }
[email protected]cac78842008-11-27 01:02:201330 xmlDocPtr doc = xmlReadMemory(data.c_str(), data_size, "", NULL, 0);
[email protected]252873ef2008-08-04 21:59:451331 DCHECK(doc);
[email protected]d01b8732008-10-16 02:18:071332 // If the document is malformed, we just use the settings that were there.
1333 if (!doc) {
[email protected]281d2882009-01-20 20:32:421334 LOG(INFO) << "METRICS: reading xml from server response data failed";
[email protected]252873ef2008-08-04 21:59:451335 return;
[email protected]d01b8732008-10-16 02:18:071336 }
[email protected]252873ef2008-08-04 21:59:451337
[email protected]d01b8732008-10-16 02:18:071338 xmlNodePtr top_node = xmlDocGetRootElement(doc), chrome_config_node = NULL;
1339 // Here, we find the chrome_config node by name.
[email protected]252873ef2008-08-04 21:59:451340 for (xmlNodePtr p = top_node->children; p; p = p->next) {
[email protected]d01b8732008-10-16 02:18:071341 if (xmlStrEqual(p->name, BAD_CAST "chrome_config")) {
1342 chrome_config_node = p;
[email protected]252873ef2008-08-04 21:59:451343 break;
1344 }
1345 }
1346 // If the server data is formatted wrong and there is no
1347 // config node where we expect, we just drop out.
[email protected]d01b8732008-10-16 02:18:071348 if (chrome_config_node != NULL)
1349 GetSettingsFromChromeConfigNode(chrome_config_node);
[email protected]252873ef2008-08-04 21:59:451350 xmlFreeDoc(doc);
1351}
1352
[email protected]d01b8732008-10-16 02:18:071353void MetricsService::GetSettingsFromChromeConfigNode(
1354 xmlNodePtr chrome_config_node) {
1355 // Iterate through all children of the config node.
1356 for (xmlNodePtr current_node = chrome_config_node->children;
1357 current_node;
1358 current_node = current_node->next) {
1359 // If we find the upload tag, we appeal to another function
1360 // GetSettingsFromUploadNode to read all the data in it.
[email protected]252873ef2008-08-04 21:59:451361 if (xmlStrEqual(current_node->name, BAD_CAST "upload")) {
[email protected]d01b8732008-10-16 02:18:071362 GetSettingsFromUploadNode(current_node);
[email protected]252873ef2008-08-04 21:59:451363 continue;
1364 }
1365 }
1366}
initial.commit09911bf2008-07-26 23:55:291367
[email protected]d01b8732008-10-16 02:18:071368void MetricsService::InheritedProperties::OverwriteWhereNeeded(
1369 xmlNodePtr node) {
1370 xmlChar* salt_value = xmlGetProp(node, BAD_CAST "salt");
1371 if (salt_value) // If the property isn't there, xmlGetProp returns NULL.
1372 salt = atoi(reinterpret_cast<char*>(salt_value));
1373 // If the property isn't there, we keep the value the property had before
1374
1375 xmlChar* denominator_value = xmlGetProp(node, BAD_CAST "denominator");
1376 if (denominator_value)
1377 denominator = atoi(reinterpret_cast<char*>(denominator_value));
1378}
1379
1380void MetricsService::GetSettingsFromUploadNode(xmlNodePtr upload_node) {
1381 InheritedProperties props;
1382 GetSettingsFromUploadNodeRecursive(upload_node, props, "", true);
1383}
1384
[email protected]cac78842008-11-27 01:02:201385void MetricsService::GetSettingsFromUploadNodeRecursive(
1386 xmlNodePtr node,
1387 InheritedProperties props,
1388 std::string path_prefix,
1389 bool uploadOn) {
[email protected]d01b8732008-10-16 02:18:071390 props.OverwriteWhereNeeded(node);
1391
1392 // The bool uploadOn is set to true if the data represented by current
1393 // node should be uploaded. This gets inherited in the tree; the children
1394 // of a node that has already been rejected for upload get rejected for
1395 // upload.
1396 uploadOn = uploadOn && NodeProbabilityTest(node, props);
1397
1398 // The path is a / separated list of the node names ancestral to the current
1399 // one. So, if you want to check if the current node has a certain name,
1400 // compare to name. If you want to check if it is a certan tag at a certain
1401 // place in the tree, compare to the whole path.
1402 std::string name = std::string(reinterpret_cast<const char*>(node->name));
1403 std::string path = path_prefix + "/" + name;
1404
1405 if (path == "/upload") {
1406 xmlChar* upload_interval_val = xmlGetProp(node, BAD_CAST "interval");
1407 if (upload_interval_val) {
1408 interlog_duration_ = TimeDelta::FromSeconds(
1409 atoi(reinterpret_cast<char*>(upload_interval_val)));
1410 }
1411
1412 server_permits_upload_ = uploadOn;
1413 }
1414 if (path == "/upload/logs") {
1415 xmlChar* log_event_limit_val = xmlGetProp(node, BAD_CAST "event_limit");
1416 if (log_event_limit_val)
1417 log_event_limit_ = atoi(reinterpret_cast<char*>(log_event_limit_val));
1418 }
1419 if (name == "histogram") {
1420 xmlChar* type_value = xmlGetProp(node, BAD_CAST "type");
1421 if (type_value) {
1422 std::string type = (reinterpret_cast<char*>(type_value));
1423 if (uploadOn)
1424 histograms_to_upload_.insert(type);
1425 else
1426 histograms_to_omit_.insert(type);
1427 }
1428 }
1429 if (name == "log") {
1430 xmlChar* type_value = xmlGetProp(node, BAD_CAST "type");
1431 if (type_value) {
1432 std::string type = (reinterpret_cast<char*>(type_value));
1433 if (uploadOn)
1434 logs_to_upload_.insert(type);
1435 else
1436 logs_to_omit_.insert(type);
1437 }
1438 }
1439
1440 // Recursive call. If the node is a leaf i.e. if it ends in a "/>", then it
1441 // doesn't have children, so node->children is NULL, and this loop doesn't
1442 // call (that's how the recursion ends).
1443 for (xmlNodePtr child_node = node->children;
[email protected]cac78842008-11-27 01:02:201444 child_node;
1445 child_node = child_node->next) {
[email protected]d01b8732008-10-16 02:18:071446 GetSettingsFromUploadNodeRecursive(child_node, props, path, uploadOn);
1447 }
1448}
1449
1450bool MetricsService::NodeProbabilityTest(xmlNodePtr node,
[email protected]cac78842008-11-27 01:02:201451 InheritedProperties props) const {
[email protected]d01b8732008-10-16 02:18:071452 // Default value of probability on any node is 1, but recall that
1453 // its parents can already have been rejected for upload.
1454 double probability = 1;
1455
1456 // If a probability is specified in the node, we use it instead.
1457 xmlChar* probability_value = xmlGetProp(node, BAD_CAST "probability");
1458 if (probability_value)
[email protected]0b33f80b2008-12-17 21:34:361459 probability = atoi(reinterpret_cast<char*>(probability_value));
[email protected]d01b8732008-10-16 02:18:071460
1461 return ProbabilityTest(probability, props.salt, props.denominator);
1462}
1463
1464bool MetricsService::ProbabilityTest(double probability,
1465 int salt,
1466 int denominator) const {
1467 // Okay, first we figure out how many of the digits of the
1468 // client_id_ we need in order to make a nice pseudorandomish
1469 // number in the range [0,denominator). Too many digits is
1470 // fine.
[email protected]d01b8732008-10-16 02:18:071471
1472 // n is the length of the client_id_ string
1473 size_t n = client_id_.size();
1474
1475 // idnumber is a positive integer generated from the client_id_.
1476 // It plus salt is going to give us our pseudorandom number.
1477 int idnumber = 0;
1478 const char* client_id_c_str = client_id_.c_str();
1479
1480 // Here we hash the relevant digits of the client_id_
1481 // string somehow to get a big integer idnumber (could be negative
1482 // from wraparound)
1483 int big = 1;
[email protected]cac78842008-11-27 01:02:201484 for (size_t j = n - 1; j >= 0; --j) {
1485 idnumber += static_cast<int>(client_id_c_str[j]) * big;
[email protected]d01b8732008-10-16 02:18:071486 big *= 10;
1487 }
1488
1489 // Mod id number by denominator making sure to get a non-negative
1490 // answer.
[email protected]cac78842008-11-27 01:02:201491 idnumber = ((idnumber % denominator) + denominator) % denominator;
[email protected]d01b8732008-10-16 02:18:071492
[email protected]cac78842008-11-27 01:02:201493 // ((idnumber + salt) % denominator) / denominator is in the range [0,1]
[email protected]d01b8732008-10-16 02:18:071494 // if it's less than probability we call that an affirmative coin
1495 // toss.
[email protected]cac78842008-11-27 01:02:201496 return static_cast<double>((idnumber + salt) % denominator) <
1497 probability * denominator;
[email protected]d01b8732008-10-16 02:18:071498}
1499
initial.commit09911bf2008-07-26 23:55:291500void MetricsService::LogWindowChange(NotificationType type,
1501 const NotificationSource& source,
1502 const NotificationDetails& details) {
[email protected]534e54b2008-08-13 15:40:091503 int controller_id = -1;
1504 uintptr_t window_or_tab = source.map_key();
initial.commit09911bf2008-07-26 23:55:291505 MetricsLog::WindowEventType window_type;
1506
1507 // Note: since we stop all logging when a single OTR session is active, it is
1508 // possible that we start getting notifications about a window that we don't
1509 // know about.
[email protected]534e54b2008-08-13 15:40:091510 if (window_map_.find(window_or_tab) == window_map_.end()) {
1511 controller_id = next_window_id_++;
1512 window_map_[window_or_tab] = controller_id;
initial.commit09911bf2008-07-26 23:55:291513 } else {
[email protected]534e54b2008-08-13 15:40:091514 controller_id = window_map_[window_or_tab];
initial.commit09911bf2008-07-26 23:55:291515 }
[email protected]534e54b2008-08-13 15:40:091516 DCHECK(controller_id != -1);
initial.commit09911bf2008-07-26 23:55:291517
[email protected]bfd04a62009-02-01 18:16:561518 switch (type.value) {
1519 case NotificationType::TAB_PARENTED:
1520 case NotificationType::BROWSER_OPENED:
initial.commit09911bf2008-07-26 23:55:291521 window_type = MetricsLog::WINDOW_CREATE;
1522 break;
1523
[email protected]bfd04a62009-02-01 18:16:561524 case NotificationType::TAB_CLOSING:
1525 case NotificationType::BROWSER_CLOSED:
[email protected]534e54b2008-08-13 15:40:091526 window_map_.erase(window_map_.find(window_or_tab));
initial.commit09911bf2008-07-26 23:55:291527 window_type = MetricsLog::WINDOW_DESTROY;
1528 break;
1529
1530 default:
1531 NOTREACHED();
[email protected]68d74f02009-02-13 01:36:501532 return;
initial.commit09911bf2008-07-26 23:55:291533 }
1534
[email protected]534e54b2008-08-13 15:40:091535 // TODO(brettw) we should have some kind of ID for the parent.
1536 current_log_->RecordWindowEvent(window_type, controller_id, 0);
initial.commit09911bf2008-07-26 23:55:291537}
1538
1539void MetricsService::LogLoadComplete(NotificationType type,
1540 const NotificationSource& source,
1541 const NotificationDetails& details) {
1542 if (details == NotificationService::NoDetails())
1543 return;
1544
[email protected]68475e602008-08-22 03:21:151545 // TODO(jar): There is a bug causing this to be called too many times, and
1546 // the log overflows. For now, we won't record these events.
1547 UMA_HISTOGRAM_COUNTS(L"UMA.LogLoadComplete called", 1);
1548 return;
1549
initial.commit09911bf2008-07-26 23:55:291550 const Details<LoadNotificationDetails> load_details(details);
[email protected]534e54b2008-08-13 15:40:091551 int controller_id = window_map_[details.map_key()];
1552 current_log_->RecordLoadEvent(controller_id,
initial.commit09911bf2008-07-26 23:55:291553 load_details->url(),
1554 load_details->origin(),
1555 load_details->session_index(),
1556 load_details->load_time());
1557}
1558
[email protected]e73c01972008-08-13 00:18:241559void MetricsService::IncrementPrefValue(const wchar_t* path) {
1560 PrefService* pref = g_browser_process->local_state();
1561 DCHECK(pref);
1562 int value = pref->GetInteger(path);
1563 pref->SetInteger(path, value + 1);
1564}
1565
initial.commit09911bf2008-07-26 23:55:291566void MetricsService::LogLoadStarted() {
[email protected]e73c01972008-08-13 00:18:241567 IncrementPrefValue(prefs::kStabilityPageLoadCount);
[email protected]0b33f80b2008-12-17 21:34:361568 // We need to save the prefs, as page load count is a critical stat, and it
1569 // might be lost due to a crash :-(.
initial.commit09911bf2008-07-26 23:55:291570}
1571
1572void MetricsService::LogRendererInSandbox(bool on_sandbox_desktop) {
1573 PrefService* prefs = g_browser_process->local_state();
1574 DCHECK(prefs);
[email protected]e73c01972008-08-13 00:18:241575 if (on_sandbox_desktop)
1576 IncrementPrefValue(prefs::kSecurityRendererOnSboxDesktop);
1577 else
1578 IncrementPrefValue(prefs::kSecurityRendererOnDefaultDesktop);
initial.commit09911bf2008-07-26 23:55:291579}
1580
1581void MetricsService::LogRendererCrash() {
[email protected]e73c01972008-08-13 00:18:241582 IncrementPrefValue(prefs::kStabilityRendererCrashCount);
initial.commit09911bf2008-07-26 23:55:291583}
1584
1585void MetricsService::LogRendererHang() {
[email protected]e73c01972008-08-13 00:18:241586 IncrementPrefValue(prefs::kStabilityRendererHangCount);
initial.commit09911bf2008-07-26 23:55:291587}
1588
[email protected]a27a9382009-02-11 23:55:101589void MetricsService::LogChildProcessChange(
1590 NotificationType type,
1591 const NotificationSource& source,
1592 const NotificationDetails& details) {
1593 const std::wstring& child_name =
1594 Details<ChildProcessInfo>(details)->name();
initial.commit09911bf2008-07-26 23:55:291595
[email protected]a27a9382009-02-11 23:55:101596 if (child_process_stats_buffer_.find(child_name) ==
1597 child_process_stats_buffer_.end()) {
1598 child_process_stats_buffer_[child_name] = ChildProcessStats();
initial.commit09911bf2008-07-26 23:55:291599 }
1600
[email protected]a27a9382009-02-11 23:55:101601 ChildProcessStats& stats = child_process_stats_buffer_[child_name];
[email protected]bfd04a62009-02-01 18:16:561602 switch (type.value) {
[email protected]a27a9382009-02-11 23:55:101603 case NotificationType::CHILD_PROCESS_HOST_CONNECTED:
initial.commit09911bf2008-07-26 23:55:291604 stats.process_launches++;
1605 break;
1606
[email protected]a27a9382009-02-11 23:55:101607 case NotificationType::CHILD_INSTANCE_CREATED:
initial.commit09911bf2008-07-26 23:55:291608 stats.instances++;
1609 break;
1610
[email protected]a27a9382009-02-11 23:55:101611 case NotificationType::CHILD_PROCESS_CRASHED:
initial.commit09911bf2008-07-26 23:55:291612 stats.process_crashes++;
1613 break;
1614
1615 default:
[email protected]bfd04a62009-02-01 18:16:561616 NOTREACHED() << "Unexpected notification type " << type.value;
initial.commit09911bf2008-07-26 23:55:291617 return;
1618 }
1619}
1620
1621// Recursively counts the number of bookmarks and folders in node.
[email protected]d8e41ed2008-09-11 15:22:321622static void CountBookmarks(BookmarkNode* node, int* bookmarks, int* folders) {
initial.commit09911bf2008-07-26 23:55:291623 if (node->GetType() == history::StarredEntry::URL)
1624 (*bookmarks)++;
1625 else
1626 (*folders)++;
1627 for (int i = 0; i < node->GetChildCount(); ++i)
1628 CountBookmarks(node->GetChild(i), bookmarks, folders);
1629}
1630
[email protected]d8e41ed2008-09-11 15:22:321631void MetricsService::LogBookmarks(BookmarkNode* node,
initial.commit09911bf2008-07-26 23:55:291632 const wchar_t* num_bookmarks_key,
1633 const wchar_t* num_folders_key) {
1634 DCHECK(node);
1635 int num_bookmarks = 0;
1636 int num_folders = 0;
1637 CountBookmarks(node, &num_bookmarks, &num_folders);
1638 num_folders--; // Don't include the root folder in the count.
1639
1640 PrefService* pref = g_browser_process->local_state();
1641 DCHECK(pref);
1642 pref->SetInteger(num_bookmarks_key, num_bookmarks);
1643 pref->SetInteger(num_folders_key, num_folders);
1644}
1645
[email protected]d8e41ed2008-09-11 15:22:321646void MetricsService::LogBookmarks(BookmarkModel* model) {
initial.commit09911bf2008-07-26 23:55:291647 DCHECK(model);
1648 LogBookmarks(model->GetBookmarkBarNode(),
1649 prefs::kNumBookmarksOnBookmarkBar,
1650 prefs::kNumFoldersOnBookmarkBar);
1651 LogBookmarks(model->other_node(),
1652 prefs::kNumBookmarksInOtherBookmarkFolder,
1653 prefs::kNumFoldersInOtherBookmarkFolder);
1654 ScheduleNextStateSave();
1655}
1656
1657void MetricsService::LogKeywords(const TemplateURLModel* url_model) {
1658 DCHECK(url_model);
1659
1660 PrefService* pref = g_browser_process->local_state();
1661 DCHECK(pref);
1662 pref->SetInteger(prefs::kNumKeywords,
1663 static_cast<int>(url_model->GetTemplateURLs().size()));
1664 ScheduleNextStateSave();
1665}
1666
1667void MetricsService::RecordPluginChanges(PrefService* pref) {
1668 ListValue* plugins = pref->GetMutableList(prefs::kStabilityPluginStats);
1669 DCHECK(plugins);
1670
1671 for (ListValue::iterator value_iter = plugins->begin();
1672 value_iter != plugins->end(); ++value_iter) {
1673 if (!(*value_iter)->IsType(Value::TYPE_DICTIONARY)) {
1674 NOTREACHED();
1675 continue;
1676 }
1677
1678 DictionaryValue* plugin_dict = static_cast<DictionaryValue*>(*value_iter);
[email protected]a27a9382009-02-11 23:55:101679 std::wstring plugin_name;
1680 plugin_dict->GetString(prefs::kStabilityPluginName, &plugin_name);
1681 if (plugin_name.empty()) {
initial.commit09911bf2008-07-26 23:55:291682 NOTREACHED();
1683 continue;
1684 }
1685
[email protected]a27a9382009-02-11 23:55:101686 if (child_process_stats_buffer_.find(plugin_name) ==
1687 child_process_stats_buffer_.end())
initial.commit09911bf2008-07-26 23:55:291688 continue;
1689
[email protected]a27a9382009-02-11 23:55:101690 ChildProcessStats stats = child_process_stats_buffer_[plugin_name];
initial.commit09911bf2008-07-26 23:55:291691 if (stats.process_launches) {
1692 int launches = 0;
1693 plugin_dict->GetInteger(prefs::kStabilityPluginLaunches, &launches);
1694 launches += stats.process_launches;
1695 plugin_dict->SetInteger(prefs::kStabilityPluginLaunches, launches);
1696 }
1697 if (stats.process_crashes) {
1698 int crashes = 0;
1699 plugin_dict->GetInteger(prefs::kStabilityPluginCrashes, &crashes);
1700 crashes += stats.process_crashes;
1701 plugin_dict->SetInteger(prefs::kStabilityPluginCrashes, crashes);
1702 }
1703 if (stats.instances) {
1704 int instances = 0;
1705 plugin_dict->GetInteger(prefs::kStabilityPluginInstances, &instances);
1706 instances += stats.instances;
1707 plugin_dict->SetInteger(prefs::kStabilityPluginInstances, instances);
1708 }
1709
[email protected]a27a9382009-02-11 23:55:101710 child_process_stats_buffer_.erase(plugin_name);
initial.commit09911bf2008-07-26 23:55:291711 }
1712
1713 // Now go through and add dictionaries for plugins that didn't already have
1714 // reports in Local State.
[email protected]a27a9382009-02-11 23:55:101715 for (std::map<std::wstring, ChildProcessStats>::iterator cache_iter =
1716 child_process_stats_buffer_.begin();
1717 cache_iter != child_process_stats_buffer_.end(); ++cache_iter) {
1718 std::wstring plugin_name = cache_iter->first;
1719 ChildProcessStats stats = cache_iter->second;
initial.commit09911bf2008-07-26 23:55:291720 DictionaryValue* plugin_dict = new DictionaryValue;
1721
[email protected]a27a9382009-02-11 23:55:101722 plugin_dict->SetString(prefs::kStabilityPluginName, plugin_name);
initial.commit09911bf2008-07-26 23:55:291723 plugin_dict->SetInteger(prefs::kStabilityPluginLaunches,
1724 stats.process_launches);
1725 plugin_dict->SetInteger(prefs::kStabilityPluginCrashes,
1726 stats.process_crashes);
1727 plugin_dict->SetInteger(prefs::kStabilityPluginInstances,
1728 stats.instances);
1729 plugins->Append(plugin_dict);
1730 }
[email protected]a27a9382009-02-11 23:55:101731 child_process_stats_buffer_.clear();
initial.commit09911bf2008-07-26 23:55:291732}
1733
1734bool MetricsService::CanLogNotification(NotificationType type,
1735 const NotificationSource& source,
1736 const NotificationDetails& details) {
1737 // We simply don't log anything to UMA if there is a single off the record
1738 // session visible. The problem is that we always notify using the orginal
1739 // profile in order to simplify notification processing.
1740 return !BrowserList::IsOffTheRecordSessionActive();
1741}
1742
1743void MetricsService::RecordBooleanPrefValue(const wchar_t* path, bool value) {
1744 DCHECK(IsSingleThreaded());
1745
1746 PrefService* pref = g_browser_process->local_state();
1747 DCHECK(pref);
1748
1749 pref->SetBoolean(path, value);
1750 RecordCurrentState(pref);
1751}
1752
1753void MetricsService::RecordCurrentState(PrefService* pref) {
1754 pref->SetString(prefs::kStabilityLastTimestampSec,
1755 Int64ToWString(Time::Now().ToTimeT()));
1756
1757 RecordPluginChanges(pref);
1758}
1759
1760void MetricsService::RecordCurrentHistograms() {
1761 DCHECK(current_log_);
1762
1763 StatisticsRecorder::Histograms histograms;
1764 StatisticsRecorder::GetHistograms(&histograms);
1765 for (StatisticsRecorder::Histograms::iterator it = histograms.begin();
1766 histograms.end() != it;
[email protected]cac78842008-11-27 01:02:201767 ++it) {
initial.commit09911bf2008-07-26 23:55:291768 if ((*it)->flags() & kUmaTargetedHistogramFlag)
[email protected]0b33f80b2008-12-17 21:34:361769 // TODO(petersont): Only record historgrams if they are not precluded by
1770 // the UMA response data.
[email protected]d01b8732008-10-16 02:18:071771 // Bug http://code.google.com/p/chromium/issues/detail?id=2739.
initial.commit09911bf2008-07-26 23:55:291772 RecordHistogram(**it);
1773 }
1774}
1775
1776void MetricsService::RecordHistogram(const Histogram& histogram) {
1777 // Get up-to-date snapshot of sample stats.
1778 Histogram::SampleSet snapshot;
1779 histogram.SnapshotSample(&snapshot);
1780
1781 const std::string& histogram_name = histogram.histogram_name();
1782
1783 // Find the already sent stats, or create an empty set.
1784 LoggedSampleMap::iterator it = logged_samples_.find(histogram_name);
1785 Histogram::SampleSet* already_logged;
1786 if (logged_samples_.end() == it) {
1787 // Add new entry
1788 already_logged = &logged_samples_[histogram.histogram_name()];
1789 already_logged->Resize(histogram); // Complete initialization.
1790 } else {
1791 already_logged = &(it->second);
1792 // Deduct any stats we've already logged from our snapshot.
1793 snapshot.Subtract(*already_logged);
1794 }
1795
1796 // snapshot now contains only a delta to what we've already_logged.
1797
1798 if (snapshot.TotalCount() > 0) {
1799 current_log_->RecordHistogramDelta(histogram, snapshot);
1800 // Add new data into our running total.
1801 already_logged->Add(snapshot);
1802 }
1803}
1804
1805void MetricsService::AddProfileMetric(Profile* profile,
1806 const std::wstring& key,
1807 int value) {
1808 // Restriction of types is needed for writing values. See
1809 // MetricsLog::WriteProfileMetrics.
1810 DCHECK(profile && !key.empty());
1811 PrefService* prefs = g_browser_process->local_state();
1812 DCHECK(prefs);
1813
1814 // Key is stored in prefs, which interpret '.'s as paths. As such, key
1815 // shouldn't have any '.'s in it.
1816 DCHECK(key.find(L'.') == std::wstring::npos);
1817 // The id is most likely an email address. We shouldn't send it to the server.
1818 const std::wstring id_hash =
1819 UTF8ToWide(MetricsLog::CreateBase64Hash(WideToUTF8(profile->GetID())));
1820 DCHECK(id_hash.find('.') == std::string::npos);
1821
1822 DictionaryValue* prof_prefs = prefs->GetMutableDictionary(
1823 prefs::kProfileMetrics);
1824 DCHECK(prof_prefs);
1825 const std::wstring pref_key = std::wstring(prefs::kProfilePrefix) + id_hash +
1826 L"." + key;
1827 prof_prefs->SetInteger(pref_key.c_str(), value);
1828}
1829
1830static bool IsSingleThreaded() {
[email protected]dc6f4962009-02-13 01:25:501831 static PlatformThreadId thread_id = 0;
initial.commit09911bf2008-07-26 23:55:291832 if (!thread_id)
[email protected]dc6f4962009-02-13 01:25:501833 thread_id = PlatformThread::CurrentId();
1834 return PlatformThread::CurrentId() == thread_id;
initial.commit09911bf2008-07-26 23:55:291835}