blob: bb2ba6242977e4f63d0fbe321cd4fbb28e656daf [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
20// URL-get, and retransmitting (or retaining at process termination) if the
21// 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//
26// 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 chrome
28// 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
31// external server's response to the initial log conceptually tells
32// this MS if it should continue transmitting logs (during this session). The
33// server response can actually be much more detailed, and always includes (at
34// a minimum) how often additional ongoing logs should be sent.
35//
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
43// periods without any (ongoing) log transmissions. Ongoing log typically
44// 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
50// to the UMA server.
51//
52// When the browser shuts down, there will typically be a fragment of an ongoing
53// log that has not yet been transmitted. At shutdown time, that fragment
54// is closed (including snapshotting histograms), and converted to text. Note
55// that memory stats are not gathered during shutdown, as gathering *might* be
56// too time consuming. The textual representation of the fragment of the
57// ongoing log is then stored persistently as a string in the PrefServices, for
58// potential transmission during a future run of the product.
59//
60// There are two slightly abnormal shutdown conditions. There is a
61// "disconnected scenario," and a "really fast startup and shutdown" scenario.
62// In the "never connected" situation, the user has (during the running of the
63// process) never established an internet connection. As a result, attempts to
64// transmit the initial log have failed, and a lot(?) of data has accumulated in
65// the ongoing log (which didn't yet get closed, because there was never even a
66// contemplation of sending it). There is also a kindred "lost connection"
67// situation, where a loss of connection prevented an ongoing log from being
68// transmitted, and a (still open) log was stuck accumulating a lot(?) of data,
69// while the earlier log retried its transmission. In both of these
70// disconnected situations, two logs need to be, and are, persistently stored
71// for future transmission.
72//
73// The other unusual shutdown condition, termed "really fast startup and
74// shutdown," involves the deliberate user termination of the process before
75// the initial log is even formed or transmitted. In that situation, no logging
76// is done, but the historical crash statistics remain (unlogged) for inclusion
77// in a future run's initial log. (i.e., we don't lose crash stats).
78//
79// With the above overview, we can now describe the state machine's various
80// stats, based on the State enum specified in the state_ member. Those states
81// are:
82//
83// INITIALIZED, // Constructor was called.
[email protected]28ab7f92009-01-06 21:39:0484// PLUGIN_LIST_REQUESTED, // Waiting for plugin list to be loaded.
initial.commit09911bf2008-07-26 23:55:2985// PLUGIN_LIST_ARRIVED, // Waiting for timer to send initial log.
86// INITIAL_LOG_READY, // Initial log generated, and waiting for reply.
87// SEND_OLD_INITIAL_LOGS, // Sending unsent logs from previous session.
88// SENDING_OLD_LOGS, // Sending unsent logs from previous session.
89// SENDING_CURRENT_LOGS, // Sending standard current logs as they accrue.
90//
91// In more detail, we have:
92//
93// INITIALIZED, // Constructor was called.
94// The MS has been constructed, but has taken no actions to compose the
95// initial log.
96//
[email protected]28ab7f92009-01-06 21:39:0497// PLUGIN_LIST_REQUESTED, // Waiting for plugin list to be loaded.
initial.commit09911bf2008-07-26 23:55:2998// Typically about 30 seconds after startup, a task is sent to a second thread
99// to get the list of plugins. That task will (when complete) make an async
100// callback (via a Task) to indicate the completion.
101//
102// PLUGIN_LIST_ARRIVED, // Waiting for timer to send initial log.
103// The callback has arrived, and it is now possible for an initial log to be
104// created. This callback typically arrives back less than one second after
105// the task is dispatched.
106//
107// INITIAL_LOG_READY, // Initial log generated, and waiting for reply.
108// This state is entered only after an initial log has been composed, and
109// prepared for transmission. It is also the case that any previously unsent
110// logs have been loaded into instance variables for possible transmission.
111//
112// SEND_OLD_INITIAL_LOGS, // Sending unsent logs from previous session.
113// This state indicates that the initial log for this session has been
114// successfully sent and it is now time to send any "initial logs" that were
115// saved from previous sessions. Most commonly, there are none, but all old
116// logs that were "initial logs" must be sent before this state is exited.
117//
118// SENDING_OLD_LOGS, // Sending unsent logs from previous session.
119// This state indicates that there are no more unsent initial logs, and now any
120// ongoing logs from previous sessions should be transmitted. All such logs
121// will be transmitted before exiting this state, and proceeding with ongoing
122// logs from the current session (see next state).
123//
124// SENDING_CURRENT_LOGS, // Sending standard current logs as they accrue.
[email protected]0b33f80b2008-12-17 21:34:36125// Current logs are being accumulated. Typically every 20 minutes a log is
initial.commit09911bf2008-07-26 23:55:29126// closed and finalized for transmission, at the same time as a new log is
127// started.
128//
129// The progression through the above states is simple, and sequential, in the
130// most common use cases. States proceed from INITIAL to SENDING_CURRENT_LOGS,
131// and remain in the latter until shutdown.
132//
133// The one unusual case is when the user asks that we stop logging. When that
134// happens, any pending (transmission in progress) log is pushed into the list
135// of old unsent logs (the appropriate list, depending on whether it is an
136// initial log, or an ongoing log). An addition, any log that is currently
137// accumulating is also finalized, and pushed into the unsent log list. With
138// those pushed performed, we regress back to the SEND_OLD_INITIAL_LOGS state in
139// case the user enables log recording again during this session. This way
140// anything we have "pushed back" will be sent automatically if/when we progress
141// back to SENDING_CURRENT_LOG state.
142//
143// Also note that whenever the member variables containing unsent logs are
144// modified (i.e., when we send an old log), we mirror the list of logs into
145// the PrefServices. This ensures that IF we crash, we won't start up and
146// retransmit our old logs again.
147//
148// Due to race conditions, it is always possible that a log file could be sent
149// twice. For example, if a log file is sent, but not yet acknowledged by
150// the external server, and the user shuts down, then a copy of the log may be
151// saved for re-transmission. These duplicates could be filtered out server
152// side, but are not expected to be a significantly statistical problem.
153//
154//
155//------------------------------------------------------------------------------
156
157#include <windows.h>
158
159#include "chrome/browser/metrics_service.h"
160
[email protected]690a99c2009-01-06 16:48:45161#include "base/file_path.h"
initial.commit09911bf2008-07-26 23:55:29162#include "base/histogram.h"
163#include "base/path_service.h"
164#include "base/string_util.h"
165#include "base/task.h"
[email protected]d8e41ed2008-09-11 15:22:32166#include "chrome/browser/bookmarks/bookmark_model.h"
initial.commit09911bf2008-07-26 23:55:29167#include "chrome/browser/browser.h"
168#include "chrome/browser/browser_list.h"
169#include "chrome/browser/browser_process.h"
170#include "chrome/browser/load_notification_details.h"
171#include "chrome/browser/memory_details.h"
172#include "chrome/browser/plugin_process_info.h"
173#include "chrome/browser/plugin_service.h"
174#include "chrome/browser/profile.h"
175#include "chrome/browser/render_process_host.h"
[email protected]d54e03a52009-01-16 00:31:04176#include "chrome/browser/search_engines/template_url.h"
177#include "chrome/browser/search_engines/template_url_model.h"
initial.commit09911bf2008-07-26 23:55:29178#include "chrome/common/chrome_paths.h"
[email protected]252873ef2008-08-04 21:59:45179#include "chrome/common/libxml_utils.h"
initial.commit09911bf2008-07-26 23:55:29180#include "chrome/common/pref_names.h"
181#include "chrome/common/pref_service.h"
[email protected]6e93e522008-08-14 19:28:17182#include "chrome/installer/util/google_update_settings.h"
initial.commit09911bf2008-07-26 23:55:29183#include "googleurl/src/gurl.h"
184#include "net/base/load_flags.h"
185#include "third_party/bzip2/bzlib.h"
186
[email protected]e1acf6f2008-10-27 20:43:33187using base::Time;
188using base::TimeDelta;
189
initial.commit09911bf2008-07-26 23:55:29190// Check to see that we're being called on only one thread.
191static bool IsSingleThreaded();
192
193static const char kMetricsURL[] =
194 "https://toolbarqueries.google.com/firefox/metrics/collect";
195
196static const char kMetricsType[] = "application/vnd.mozilla.metrics.bz2";
197
198// The delay, in seconds, after startup before sending the first log message.
[email protected]252873ef2008-08-04 21:59:45199static const int kInitialInterlogDuration = 60; // one minute
200
201// The default maximum number of events in a log uploaded to the UMA server.
[email protected]0b33f80b2008-12-17 21:34:36202static const int kInitialEventLimit = 2400;
[email protected]68475e602008-08-22 03:21:15203
204// If an upload fails, and the transmission was over this byte count, then we
205// will discard the log, and not try to retransmit it. We also don't persist
206// the log to the prefs for transmission during the next chrome session if this
207// limit is exceeded.
208static const int kUploadLogAvoidRetransmitSize = 50000;
initial.commit09911bf2008-07-26 23:55:29209
210// When we have logs from previous Chrome sessions to send, how long should we
211// delay (in seconds) between each log transmission.
212static const int kUnsentLogDelay = 15; // 15 seconds
213
214// Minimum time a log typically exists before sending, in seconds.
215// This number is supplied by the server, but until we parse it out of a server
216// response, we use this duration to specify how long we should wait before
217// sending the next log. If the channel is busy, such as when there is a
218// failure during an attempt to transmit a previous log, then a log may wait
219// (and continue to accrue now log entries) for a much greater period of time.
[email protected]0b33f80b2008-12-17 21:34:36220static const int kMinSecondsPerLog = 20 * 60; // twenty minutes
initial.commit09911bf2008-07-26 23:55:29221
initial.commit09911bf2008-07-26 23:55:29222// When we don't succeed at transmitting a log to a server, we progressively
223// wait longer and longer before sending the next log. This backoff process
224// help reduce load on the server, and makes the amount of backoff vary between
225// clients so that a collision (server overload?) on retransmit is less likely.
226// The following is the constant we use to expand that inter-log duration.
227static const double kBackoff = 1.1;
228// We limit the maximum backoff to be no greater than some multiple of the
229// default kMinSecondsPerLog. The following is that maximum ratio.
230static const int kMaxBackoff = 10;
231
232// Interval, in seconds, between state saves.
233static const int kSaveStateInterval = 5 * 60; // five minutes
234
235// The number of "initial" logs we're willing to save, and hope to send during
236// a future Chrome session. Initial logs contain crash stats, and are pretty
237// small.
238static const size_t kMaxInitialLogsPersisted = 20;
239
240// The number of ongoing logs we're willing to save persistently, and hope to
241// send during a this or future sessions. Note that each log will be pretty
242// large, as presumably the related "initial" log wasn't sent (probably nothing
243// was, as the user was probably off-line). As a result, the log probably kept
244// accumulating while the "initial" log was stalled (pending_), and couldn't be
245// sent. As a result, we don't want to save too many of these mega-logs.
246// A "standard shutdown" will create a small log, including just the data that
247// was not yet been transmitted, and that is normal (to have exactly one
248// ongoing_log_ at startup).
249static const size_t kMaxOngoingLogsPersisted = 4;
250
251
252// Handles asynchronous fetching of memory details.
253// Will run the provided task after finished.
254class MetricsMemoryDetails : public MemoryDetails {
255 public:
256 explicit MetricsMemoryDetails(Task* completion) : completion_(completion) {}
257
258 virtual void OnDetailsAvailable() {
259 MessageLoop::current()->PostTask(FROM_HERE, completion_);
260 }
261
262 private:
263 Task* completion_;
264 DISALLOW_EVIL_CONSTRUCTORS(MetricsMemoryDetails);
265};
266
267class MetricsService::GetPluginListTaskComplete : public Task {
268 virtual void Run() {
269 g_browser_process->metrics_service()->OnGetPluginListTaskComplete();
270 }
271};
272
273class MetricsService::GetPluginListTask : public Task {
274 public:
275 explicit GetPluginListTask(MessageLoop* callback_loop)
276 : callback_loop_(callback_loop) {}
277
278 virtual void Run() {
279 std::vector<WebPluginInfo> plugins;
280 PluginService::GetInstance()->GetPlugins(false, &plugins);
281
282 callback_loop_->PostTask(FROM_HERE, new GetPluginListTaskComplete());
283 }
284
285 private:
286 MessageLoop* callback_loop_;
287};
288
289// static
290void MetricsService::RegisterPrefs(PrefService* local_state) {
291 DCHECK(IsSingleThreaded());
292 local_state->RegisterStringPref(prefs::kMetricsClientID, L"");
293 local_state->RegisterStringPref(prefs::kMetricsClientIDTimestamp, L"0");
294 local_state->RegisterStringPref(prefs::kStabilityLaunchTimeSec, L"0");
295 local_state->RegisterStringPref(prefs::kStabilityLastTimestampSec, L"0");
296 local_state->RegisterStringPref(prefs::kStabilityUptimeSec, L"0");
297 local_state->RegisterBooleanPref(prefs::kStabilityExitedCleanly, true);
298 local_state->RegisterBooleanPref(prefs::kStabilitySessionEndCompleted, true);
299 local_state->RegisterIntegerPref(prefs::kMetricsSessionID, -1);
300 local_state->RegisterIntegerPref(prefs::kStabilityLaunchCount, 0);
301 local_state->RegisterIntegerPref(prefs::kStabilityCrashCount, 0);
302 local_state->RegisterIntegerPref(prefs::kStabilityIncompleteSessionEndCount,
303 0);
304 local_state->RegisterIntegerPref(prefs::kStabilityPageLoadCount, 0);
305 local_state->RegisterIntegerPref(prefs::kSecurityRendererOnSboxDesktop, 0);
306 local_state->RegisterIntegerPref(prefs::kSecurityRendererOnDefaultDesktop, 0);
307 local_state->RegisterIntegerPref(prefs::kStabilityRendererCrashCount, 0);
308 local_state->RegisterIntegerPref(prefs::kStabilityRendererHangCount, 0);
[email protected]e73c01972008-08-13 00:18:24309 local_state->RegisterIntegerPref(prefs::kStabilityBreakpadRegistrationFail,
310 0);
311 local_state->RegisterIntegerPref(prefs::kStabilityBreakpadRegistrationSuccess,
312 0);
313 local_state->RegisterIntegerPref(prefs::kStabilityDebuggerPresent, 0);
314 local_state->RegisterIntegerPref(prefs::kStabilityDebuggerNotPresent, 0);
315
initial.commit09911bf2008-07-26 23:55:29316 local_state->RegisterDictionaryPref(prefs::kProfileMetrics);
317 local_state->RegisterIntegerPref(prefs::kNumBookmarksOnBookmarkBar, 0);
318 local_state->RegisterIntegerPref(prefs::kNumFoldersOnBookmarkBar, 0);
319 local_state->RegisterIntegerPref(prefs::kNumBookmarksInOtherBookmarkFolder,
320 0);
321 local_state->RegisterIntegerPref(prefs::kNumFoldersInOtherBookmarkFolder, 0);
322 local_state->RegisterIntegerPref(prefs::kNumKeywords, 0);
323 local_state->RegisterListPref(prefs::kMetricsInitialLogs);
324 local_state->RegisterListPref(prefs::kMetricsOngoingLogs);
325}
326
327MetricsService::MetricsService()
[email protected]d01b8732008-10-16 02:18:07328 : recording_active_(false),
329 reporting_active_(false),
330 user_permits_upload_(false),
331 server_permits_upload_(true),
332 state_(INITIALIZED),
initial.commit09911bf2008-07-26 23:55:29333 pending_log_(NULL),
334 pending_log_text_(""),
335 current_fetch_(NULL),
336 current_log_(NULL),
[email protected]d01b8732008-10-16 02:18:07337 idle_since_last_transmission_(false),
initial.commit09911bf2008-07-26 23:55:29338 next_window_id_(0),
339 log_sender_factory_(this),
340 state_saver_factory_(this),
341 logged_samples_(),
[email protected]252873ef2008-08-04 21:59:45342 interlog_duration_(TimeDelta::FromSeconds(kInitialInterlogDuration)),
[email protected]d01b8732008-10-16 02:18:07343 log_event_limit_(kInitialEventLimit),
initial.commit09911bf2008-07-26 23:55:29344 timer_pending_(false) {
345 DCHECK(IsSingleThreaded());
346 InitializeMetricsState();
347}
348
349MetricsService::~MetricsService() {
350 SetRecording(false);
351}
352
[email protected]d01b8732008-10-16 02:18:07353void MetricsService::SetUserPermitsUpload(bool enabled) {
354 HandleIdleSinceLastTransmission(false);
355 user_permits_upload_ = enabled;
356}
357
358void MetricsService::Start() {
359 SetRecording(true);
360 SetReporting(true);
361}
362
363void MetricsService::StartRecordingOnly() {
364 SetRecording(true);
365 SetReporting(false);
366}
367
368void MetricsService::Stop() {
369 SetReporting(false);
370 SetRecording(false);
371}
372
initial.commit09911bf2008-07-26 23:55:29373void MetricsService::SetRecording(bool enabled) {
374 DCHECK(IsSingleThreaded());
375
[email protected]d01b8732008-10-16 02:18:07376 if (enabled == recording_active_)
initial.commit09911bf2008-07-26 23:55:29377 return;
378
379 if (enabled) {
380 StartRecording();
381 ListenerRegistration(true);
382 } else {
383 // Turn off all observers.
384 ListenerRegistration(false);
385 PushPendingLogsToUnsentLists();
386 DCHECK(!pending_log());
387 if (state_ > INITIAL_LOG_READY && unsent_logs())
388 state_ = SEND_OLD_INITIAL_LOGS;
389 }
[email protected]d01b8732008-10-16 02:18:07390 recording_active_ = enabled;
initial.commit09911bf2008-07-26 23:55:29391}
392
[email protected]d01b8732008-10-16 02:18:07393bool MetricsService::recording_active() const {
initial.commit09911bf2008-07-26 23:55:29394 DCHECK(IsSingleThreaded());
[email protected]d01b8732008-10-16 02:18:07395 return recording_active_;
initial.commit09911bf2008-07-26 23:55:29396}
397
[email protected]d01b8732008-10-16 02:18:07398void MetricsService::SetReporting(bool enable) {
399 if (reporting_active_ != enable) {
400 reporting_active_ = enable;
401 if (reporting_active_)
initial.commit09911bf2008-07-26 23:55:29402 StartLogTransmissionTimer();
403 }
[email protected]d01b8732008-10-16 02:18:07404}
405
406bool MetricsService::reporting_active() const {
407 DCHECK(IsSingleThreaded());
408 return reporting_active_;
initial.commit09911bf2008-07-26 23:55:29409}
410
411void MetricsService::Observe(NotificationType type,
412 const NotificationSource& source,
413 const NotificationDetails& details) {
414 DCHECK(current_log_);
415 DCHECK(IsSingleThreaded());
416
417 if (!CanLogNotification(type, source, details))
418 return;
419
420 switch (type) {
421 case NOTIFY_USER_ACTION:
422 current_log_->RecordUserAction(*Details<const wchar_t*>(details).ptr());
423 break;
424
425 case NOTIFY_BROWSER_OPENED:
426 case NOTIFY_BROWSER_CLOSED:
427 LogWindowChange(type, source, details);
428 break;
429
[email protected]534e54b2008-08-13 15:40:09430 case NOTIFY_TAB_PARENTED:
initial.commit09911bf2008-07-26 23:55:29431 case NOTIFY_TAB_CLOSING:
432 LogWindowChange(type, source, details);
433 break;
434
435 case NOTIFY_LOAD_STOP:
436 LogLoadComplete(type, source, details);
437 break;
438
439 case NOTIFY_LOAD_START:
440 LogLoadStarted();
441 break;
442
443 case NOTIFY_RENDERER_PROCESS_TERMINATED:
444 if (!*Details<bool>(details).ptr())
445 LogRendererCrash();
446 break;
447
448 case NOTIFY_RENDERER_PROCESS_HANG:
449 LogRendererHang();
450 break;
451
452 case NOTIFY_RENDERER_PROCESS_IN_SBOX:
453 LogRendererInSandbox(*Details<bool>(details).ptr());
454 break;
455
456 case NOTIFY_PLUGIN_PROCESS_HOST_CONNECTED:
457 case NOTIFY_PLUGIN_PROCESS_CRASHED:
458 case NOTIFY_PLUGIN_INSTANCE_CREATED:
459 LogPluginChange(type, source, details);
460 break;
461
462 case TEMPLATE_URL_MODEL_LOADED:
463 LogKeywords(Source<TemplateURLModel>(source).ptr());
464 break;
465
466 case NOTIFY_OMNIBOX_OPENED_URL:
467 current_log_->RecordOmniboxOpenedURL(
468 *Details<AutocompleteLog>(details).ptr());
469 break;
470
471 case NOTIFY_BOOKMARK_MODEL_LOADED:
[email protected]d8e41ed2008-09-11 15:22:32472 LogBookmarks(Source<Profile>(source)->GetBookmarkModel());
initial.commit09911bf2008-07-26 23:55:29473 break;
474
475 default:
476 NOTREACHED();
477 break;
478 }
[email protected]d01b8732008-10-16 02:18:07479
480 HandleIdleSinceLastTransmission(false);
481
482 if (current_log_)
483 DLOG(INFO) << "METRICS: NUMBER OF LOGS = " << current_log_->num_events();
484}
485
486void MetricsService::HandleIdleSinceLastTransmission(bool in_idle) {
487 // If there wasn't a lot of action, maybe the computer was asleep, in which
488 // case, the log transmissions should have stopped. Here we start them up
489 // again.
[email protected]cac78842008-11-27 01:02:20490 if (!in_idle && idle_since_last_transmission_)
491 StartLogTransmissionTimer();
492 idle_since_last_transmission_ = in_idle;
initial.commit09911bf2008-07-26 23:55:29493}
494
495void MetricsService::RecordCleanShutdown() {
496 RecordBooleanPrefValue(prefs::kStabilityExitedCleanly, true);
497}
498
499void MetricsService::RecordStartOfSessionEnd() {
500 RecordBooleanPrefValue(prefs::kStabilitySessionEndCompleted, false);
501}
502
503void MetricsService::RecordCompletedSessionEnd() {
504 RecordBooleanPrefValue(prefs::kStabilitySessionEndCompleted, true);
505}
506
[email protected]e73c01972008-08-13 00:18:24507void MetricsService:: RecordBreakpadRegistration(bool success) {
[email protected]68475e602008-08-22 03:21:15508 if (!success)
[email protected]e73c01972008-08-13 00:18:24509 IncrementPrefValue(prefs::kStabilityBreakpadRegistrationFail);
510 else
511 IncrementPrefValue(prefs::kStabilityBreakpadRegistrationSuccess);
512}
513
514void MetricsService::RecordBreakpadHasDebugger(bool has_debugger) {
515 if (!has_debugger)
516 IncrementPrefValue(prefs::kStabilityDebuggerNotPresent);
517 else
[email protected]68475e602008-08-22 03:21:15518 IncrementPrefValue(prefs::kStabilityDebuggerPresent);
[email protected]e73c01972008-08-13 00:18:24519}
520
initial.commit09911bf2008-07-26 23:55:29521//------------------------------------------------------------------------------
522// private methods
523//------------------------------------------------------------------------------
524
525
526//------------------------------------------------------------------------------
527// Initialization methods
528
529void MetricsService::InitializeMetricsState() {
530 PrefService* pref = g_browser_process->local_state();
531 DCHECK(pref);
532
533 client_id_ = WideToUTF8(pref->GetString(prefs::kMetricsClientID));
534 if (client_id_.empty()) {
535 client_id_ = GenerateClientID();
536 pref->SetString(prefs::kMetricsClientID, UTF8ToWide(client_id_));
537
538 // Might as well make a note of how long this ID has existed
539 pref->SetString(prefs::kMetricsClientIDTimestamp,
540 Int64ToWString(Time::Now().ToTimeT()));
541 }
542
543 // Update session ID
544 session_id_ = pref->GetInteger(prefs::kMetricsSessionID);
545 ++session_id_;
546 pref->SetInteger(prefs::kMetricsSessionID, session_id_);
547
initial.commit09911bf2008-07-26 23:55:29548 // Stability bookkeeping
[email protected]e73c01972008-08-13 00:18:24549 IncrementPrefValue(prefs::kStabilityLaunchCount);
initial.commit09911bf2008-07-26 23:55:29550
[email protected]e73c01972008-08-13 00:18:24551 if (!pref->GetBoolean(prefs::kStabilityExitedCleanly)) {
552 IncrementPrefValue(prefs::kStabilityCrashCount);
initial.commit09911bf2008-07-26 23:55:29553 }
[email protected]e73c01972008-08-13 00:18:24554
555 // This will be set to 'true' if we exit cleanly.
initial.commit09911bf2008-07-26 23:55:29556 pref->SetBoolean(prefs::kStabilityExitedCleanly, false);
557
[email protected]e73c01972008-08-13 00:18:24558 if (!pref->GetBoolean(prefs::kStabilitySessionEndCompleted)) {
559 IncrementPrefValue(prefs::kStabilityIncompleteSessionEndCount);
initial.commit09911bf2008-07-26 23:55:29560 }
561 // This is marked false when we get a WM_ENDSESSION.
562 pref->SetBoolean(prefs::kStabilitySessionEndCompleted, true);
563
564 int64 last_start_time =
565 StringToInt64(pref->GetString(prefs::kStabilityLaunchTimeSec));
566 int64 last_end_time =
567 StringToInt64(pref->GetString(prefs::kStabilityLastTimestampSec));
568 int64 uptime =
569 StringToInt64(pref->GetString(prefs::kStabilityUptimeSec));
570
571 if (last_start_time && last_end_time) {
572 // TODO(JAR): Exclude sleep time. ... which must be gathered in UI loop.
573 uptime += last_end_time - last_start_time;
574 pref->SetString(prefs::kStabilityUptimeSec, Int64ToWString(uptime));
575 }
576 pref->SetString(prefs::kStabilityLaunchTimeSec,
577 Int64ToWString(Time::Now().ToTimeT()));
578
579 // Save profile metrics.
580 PrefService* prefs = g_browser_process->local_state();
581 if (prefs) {
582 // Remove the current dictionary and store it for use when sending data to
583 // server. By removing the value we prune potentially dead profiles
584 // (and keys). All valid values are added back once services startup.
585 const DictionaryValue* profile_dictionary =
586 prefs->GetDictionary(prefs::kProfileMetrics);
587 if (profile_dictionary) {
588 // Do a deep copy of profile_dictionary since ClearPref will delete it.
589 profile_dictionary_.reset(static_cast<DictionaryValue*>(
590 profile_dictionary->DeepCopy()));
591 prefs->ClearPref(prefs::kProfileMetrics);
592 }
593 }
594
595 // Kick off the process of saving the state (so the uptime numbers keep
596 // getting updated) every n minutes.
597 ScheduleNextStateSave();
598}
599
600void MetricsService::OnGetPluginListTaskComplete() {
601 DCHECK(state_ == PLUGIN_LIST_REQUESTED);
602 if (state_ == PLUGIN_LIST_REQUESTED)
603 state_ = PLUGIN_LIST_ARRIVED;
604}
605
606std::string MetricsService::GenerateClientID() {
607 const int kGUIDSize = 39;
608
609 GUID guid;
610 HRESULT guid_result = CoCreateGuid(&guid);
611 DCHECK(SUCCEEDED(guid_result));
612
613 std::wstring guid_string;
614 int result = StringFromGUID2(guid,
615 WriteInto(&guid_string, kGUIDSize), kGUIDSize);
616 DCHECK(result == kGUIDSize);
617
618 return WideToUTF8(guid_string.substr(1, guid_string.length() - 2));
619}
620
621
622//------------------------------------------------------------------------------
623// State save methods
624
625void MetricsService::ScheduleNextStateSave() {
626 state_saver_factory_.RevokeAll();
627
628 MessageLoop::current()->PostDelayedTask(FROM_HERE,
629 state_saver_factory_.NewRunnableMethod(&MetricsService::SaveLocalState),
630 kSaveStateInterval * 1000);
631}
632
633void MetricsService::SaveLocalState() {
634 PrefService* pref = g_browser_process->local_state();
635 if (!pref) {
636 NOTREACHED();
637 return;
638 }
639
640 RecordCurrentState(pref);
641 pref->ScheduleSavePersistentPrefs(g_browser_process->file_thread());
642
643 ScheduleNextStateSave();
644}
645
646
647//------------------------------------------------------------------------------
648// Recording control methods
649
650void MetricsService::StartRecording() {
651 if (current_log_)
652 return;
653
654 current_log_ = new MetricsLog(client_id_, session_id_);
655 if (state_ == INITIALIZED) {
656 // We only need to schedule that run once.
657 state_ = PLUGIN_LIST_REQUESTED;
658
659 // Make sure the plugin list is loaded before the inital log is sent, so
660 // that the main thread isn't blocked generating the list.
661 g_browser_process->file_thread()->message_loop()->PostDelayedTask(FROM_HERE,
662 new GetPluginListTask(MessageLoop::current()),
[email protected]252873ef2008-08-04 21:59:45663 kInitialInterlogDuration * 1000 / 2);
initial.commit09911bf2008-07-26 23:55:29664 }
665}
666
667void MetricsService::StopRecording(MetricsLog** log) {
668 if (!current_log_)
669 return;
670
[email protected]68475e602008-08-22 03:21:15671 // TODO(jar): Integrate bounds on log recording more consistently, so that we
672 // can stop recording logs that are too big much sooner.
[email protected]d01b8732008-10-16 02:18:07673 if (current_log_->num_events() > log_event_limit_) {
[email protected]68475e602008-08-22 03:21:15674 UMA_HISTOGRAM_COUNTS(L"UMA.Discarded Log Events",
675 current_log_->num_events());
676 current_log_->CloseLog();
677 delete current_log_;
[email protected]294638782008-09-24 00:22:41678 current_log_ = NULL;
[email protected]68475e602008-08-22 03:21:15679 StartRecording(); // Start trivial log to hold our histograms.
680 }
681
[email protected]0b33f80b2008-12-17 21:34:36682 // Put incremental data (histogram deltas, and realtime stats deltas) at the
[email protected]147bbc0b2009-01-06 19:37:40683 // end of all log transmissions (initial log handles this separately).
initial.commit09911bf2008-07-26 23:55:29684 // Don't bother if we're going to discard current_log_.
[email protected]0b33f80b2008-12-17 21:34:36685 if (log) {
686 current_log_->RecordIncrementalStabilityElements();
initial.commit09911bf2008-07-26 23:55:29687 RecordCurrentHistograms();
[email protected]0b33f80b2008-12-17 21:34:36688 }
initial.commit09911bf2008-07-26 23:55:29689
690 current_log_->CloseLog();
[email protected]cac78842008-11-27 01:02:20691 if (log)
initial.commit09911bf2008-07-26 23:55:29692 *log = current_log_;
[email protected]cac78842008-11-27 01:02:20693 else
initial.commit09911bf2008-07-26 23:55:29694 delete current_log_;
initial.commit09911bf2008-07-26 23:55:29695 current_log_ = NULL;
696}
697
698void MetricsService::ListenerRegistration(bool start_listening) {
699 AddOrRemoveObserver(this, NOTIFY_BROWSER_OPENED, start_listening);
700 AddOrRemoveObserver(this, NOTIFY_BROWSER_CLOSED, start_listening);
701 AddOrRemoveObserver(this, NOTIFY_USER_ACTION, start_listening);
[email protected]534e54b2008-08-13 15:40:09702 AddOrRemoveObserver(this, NOTIFY_TAB_PARENTED, start_listening);
initial.commit09911bf2008-07-26 23:55:29703 AddOrRemoveObserver(this, NOTIFY_TAB_CLOSING, start_listening);
704 AddOrRemoveObserver(this, NOTIFY_LOAD_START, start_listening);
705 AddOrRemoveObserver(this, NOTIFY_LOAD_STOP, start_listening);
706 AddOrRemoveObserver(this, NOTIFY_RENDERER_PROCESS_IN_SBOX, start_listening);
707 AddOrRemoveObserver(this, NOTIFY_RENDERER_PROCESS_TERMINATED,
708 start_listening);
709 AddOrRemoveObserver(this, NOTIFY_RENDERER_PROCESS_HANG, start_listening);
710 AddOrRemoveObserver(this, NOTIFY_PLUGIN_PROCESS_HOST_CONNECTED,
711 start_listening);
712 AddOrRemoveObserver(this, NOTIFY_PLUGIN_INSTANCE_CREATED, start_listening);
713 AddOrRemoveObserver(this, NOTIFY_PLUGIN_PROCESS_CRASHED, start_listening);
714 AddOrRemoveObserver(this, TEMPLATE_URL_MODEL_LOADED, start_listening);
715 AddOrRemoveObserver(this, NOTIFY_OMNIBOX_OPENED_URL, start_listening);
716 AddOrRemoveObserver(this, NOTIFY_BOOKMARK_MODEL_LOADED, start_listening);
717}
718
719// static
720void MetricsService::AddOrRemoveObserver(NotificationObserver* observer,
[email protected]cac78842008-11-27 01:02:20721 NotificationType type,
722 bool is_add) {
initial.commit09911bf2008-07-26 23:55:29723 NotificationService* service = NotificationService::current();
724
[email protected]cac78842008-11-27 01:02:20725 if (is_add)
initial.commit09911bf2008-07-26 23:55:29726 service->AddObserver(observer, type, NotificationService::AllSources());
[email protected]cac78842008-11-27 01:02:20727 else
initial.commit09911bf2008-07-26 23:55:29728 service->RemoveObserver(observer, type, NotificationService::AllSources());
initial.commit09911bf2008-07-26 23:55:29729}
730
731void MetricsService::PushPendingLogsToUnsentLists() {
732 if (state_ < INITIAL_LOG_READY)
[email protected]28ab7f92009-01-06 21:39:04733 return; // We didn't and still don't have time to get plugin list etc.
initial.commit09911bf2008-07-26 23:55:29734
735 if (pending_log()) {
736 PreparePendingLogText();
737 if (state_ == INITIAL_LOG_READY) {
738 // We may race here, and send second copy of initial log later.
739 unsent_initial_logs_.push_back(pending_log_text_);
[email protected]d01b8732008-10-16 02:18:07740 state_ = SEND_OLD_INITIAL_LOGS;
initial.commit09911bf2008-07-26 23:55:29741 } else {
[email protected]68475e602008-08-22 03:21:15742 PushPendingLogTextToUnsentOngoingLogs();
initial.commit09911bf2008-07-26 23:55:29743 }
744 DiscardPendingLog();
745 }
746 DCHECK(!pending_log());
747 StopRecording(&pending_log_);
748 PreparePendingLogText();
[email protected]68475e602008-08-22 03:21:15749 PushPendingLogTextToUnsentOngoingLogs();
initial.commit09911bf2008-07-26 23:55:29750 DiscardPendingLog();
751 StoreUnsentLogs();
752}
753
[email protected]68475e602008-08-22 03:21:15754void MetricsService::PushPendingLogTextToUnsentOngoingLogs() {
[email protected]d01b8732008-10-16 02:18:07755 // If UMA response told us not to upload, there's no need to save the pending
756 // log. It wasn't supposed to be uploaded anyway.
757 if (!server_permits_upload_)
758 return;
759
[email protected]68475e602008-08-22 03:21:15760 if (pending_log_text_.length() > kUploadLogAvoidRetransmitSize) {
761 UMA_HISTOGRAM_COUNTS(L"UMA.Large Accumulated Log Not Persisted",
762 static_cast<int>(pending_log_text_.length()));
763 return;
764 }
765 unsent_ongoing_logs_.push_back(pending_log_text_);
766}
767
initial.commit09911bf2008-07-26 23:55:29768//------------------------------------------------------------------------------
769// Transmission of logs methods
770
771void MetricsService::StartLogTransmissionTimer() {
[email protected]d01b8732008-10-16 02:18:07772 // If we're not reporting, there's no point in starting a log transmission
773 // timer.
774 if (!reporting_active())
775 return;
776
initial.commit09911bf2008-07-26 23:55:29777 if (!current_log_)
778 return; // Recorder is shutdown.
[email protected]d01b8732008-10-16 02:18:07779
780 // If there is already a timer running, we leave it running.
781 // If timer_pending is true because the fetch is waiting for a response,
782 // we return for now and let the response handler start the timer.
783 if (timer_pending_)
initial.commit09911bf2008-07-26 23:55:29784 return;
[email protected]d01b8732008-10-16 02:18:07785
[email protected]d01b8732008-10-16 02:18:07786 // Before starting the timer, set timer_pending_ to true.
initial.commit09911bf2008-07-26 23:55:29787 timer_pending_ = true;
[email protected]d01b8732008-10-16 02:18:07788
789 // Right before the UMA transmission gets started, there's one more thing we'd
790 // like to record: the histogram of memory usage, so we spawn a task to
791 // collect the memory details and when that task is finished, we arrange for
792 // TryToStartTransmission to take over.
initial.commit09911bf2008-07-26 23:55:29793 MessageLoop::current()->PostDelayedTask(FROM_HERE,
794 log_sender_factory_.
795 NewRunnableMethod(&MetricsService::CollectMemoryDetails),
796 static_cast<int>(interlog_duration_.InMilliseconds()));
797}
798
799void MetricsService::TryToStartTransmission() {
800 DCHECK(IsSingleThreaded());
801
[email protected]d01b8732008-10-16 02:18:07802 // This function should only be called via timer, so timer_pending_
803 // should be true.
804 DCHECK(timer_pending_);
805 timer_pending_ = false;
initial.commit09911bf2008-07-26 23:55:29806
807 DCHECK(!current_fetch_.get());
initial.commit09911bf2008-07-26 23:55:29808
[email protected]d01b8732008-10-16 02:18:07809 // If we're getting no notifications, then the log won't have much in it, and
810 // it's possible the computer is about to go to sleep, so don't upload and
811 // don't restart the transmission timer.
812 if (idle_since_last_transmission_)
813 return;
814
815 // If somehow there is a fetch in progress, we return setting timer_pending_
816 // to true and hope things work out.
817 if (current_fetch_.get()) {
818 timer_pending_ = true;
819 return;
820 }
821
822 // If uploads are forbidden by UMA response, there's no point in keeping
823 // the current_log_, and the more often we delete it, the less likely it is
824 // to expand forever.
825 if (!server_permits_upload_ && current_log_) {
826 StopRecording(NULL);
827 StartRecording();
828 }
initial.commit09911bf2008-07-26 23:55:29829
830 if (!current_log_)
831 return; // Logging was disabled.
[email protected]d01b8732008-10-16 02:18:07832 if (!reporting_active())
initial.commit09911bf2008-07-26 23:55:29833 return; // Don't do work if we're not going to send anything now.
834
[email protected]d01b8732008-10-16 02:18:07835 MakePendingLog();
initial.commit09911bf2008-07-26 23:55:29836
[email protected]d01b8732008-10-16 02:18:07837 // MakePendingLog should have put something in the pending log, if it didn't,
838 // we start the timer again, return and hope things work out.
839 if (!pending_log()) {
840 StartLogTransmissionTimer();
841 return;
842 }
initial.commit09911bf2008-07-26 23:55:29843
[email protected]d01b8732008-10-16 02:18:07844 // If we're not supposed to upload any UMA data because the response or the
845 // user said so, cancel the upload at this point, but start the timer.
846 if (!TransmissionPermitted()) {
847 DiscardPendingLog();
848 StartLogTransmissionTimer();
849 return;
850 }
initial.commit09911bf2008-07-26 23:55:29851
[email protected]d01b8732008-10-16 02:18:07852 PrepareFetchWithPendingLog();
853
854 if (!current_fetch_.get()) {
855 // Compression failed, and log discarded :-/.
856 DiscardPendingLog();
857 StartLogTransmissionTimer(); // Maybe we'll do better next time
858 // TODO(jar): If compression failed, we should have created a tiny log and
859 // compressed that, so that we can signal that we're losing logs.
860 return;
861 }
862
863 DCHECK(!timer_pending_);
864
865 // The URL fetch is a like timer in that after a while we get called back
866 // so we set timer_pending_ true just as we start the url fetch.
867 timer_pending_ = true;
868 current_fetch_->Start();
869
870 HandleIdleSinceLastTransmission(true);
871}
872
873
874void MetricsService::MakePendingLog() {
875 if (pending_log())
876 return;
877
878 switch (state_) {
879 case INITIALIZED:
880 case PLUGIN_LIST_REQUESTED: // We should be further along by now.
881 DCHECK(false);
882 return;
883
884 case PLUGIN_LIST_ARRIVED:
885 // We need to wait for the initial log to be ready before sending
886 // anything, because the server will tell us whether it wants to hear
887 // from us.
888 PrepareInitialLog();
889 DCHECK(state_ == PLUGIN_LIST_ARRIVED);
890 RecallUnsentLogs();
891 state_ = INITIAL_LOG_READY;
892 break;
893
894 case SEND_OLD_INITIAL_LOGS:
[email protected]cac78842008-11-27 01:02:20895 if (!unsent_initial_logs_.empty()) {
896 pending_log_text_ = unsent_initial_logs_.back();
897 break;
898 }
[email protected]d01b8732008-10-16 02:18:07899 state_ = SENDING_OLD_LOGS;
900 // Fall through.
initial.commit09911bf2008-07-26 23:55:29901
[email protected]d01b8732008-10-16 02:18:07902 case SENDING_OLD_LOGS:
903 if (!unsent_ongoing_logs_.empty()) {
904 pending_log_text_ = unsent_ongoing_logs_.back();
905 break;
906 }
907 state_ = SENDING_CURRENT_LOGS;
908 // Fall through.
909
910 case SENDING_CURRENT_LOGS:
911 StopRecording(&pending_log_);
912 StartRecording();
913 break;
914
915 default:
916 DCHECK(false);
917 return;
918 }
919
920 DCHECK(pending_log());
921}
922
923bool MetricsService::TransmissionPermitted() const {
924 // If the user forbids uploading that's they're business, and we don't upload
925 // anything. If the server forbids uploading, that's our business, so we take
926 // that to mean it forbids current logs, but we still send up the inital logs
927 // and any old logs.
[email protected]d01b8732008-10-16 02:18:07928 if (!user_permits_upload_)
929 return false;
[email protected]cac78842008-11-27 01:02:20930 if (server_permits_upload_)
[email protected]d01b8732008-10-16 02:18:07931 return true;
initial.commit09911bf2008-07-26 23:55:29932
[email protected]cac78842008-11-27 01:02:20933 switch (state_) {
934 case INITIAL_LOG_READY:
935 case SEND_OLD_INITIAL_LOGS:
936 case SENDING_OLD_LOGS:
937 return true;
938
939 case SENDING_CURRENT_LOGS:
940 default:
941 return false;
[email protected]8c8824b2008-09-20 01:55:50942 }
initial.commit09911bf2008-07-26 23:55:29943}
944
945void MetricsService::CollectMemoryDetails() {
946 Task* task = log_sender_factory_.
947 NewRunnableMethod(&MetricsService::TryToStartTransmission);
948 MetricsMemoryDetails* details = new MetricsMemoryDetails(task);
949 details->StartFetch();
950
951 // Collect WebCore cache information to put into a histogram.
952 for (RenderProcessHost::iterator it = RenderProcessHost::begin();
953 it != RenderProcessHost::end(); ++it) {
954 it->second->Send(new ViewMsg_GetCacheResourceStats());
955 }
956}
957
958void MetricsService::PrepareInitialLog() {
959 DCHECK(state_ == PLUGIN_LIST_ARRIVED);
960 std::vector<WebPluginInfo> plugins;
961 PluginService::GetInstance()->GetPlugins(false, &plugins);
962
963 MetricsLog* log = new MetricsLog(client_id_, session_id_);
964 log->RecordEnvironment(plugins, profile_dictionary_.get());
965
966 // Histograms only get written to current_log_, so setup for the write.
967 MetricsLog* save_log = current_log_;
968 current_log_ = log;
969 RecordCurrentHistograms(); // Into current_log_... which is really log.
970 current_log_ = save_log;
971
972 log->CloseLog();
973 DCHECK(!pending_log());
974 pending_log_ = log;
975}
976
977void MetricsService::RecallUnsentLogs() {
978 DCHECK(unsent_initial_logs_.empty());
979 DCHECK(unsent_ongoing_logs_.empty());
980
981 PrefService* local_state = g_browser_process->local_state();
982 DCHECK(local_state);
983
984 ListValue* unsent_initial_logs = local_state->GetMutableList(
985 prefs::kMetricsInitialLogs);
986 for (ListValue::iterator it = unsent_initial_logs->begin();
987 it != unsent_initial_logs->end(); ++it) {
[email protected]5e324b72008-12-18 00:07:59988 std::string log;
989 (*it)->GetAsString(&log);
990 unsent_initial_logs_.push_back(log);
initial.commit09911bf2008-07-26 23:55:29991 }
992
993 ListValue* unsent_ongoing_logs = local_state->GetMutableList(
994 prefs::kMetricsOngoingLogs);
995 for (ListValue::iterator it = unsent_ongoing_logs->begin();
996 it != unsent_ongoing_logs->end(); ++it) {
[email protected]5e324b72008-12-18 00:07:59997 std::string log;
998 (*it)->GetAsString(&log);
999 unsent_ongoing_logs_.push_back(log);
initial.commit09911bf2008-07-26 23:55:291000 }
1001}
1002
1003void MetricsService::StoreUnsentLogs() {
1004 if (state_ < INITIAL_LOG_READY)
1005 return; // We never Recalled the prior unsent logs.
1006
1007 PrefService* local_state = g_browser_process->local_state();
1008 DCHECK(local_state);
1009
1010 ListValue* unsent_initial_logs = local_state->GetMutableList(
1011 prefs::kMetricsInitialLogs);
1012 unsent_initial_logs->Clear();
1013 size_t start = 0;
1014 if (unsent_initial_logs_.size() > kMaxInitialLogsPersisted)
1015 start = unsent_initial_logs_.size() - kMaxInitialLogsPersisted;
1016 for (size_t i = start; i < unsent_initial_logs_.size(); ++i)
1017 unsent_initial_logs->Append(
[email protected]5e324b72008-12-18 00:07:591018 Value::CreateStringValue(unsent_initial_logs_[i]));
initial.commit09911bf2008-07-26 23:55:291019
1020 ListValue* unsent_ongoing_logs = local_state->GetMutableList(
1021 prefs::kMetricsOngoingLogs);
1022 unsent_ongoing_logs->Clear();
1023 start = 0;
1024 if (unsent_ongoing_logs_.size() > kMaxOngoingLogsPersisted)
1025 start = unsent_ongoing_logs_.size() - kMaxOngoingLogsPersisted;
1026 for (size_t i = start; i < unsent_ongoing_logs_.size(); ++i)
1027 unsent_ongoing_logs->Append(
[email protected]5e324b72008-12-18 00:07:591028 Value::CreateStringValue(unsent_ongoing_logs_[i]));
initial.commit09911bf2008-07-26 23:55:291029}
1030
1031void MetricsService::PreparePendingLogText() {
1032 DCHECK(pending_log());
1033 if (!pending_log_text_.empty())
1034 return;
1035 int original_size = pending_log_->GetEncodedLogSize();
1036 pending_log_->GetEncodedLog(WriteInto(&pending_log_text_, original_size),
1037 original_size);
1038}
1039
[email protected]d01b8732008-10-16 02:18:071040void MetricsService::PrepareFetchWithPendingLog() {
initial.commit09911bf2008-07-26 23:55:291041 DCHECK(pending_log());
1042 DCHECK(!current_fetch_.get());
1043 PreparePendingLogText();
1044 DCHECK(!pending_log_text_.empty());
1045
1046 // Allow security conscious users to see all metrics logs that we send.
1047 LOG(INFO) << "METRICS LOG: " << pending_log_text_;
1048
1049 std::string compressed_log;
[email protected]cac78842008-11-27 01:02:201050 if (!Bzip2Compress(pending_log_text_, &compressed_log)) {
initial.commit09911bf2008-07-26 23:55:291051 NOTREACHED() << "Failed to compress log for transmission.";
1052 DiscardPendingLog();
1053 StartLogTransmissionTimer(); // Maybe we'll do better on next log :-/.
1054 return;
1055 }
[email protected]cac78842008-11-27 01:02:201056
initial.commit09911bf2008-07-26 23:55:291057 current_fetch_.reset(new URLFetcher(GURL(kMetricsURL), URLFetcher::POST,
1058 this));
1059 current_fetch_->set_request_context(Profile::GetDefaultRequestContext());
1060 current_fetch_->set_upload_data(kMetricsType, compressed_log);
1061 // This flag works around the cert mismatch on toolbarqueries.google.com.
1062 current_fetch_->set_load_flags(net::LOAD_IGNORE_CERT_COMMON_NAME_INVALID);
1063}
1064
1065void MetricsService::DiscardPendingLog() {
1066 if (pending_log_) { // Shutdown might have deleted it!
1067 delete pending_log_;
1068 pending_log_ = NULL;
1069 }
1070 pending_log_text_.clear();
1071}
1072
1073// This implementation is based on the Firefox MetricsService implementation.
1074bool MetricsService::Bzip2Compress(const std::string& input,
1075 std::string* output) {
1076 bz_stream stream = {0};
1077 // As long as our input is smaller than the bzip2 block size, we should get
1078 // the best compression. For example, if your input was 250k, using a block
1079 // size of 300k or 500k should result in the same compression ratio. Since
1080 // our data should be under 100k, using the minimum block size of 100k should
1081 // allocate less temporary memory, but result in the same compression ratio.
1082 int result = BZ2_bzCompressInit(&stream,
1083 1, // 100k (min) block size
1084 0, // quiet
1085 0); // default "work factor"
1086 if (result != BZ_OK) { // out of memory?
1087 return false;
1088 }
1089
1090 output->clear();
1091
1092 stream.next_in = const_cast<char*>(input.data());
1093 stream.avail_in = static_cast<int>(input.size());
1094 // NOTE: we don't need a BZ_RUN phase since our input buffer contains
1095 // the entire input
1096 do {
1097 output->resize(output->size() + 1024);
1098 stream.next_out = &((*output)[stream.total_out_lo32]);
1099 stream.avail_out = static_cast<int>(output->size()) - stream.total_out_lo32;
1100 result = BZ2_bzCompress(&stream, BZ_FINISH);
1101 } while (result == BZ_FINISH_OK);
1102 if (result != BZ_STREAM_END) // unknown failure?
1103 return false;
1104 result = BZ2_bzCompressEnd(&stream);
1105 DCHECK(result == BZ_OK);
1106
1107 output->resize(stream.total_out_lo32);
1108
1109 return true;
1110}
1111
1112static const char* StatusToString(const URLRequestStatus& status) {
1113 switch (status.status()) {
1114 case URLRequestStatus::SUCCESS:
1115 return "SUCCESS";
1116
1117 case URLRequestStatus::IO_PENDING:
1118 return "IO_PENDING";
1119
1120 case URLRequestStatus::HANDLED_EXTERNALLY:
1121 return "HANDLED_EXTERNALLY";
1122
1123 case URLRequestStatus::CANCELED:
1124 return "CANCELED";
1125
1126 case URLRequestStatus::FAILED:
1127 return "FAILED";
1128
1129 default:
1130 NOTREACHED();
1131 return "Unknown";
1132 }
1133}
1134
1135void MetricsService::OnURLFetchComplete(const URLFetcher* source,
1136 const GURL& url,
1137 const URLRequestStatus& status,
1138 int response_code,
1139 const ResponseCookies& cookies,
1140 const std::string& data) {
1141 DCHECK(timer_pending_);
1142 timer_pending_ = false;
1143 DCHECK(current_fetch_.get());
1144 current_fetch_.reset(NULL); // We're not allowed to re-use it.
1145
1146 // Confirm send so that we can move on.
[email protected]cac78842008-11-27 01:02:201147 DLOG(INFO) << "METRICS RESPONSE CODE: " << response_code << " status=" <<
1148 StatusToString(status);
[email protected]252873ef2008-08-04 21:59:451149
[email protected]68475e602008-08-22 03:21:151150 // TODO(petersont): Refactor or remove the following so that we don't have to
1151 // fake a valid response code.
1152 if (response_code != 200 &&
1153 pending_log_text_.length() > kUploadLogAvoidRetransmitSize) {
1154 UMA_HISTOGRAM_COUNTS(L"UMA.Large Rejected Log was Discarded",
1155 static_cast<int>(pending_log_text_.length()));
1156 response_code = 200; // Simulate transmission so we will discard log.
1157 }
1158
[email protected]252873ef2008-08-04 21:59:451159 if (response_code != 200) {
1160 HandleBadResponseCode();
1161 } else { // Success.
[email protected]d01b8732008-10-16 02:18:071162 DLOG(INFO) << "METRICS RESPONSE DATA: " << data;
initial.commit09911bf2008-07-26 23:55:291163 switch (state_) {
1164 case INITIAL_LOG_READY:
1165 state_ = SEND_OLD_INITIAL_LOGS;
1166 break;
1167
1168 case SEND_OLD_INITIAL_LOGS:
1169 DCHECK(!unsent_initial_logs_.empty());
1170 unsent_initial_logs_.pop_back();
1171 StoreUnsentLogs();
1172 break;
1173
1174 case SENDING_OLD_LOGS:
1175 DCHECK(!unsent_ongoing_logs_.empty());
1176 unsent_ongoing_logs_.pop_back();
1177 StoreUnsentLogs();
1178 break;
1179
1180 case SENDING_CURRENT_LOGS:
1181 break;
1182
1183 default:
1184 DCHECK(false);
1185 break;
1186 }
[email protected]d01b8732008-10-16 02:18:071187
initial.commit09911bf2008-07-26 23:55:291188 DiscardPendingLog();
[email protected]29be92552008-08-07 22:49:271189 // Since we sent a log, make sure our in-memory state is recorded to disk.
1190 PrefService* local_state = g_browser_process->local_state();
1191 DCHECK(local_state);
1192 if (local_state)
1193 local_state->ScheduleSavePersistentPrefs(
1194 g_browser_process->file_thread());
[email protected]252873ef2008-08-04 21:59:451195
[email protected]147bbc0b2009-01-06 19:37:401196 // Provide a default (free of exponetial backoff, other varances) in case
1197 // the server does not specify a value.
1198 interlog_duration_ = TimeDelta::FromSeconds(kMinSecondsPerLog);
1199
[email protected]252873ef2008-08-04 21:59:451200 GetSettingsFromResponseData(data);
[email protected]252873ef2008-08-04 21:59:451201 // Override server specified interlog delay if there are unsent logs to
[email protected]29be92552008-08-07 22:49:271202 // transmit.
initial.commit09911bf2008-07-26 23:55:291203 if (unsent_logs()) {
1204 DCHECK(state_ < SENDING_CURRENT_LOGS);
1205 interlog_duration_ = TimeDelta::FromSeconds(kUnsentLogDelay);
initial.commit09911bf2008-07-26 23:55:291206 }
1207 }
[email protected]252873ef2008-08-04 21:59:451208
initial.commit09911bf2008-07-26 23:55:291209 StartLogTransmissionTimer();
1210}
1211
[email protected]252873ef2008-08-04 21:59:451212void MetricsService::HandleBadResponseCode() {
1213 DLOG(INFO) << "METRICS: transmission attempt returned a failure code. "
1214 "Verify network connectivity";
1215#ifndef NDEBUG
[email protected]cac78842008-11-27 01:02:201216 DLOG(INFO) << "Verify your metrics logs are formatted correctly. "
1217 "Verify server is active at " << kMetricsURL;
[email protected]252873ef2008-08-04 21:59:451218#endif
1219 if (!pending_log()) {
1220 DLOG(INFO) << "METRICS: Recorder shutdown during log transmission.";
1221 } else {
1222 // Send progressively less frequently.
1223 DCHECK(kBackoff > 1.0);
1224 interlog_duration_ = TimeDelta::FromMicroseconds(
1225 static_cast<int64>(kBackoff * interlog_duration_.InMicroseconds()));
1226
1227 if (kMaxBackoff * TimeDelta::FromSeconds(kMinSecondsPerLog) <
[email protected]cac78842008-11-27 01:02:201228 interlog_duration_) {
[email protected]252873ef2008-08-04 21:59:451229 interlog_duration_ = kMaxBackoff *
1230 TimeDelta::FromSeconds(kMinSecondsPerLog);
[email protected]cac78842008-11-27 01:02:201231 }
[email protected]252873ef2008-08-04 21:59:451232
1233 DLOG(INFO) << "METRICS: transmission retry being scheduled in " <<
1234 interlog_duration_.InSeconds() << " seconds for " <<
1235 pending_log_text_;
initial.commit09911bf2008-07-26 23:55:291236 }
initial.commit09911bf2008-07-26 23:55:291237}
1238
[email protected]252873ef2008-08-04 21:59:451239void MetricsService::GetSettingsFromResponseData(const std::string& data) {
1240 // We assume that the file is structured as a block opened by <response>
[email protected]d01b8732008-10-16 02:18:071241 // and that inside response, there is a block opened by tag <chrome_config>
1242 // other tags are ignored for now except the content of <chrome_config>.
1243 DLOG(INFO) << "METRICS: getting settings from response data: " << data;
1244
[email protected]252873ef2008-08-04 21:59:451245 int data_size = static_cast<int>(data.size());
1246 if (data_size < 0) {
[email protected]cac78842008-11-27 01:02:201247 DLOG(INFO) << "METRICS: server response data bad size: " << data_size <<
1248 "; aborting extraction of settings";
[email protected]252873ef2008-08-04 21:59:451249 return;
1250 }
[email protected]cac78842008-11-27 01:02:201251 xmlDocPtr doc = xmlReadMemory(data.c_str(), data_size, "", NULL, 0);
[email protected]252873ef2008-08-04 21:59:451252 DCHECK(doc);
[email protected]d01b8732008-10-16 02:18:071253 // If the document is malformed, we just use the settings that were there.
1254 if (!doc) {
1255 DLOG(INFO) << "METRICS: reading xml from server response data failed";
[email protected]252873ef2008-08-04 21:59:451256 return;
[email protected]d01b8732008-10-16 02:18:071257 }
[email protected]252873ef2008-08-04 21:59:451258
[email protected]d01b8732008-10-16 02:18:071259 xmlNodePtr top_node = xmlDocGetRootElement(doc), chrome_config_node = NULL;
1260 // Here, we find the chrome_config node by name.
[email protected]252873ef2008-08-04 21:59:451261 for (xmlNodePtr p = top_node->children; p; p = p->next) {
[email protected]d01b8732008-10-16 02:18:071262 if (xmlStrEqual(p->name, BAD_CAST "chrome_config")) {
1263 chrome_config_node = p;
[email protected]252873ef2008-08-04 21:59:451264 break;
1265 }
1266 }
1267 // If the server data is formatted wrong and there is no
1268 // config node where we expect, we just drop out.
[email protected]d01b8732008-10-16 02:18:071269 if (chrome_config_node != NULL)
1270 GetSettingsFromChromeConfigNode(chrome_config_node);
[email protected]252873ef2008-08-04 21:59:451271 xmlFreeDoc(doc);
1272}
1273
[email protected]d01b8732008-10-16 02:18:071274void MetricsService::GetSettingsFromChromeConfigNode(
1275 xmlNodePtr chrome_config_node) {
1276 // Iterate through all children of the config node.
1277 for (xmlNodePtr current_node = chrome_config_node->children;
1278 current_node;
1279 current_node = current_node->next) {
1280 // If we find the upload tag, we appeal to another function
1281 // GetSettingsFromUploadNode to read all the data in it.
[email protected]252873ef2008-08-04 21:59:451282 if (xmlStrEqual(current_node->name, BAD_CAST "upload")) {
[email protected]d01b8732008-10-16 02:18:071283 GetSettingsFromUploadNode(current_node);
[email protected]252873ef2008-08-04 21:59:451284 continue;
1285 }
1286 }
1287}
initial.commit09911bf2008-07-26 23:55:291288
[email protected]d01b8732008-10-16 02:18:071289void MetricsService::InheritedProperties::OverwriteWhereNeeded(
1290 xmlNodePtr node) {
1291 xmlChar* salt_value = xmlGetProp(node, BAD_CAST "salt");
1292 if (salt_value) // If the property isn't there, xmlGetProp returns NULL.
1293 salt = atoi(reinterpret_cast<char*>(salt_value));
1294 // If the property isn't there, we keep the value the property had before
1295
1296 xmlChar* denominator_value = xmlGetProp(node, BAD_CAST "denominator");
1297 if (denominator_value)
1298 denominator = atoi(reinterpret_cast<char*>(denominator_value));
1299}
1300
1301void MetricsService::GetSettingsFromUploadNode(xmlNodePtr upload_node) {
1302 InheritedProperties props;
1303 GetSettingsFromUploadNodeRecursive(upload_node, props, "", true);
1304}
1305
[email protected]cac78842008-11-27 01:02:201306void MetricsService::GetSettingsFromUploadNodeRecursive(
1307 xmlNodePtr node,
1308 InheritedProperties props,
1309 std::string path_prefix,
1310 bool uploadOn) {
[email protected]d01b8732008-10-16 02:18:071311 props.OverwriteWhereNeeded(node);
1312
1313 // The bool uploadOn is set to true if the data represented by current
1314 // node should be uploaded. This gets inherited in the tree; the children
1315 // of a node that has already been rejected for upload get rejected for
1316 // upload.
1317 uploadOn = uploadOn && NodeProbabilityTest(node, props);
1318
1319 // The path is a / separated list of the node names ancestral to the current
1320 // one. So, if you want to check if the current node has a certain name,
1321 // compare to name. If you want to check if it is a certan tag at a certain
1322 // place in the tree, compare to the whole path.
1323 std::string name = std::string(reinterpret_cast<const char*>(node->name));
1324 std::string path = path_prefix + "/" + name;
1325
1326 if (path == "/upload") {
1327 xmlChar* upload_interval_val = xmlGetProp(node, BAD_CAST "interval");
1328 if (upload_interval_val) {
1329 interlog_duration_ = TimeDelta::FromSeconds(
1330 atoi(reinterpret_cast<char*>(upload_interval_val)));
1331 }
1332
1333 server_permits_upload_ = uploadOn;
1334 }
1335 if (path == "/upload/logs") {
1336 xmlChar* log_event_limit_val = xmlGetProp(node, BAD_CAST "event_limit");
1337 if (log_event_limit_val)
1338 log_event_limit_ = atoi(reinterpret_cast<char*>(log_event_limit_val));
1339 }
1340 if (name == "histogram") {
1341 xmlChar* type_value = xmlGetProp(node, BAD_CAST "type");
1342 if (type_value) {
1343 std::string type = (reinterpret_cast<char*>(type_value));
1344 if (uploadOn)
1345 histograms_to_upload_.insert(type);
1346 else
1347 histograms_to_omit_.insert(type);
1348 }
1349 }
1350 if (name == "log") {
1351 xmlChar* type_value = xmlGetProp(node, BAD_CAST "type");
1352 if (type_value) {
1353 std::string type = (reinterpret_cast<char*>(type_value));
1354 if (uploadOn)
1355 logs_to_upload_.insert(type);
1356 else
1357 logs_to_omit_.insert(type);
1358 }
1359 }
1360
1361 // Recursive call. If the node is a leaf i.e. if it ends in a "/>", then it
1362 // doesn't have children, so node->children is NULL, and this loop doesn't
1363 // call (that's how the recursion ends).
1364 for (xmlNodePtr child_node = node->children;
[email protected]cac78842008-11-27 01:02:201365 child_node;
1366 child_node = child_node->next) {
[email protected]d01b8732008-10-16 02:18:071367 GetSettingsFromUploadNodeRecursive(child_node, props, path, uploadOn);
1368 }
1369}
1370
1371bool MetricsService::NodeProbabilityTest(xmlNodePtr node,
[email protected]cac78842008-11-27 01:02:201372 InheritedProperties props) const {
[email protected]d01b8732008-10-16 02:18:071373 // Default value of probability on any node is 1, but recall that
1374 // its parents can already have been rejected for upload.
1375 double probability = 1;
1376
1377 // If a probability is specified in the node, we use it instead.
1378 xmlChar* probability_value = xmlGetProp(node, BAD_CAST "probability");
1379 if (probability_value)
[email protected]0b33f80b2008-12-17 21:34:361380 probability = atoi(reinterpret_cast<char*>(probability_value));
[email protected]d01b8732008-10-16 02:18:071381
1382 return ProbabilityTest(probability, props.salt, props.denominator);
1383}
1384
1385bool MetricsService::ProbabilityTest(double probability,
1386 int salt,
1387 int denominator) const {
1388 // Okay, first we figure out how many of the digits of the
1389 // client_id_ we need in order to make a nice pseudorandomish
1390 // number in the range [0,denominator). Too many digits is
1391 // fine.
[email protected]cac78842008-11-27 01:02:201392 int relevant_digits =
1393 static_cast<int>(log10(static_cast<double>(denominator)) + 1.0);
[email protected]d01b8732008-10-16 02:18:071394
1395 // n is the length of the client_id_ string
1396 size_t n = client_id_.size();
1397
1398 // idnumber is a positive integer generated from the client_id_.
1399 // It plus salt is going to give us our pseudorandom number.
1400 int idnumber = 0;
1401 const char* client_id_c_str = client_id_.c_str();
1402
1403 // Here we hash the relevant digits of the client_id_
1404 // string somehow to get a big integer idnumber (could be negative
1405 // from wraparound)
1406 int big = 1;
[email protected]cac78842008-11-27 01:02:201407 for (size_t j = n - 1; j >= 0; --j) {
1408 idnumber += static_cast<int>(client_id_c_str[j]) * big;
[email protected]d01b8732008-10-16 02:18:071409 big *= 10;
1410 }
1411
1412 // Mod id number by denominator making sure to get a non-negative
1413 // answer.
[email protected]cac78842008-11-27 01:02:201414 idnumber = ((idnumber % denominator) + denominator) % denominator;
[email protected]d01b8732008-10-16 02:18:071415
[email protected]cac78842008-11-27 01:02:201416 // ((idnumber + salt) % denominator) / denominator is in the range [0,1]
[email protected]d01b8732008-10-16 02:18:071417 // if it's less than probability we call that an affirmative coin
1418 // toss.
[email protected]cac78842008-11-27 01:02:201419 return static_cast<double>((idnumber + salt) % denominator) <
1420 probability * denominator;
[email protected]d01b8732008-10-16 02:18:071421}
1422
initial.commit09911bf2008-07-26 23:55:291423void MetricsService::LogWindowChange(NotificationType type,
1424 const NotificationSource& source,
1425 const NotificationDetails& details) {
[email protected]534e54b2008-08-13 15:40:091426 int controller_id = -1;
1427 uintptr_t window_or_tab = source.map_key();
initial.commit09911bf2008-07-26 23:55:291428 MetricsLog::WindowEventType window_type;
1429
1430 // Note: since we stop all logging when a single OTR session is active, it is
1431 // possible that we start getting notifications about a window that we don't
1432 // know about.
[email protected]534e54b2008-08-13 15:40:091433 if (window_map_.find(window_or_tab) == window_map_.end()) {
1434 controller_id = next_window_id_++;
1435 window_map_[window_or_tab] = controller_id;
initial.commit09911bf2008-07-26 23:55:291436 } else {
[email protected]534e54b2008-08-13 15:40:091437 controller_id = window_map_[window_or_tab];
initial.commit09911bf2008-07-26 23:55:291438 }
[email protected]534e54b2008-08-13 15:40:091439 DCHECK(controller_id != -1);
initial.commit09911bf2008-07-26 23:55:291440
1441 switch (type) {
[email protected]534e54b2008-08-13 15:40:091442 case NOTIFY_TAB_PARENTED:
initial.commit09911bf2008-07-26 23:55:291443 case NOTIFY_BROWSER_OPENED:
1444 window_type = MetricsLog::WINDOW_CREATE;
1445 break;
1446
1447 case NOTIFY_TAB_CLOSING:
1448 case NOTIFY_BROWSER_CLOSED:
[email protected]534e54b2008-08-13 15:40:091449 window_map_.erase(window_map_.find(window_or_tab));
initial.commit09911bf2008-07-26 23:55:291450 window_type = MetricsLog::WINDOW_DESTROY;
1451 break;
1452
1453 default:
1454 NOTREACHED();
1455 break;
1456 }
1457
[email protected]534e54b2008-08-13 15:40:091458 // TODO(brettw) we should have some kind of ID for the parent.
1459 current_log_->RecordWindowEvent(window_type, controller_id, 0);
initial.commit09911bf2008-07-26 23:55:291460}
1461
1462void MetricsService::LogLoadComplete(NotificationType type,
1463 const NotificationSource& source,
1464 const NotificationDetails& details) {
1465 if (details == NotificationService::NoDetails())
1466 return;
1467
[email protected]68475e602008-08-22 03:21:151468 // TODO(jar): There is a bug causing this to be called too many times, and
1469 // the log overflows. For now, we won't record these events.
1470 UMA_HISTOGRAM_COUNTS(L"UMA.LogLoadComplete called", 1);
1471 return;
1472
initial.commit09911bf2008-07-26 23:55:291473 const Details<LoadNotificationDetails> load_details(details);
[email protected]534e54b2008-08-13 15:40:091474 int controller_id = window_map_[details.map_key()];
1475 current_log_->RecordLoadEvent(controller_id,
initial.commit09911bf2008-07-26 23:55:291476 load_details->url(),
1477 load_details->origin(),
1478 load_details->session_index(),
1479 load_details->load_time());
1480}
1481
[email protected]e73c01972008-08-13 00:18:241482void MetricsService::IncrementPrefValue(const wchar_t* path) {
1483 PrefService* pref = g_browser_process->local_state();
1484 DCHECK(pref);
1485 int value = pref->GetInteger(path);
1486 pref->SetInteger(path, value + 1);
1487}
1488
initial.commit09911bf2008-07-26 23:55:291489void MetricsService::LogLoadStarted() {
[email protected]e73c01972008-08-13 00:18:241490 IncrementPrefValue(prefs::kStabilityPageLoadCount);
[email protected]0b33f80b2008-12-17 21:34:361491 // We need to save the prefs, as page load count is a critical stat, and it
1492 // might be lost due to a crash :-(.
initial.commit09911bf2008-07-26 23:55:291493}
1494
1495void MetricsService::LogRendererInSandbox(bool on_sandbox_desktop) {
1496 PrefService* prefs = g_browser_process->local_state();
1497 DCHECK(prefs);
[email protected]e73c01972008-08-13 00:18:241498 if (on_sandbox_desktop)
1499 IncrementPrefValue(prefs::kSecurityRendererOnSboxDesktop);
1500 else
1501 IncrementPrefValue(prefs::kSecurityRendererOnDefaultDesktop);
initial.commit09911bf2008-07-26 23:55:291502}
1503
1504void MetricsService::LogRendererCrash() {
[email protected]e73c01972008-08-13 00:18:241505 IncrementPrefValue(prefs::kStabilityRendererCrashCount);
initial.commit09911bf2008-07-26 23:55:291506}
1507
1508void MetricsService::LogRendererHang() {
[email protected]e73c01972008-08-13 00:18:241509 IncrementPrefValue(prefs::kStabilityRendererHangCount);
initial.commit09911bf2008-07-26 23:55:291510}
1511
1512void MetricsService::LogPluginChange(NotificationType type,
1513 const NotificationSource& source,
1514 const NotificationDetails& details) {
[email protected]690a99c2009-01-06 16:48:451515 FilePath plugin = Details<PluginProcessInfo>(details)->plugin_path();
initial.commit09911bf2008-07-26 23:55:291516
1517 if (plugin_stats_buffer_.find(plugin) == plugin_stats_buffer_.end()) {
1518 plugin_stats_buffer_[plugin] = PluginStats();
1519 }
1520
1521 PluginStats& stats = plugin_stats_buffer_[plugin];
1522 switch (type) {
1523 case NOTIFY_PLUGIN_PROCESS_HOST_CONNECTED:
1524 stats.process_launches++;
1525 break;
1526
1527 case NOTIFY_PLUGIN_INSTANCE_CREATED:
1528 stats.instances++;
1529 break;
1530
1531 case NOTIFY_PLUGIN_PROCESS_CRASHED:
1532 stats.process_crashes++;
1533 break;
1534
1535 default:
1536 NOTREACHED() << "Unexpected notification type " << type;
1537 return;
1538 }
1539}
1540
1541// Recursively counts the number of bookmarks and folders in node.
[email protected]d8e41ed2008-09-11 15:22:321542static void CountBookmarks(BookmarkNode* node, int* bookmarks, int* folders) {
initial.commit09911bf2008-07-26 23:55:291543 if (node->GetType() == history::StarredEntry::URL)
1544 (*bookmarks)++;
1545 else
1546 (*folders)++;
1547 for (int i = 0; i < node->GetChildCount(); ++i)
1548 CountBookmarks(node->GetChild(i), bookmarks, folders);
1549}
1550
[email protected]d8e41ed2008-09-11 15:22:321551void MetricsService::LogBookmarks(BookmarkNode* node,
initial.commit09911bf2008-07-26 23:55:291552 const wchar_t* num_bookmarks_key,
1553 const wchar_t* num_folders_key) {
1554 DCHECK(node);
1555 int num_bookmarks = 0;
1556 int num_folders = 0;
1557 CountBookmarks(node, &num_bookmarks, &num_folders);
1558 num_folders--; // Don't include the root folder in the count.
1559
1560 PrefService* pref = g_browser_process->local_state();
1561 DCHECK(pref);
1562 pref->SetInteger(num_bookmarks_key, num_bookmarks);
1563 pref->SetInteger(num_folders_key, num_folders);
1564}
1565
[email protected]d8e41ed2008-09-11 15:22:321566void MetricsService::LogBookmarks(BookmarkModel* model) {
initial.commit09911bf2008-07-26 23:55:291567 DCHECK(model);
1568 LogBookmarks(model->GetBookmarkBarNode(),
1569 prefs::kNumBookmarksOnBookmarkBar,
1570 prefs::kNumFoldersOnBookmarkBar);
1571 LogBookmarks(model->other_node(),
1572 prefs::kNumBookmarksInOtherBookmarkFolder,
1573 prefs::kNumFoldersInOtherBookmarkFolder);
1574 ScheduleNextStateSave();
1575}
1576
1577void MetricsService::LogKeywords(const TemplateURLModel* url_model) {
1578 DCHECK(url_model);
1579
1580 PrefService* pref = g_browser_process->local_state();
1581 DCHECK(pref);
1582 pref->SetInteger(prefs::kNumKeywords,
1583 static_cast<int>(url_model->GetTemplateURLs().size()));
1584 ScheduleNextStateSave();
1585}
1586
1587void MetricsService::RecordPluginChanges(PrefService* pref) {
1588 ListValue* plugins = pref->GetMutableList(prefs::kStabilityPluginStats);
1589 DCHECK(plugins);
1590
1591 for (ListValue::iterator value_iter = plugins->begin();
1592 value_iter != plugins->end(); ++value_iter) {
1593 if (!(*value_iter)->IsType(Value::TYPE_DICTIONARY)) {
1594 NOTREACHED();
1595 continue;
1596 }
1597
1598 DictionaryValue* plugin_dict = static_cast<DictionaryValue*>(*value_iter);
[email protected]690a99c2009-01-06 16:48:451599 FilePath::StringType plugin_path_str;
1600 plugin_dict->GetString(prefs::kStabilityPluginPath, &plugin_path_str);
1601 if (plugin_path_str.empty()) {
initial.commit09911bf2008-07-26 23:55:291602 NOTREACHED();
1603 continue;
1604 }
1605
[email protected]690a99c2009-01-06 16:48:451606 FilePath plugin_path(plugin_path_str);
initial.commit09911bf2008-07-26 23:55:291607 if (plugin_stats_buffer_.find(plugin_path) == plugin_stats_buffer_.end())
1608 continue;
1609
1610 PluginStats stats = plugin_stats_buffer_[plugin_path];
1611 if (stats.process_launches) {
1612 int launches = 0;
1613 plugin_dict->GetInteger(prefs::kStabilityPluginLaunches, &launches);
1614 launches += stats.process_launches;
1615 plugin_dict->SetInteger(prefs::kStabilityPluginLaunches, launches);
1616 }
1617 if (stats.process_crashes) {
1618 int crashes = 0;
1619 plugin_dict->GetInteger(prefs::kStabilityPluginCrashes, &crashes);
1620 crashes += stats.process_crashes;
1621 plugin_dict->SetInteger(prefs::kStabilityPluginCrashes, crashes);
1622 }
1623 if (stats.instances) {
1624 int instances = 0;
1625 plugin_dict->GetInteger(prefs::kStabilityPluginInstances, &instances);
1626 instances += stats.instances;
1627 plugin_dict->SetInteger(prefs::kStabilityPluginInstances, instances);
1628 }
1629
1630 plugin_stats_buffer_.erase(plugin_path);
1631 }
1632
1633 // Now go through and add dictionaries for plugins that didn't already have
1634 // reports in Local State.
[email protected]690a99c2009-01-06 16:48:451635 for (std::map<FilePath, PluginStats>::iterator cache_iter =
initial.commit09911bf2008-07-26 23:55:291636 plugin_stats_buffer_.begin();
1637 cache_iter != plugin_stats_buffer_.end(); ++cache_iter) {
[email protected]690a99c2009-01-06 16:48:451638 FilePath plugin_path = cache_iter->first;
initial.commit09911bf2008-07-26 23:55:291639 PluginStats stats = cache_iter->second;
1640 DictionaryValue* plugin_dict = new DictionaryValue;
1641
[email protected]690a99c2009-01-06 16:48:451642 plugin_dict->SetString(prefs::kStabilityPluginPath, plugin_path.value());
initial.commit09911bf2008-07-26 23:55:291643 plugin_dict->SetInteger(prefs::kStabilityPluginLaunches,
1644 stats.process_launches);
1645 plugin_dict->SetInteger(prefs::kStabilityPluginCrashes,
1646 stats.process_crashes);
1647 plugin_dict->SetInteger(prefs::kStabilityPluginInstances,
1648 stats.instances);
1649 plugins->Append(plugin_dict);
1650 }
1651 plugin_stats_buffer_.clear();
1652}
1653
1654bool MetricsService::CanLogNotification(NotificationType type,
1655 const NotificationSource& source,
1656 const NotificationDetails& details) {
1657 // We simply don't log anything to UMA if there is a single off the record
1658 // session visible. The problem is that we always notify using the orginal
1659 // profile in order to simplify notification processing.
1660 return !BrowserList::IsOffTheRecordSessionActive();
1661}
1662
1663void MetricsService::RecordBooleanPrefValue(const wchar_t* path, bool value) {
1664 DCHECK(IsSingleThreaded());
1665
1666 PrefService* pref = g_browser_process->local_state();
1667 DCHECK(pref);
1668
1669 pref->SetBoolean(path, value);
1670 RecordCurrentState(pref);
1671}
1672
1673void MetricsService::RecordCurrentState(PrefService* pref) {
1674 pref->SetString(prefs::kStabilityLastTimestampSec,
1675 Int64ToWString(Time::Now().ToTimeT()));
1676
1677 RecordPluginChanges(pref);
1678}
1679
1680void MetricsService::RecordCurrentHistograms() {
1681 DCHECK(current_log_);
1682
1683 StatisticsRecorder::Histograms histograms;
1684 StatisticsRecorder::GetHistograms(&histograms);
1685 for (StatisticsRecorder::Histograms::iterator it = histograms.begin();
1686 histograms.end() != it;
[email protected]cac78842008-11-27 01:02:201687 ++it) {
initial.commit09911bf2008-07-26 23:55:291688 if ((*it)->flags() & kUmaTargetedHistogramFlag)
[email protected]0b33f80b2008-12-17 21:34:361689 // TODO(petersont): Only record historgrams if they are not precluded by
1690 // the UMA response data.
[email protected]d01b8732008-10-16 02:18:071691 // Bug http://code.google.com/p/chromium/issues/detail?id=2739.
initial.commit09911bf2008-07-26 23:55:291692 RecordHistogram(**it);
1693 }
1694}
1695
1696void MetricsService::RecordHistogram(const Histogram& histogram) {
1697 // Get up-to-date snapshot of sample stats.
1698 Histogram::SampleSet snapshot;
1699 histogram.SnapshotSample(&snapshot);
1700
1701 const std::string& histogram_name = histogram.histogram_name();
1702
1703 // Find the already sent stats, or create an empty set.
1704 LoggedSampleMap::iterator it = logged_samples_.find(histogram_name);
1705 Histogram::SampleSet* already_logged;
1706 if (logged_samples_.end() == it) {
1707 // Add new entry
1708 already_logged = &logged_samples_[histogram.histogram_name()];
1709 already_logged->Resize(histogram); // Complete initialization.
1710 } else {
1711 already_logged = &(it->second);
1712 // Deduct any stats we've already logged from our snapshot.
1713 snapshot.Subtract(*already_logged);
1714 }
1715
1716 // snapshot now contains only a delta to what we've already_logged.
1717
1718 if (snapshot.TotalCount() > 0) {
1719 current_log_->RecordHistogramDelta(histogram, snapshot);
1720 // Add new data into our running total.
1721 already_logged->Add(snapshot);
1722 }
1723}
1724
1725void MetricsService::AddProfileMetric(Profile* profile,
1726 const std::wstring& key,
1727 int value) {
1728 // Restriction of types is needed for writing values. See
1729 // MetricsLog::WriteProfileMetrics.
1730 DCHECK(profile && !key.empty());
1731 PrefService* prefs = g_browser_process->local_state();
1732 DCHECK(prefs);
1733
1734 // Key is stored in prefs, which interpret '.'s as paths. As such, key
1735 // shouldn't have any '.'s in it.
1736 DCHECK(key.find(L'.') == std::wstring::npos);
1737 // The id is most likely an email address. We shouldn't send it to the server.
1738 const std::wstring id_hash =
1739 UTF8ToWide(MetricsLog::CreateBase64Hash(WideToUTF8(profile->GetID())));
1740 DCHECK(id_hash.find('.') == std::string::npos);
1741
1742 DictionaryValue* prof_prefs = prefs->GetMutableDictionary(
1743 prefs::kProfileMetrics);
1744 DCHECK(prof_prefs);
1745 const std::wstring pref_key = std::wstring(prefs::kProfilePrefix) + id_hash +
1746 L"." + key;
1747 prof_prefs->SetInteger(pref_key.c_str(), value);
1748}
1749
1750static bool IsSingleThreaded() {
1751 static int thread_id = 0;
1752 if (!thread_id)
1753 thread_id = GetCurrentThreadId();
1754 return GetCurrentThreadId() == thread_id;
1755}