blob: 7a022fa37d4f0176772bbc61062ecf2b1e8e3548 [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.
84// PLUGIN_LIST_REQUESTED, // Waiting for DLL list to be loaded.
85// 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//
97// PLUGIN_LIST_REQUESTED, // Waiting for DLL list to be loaded.
98// 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
161#include "base/histogram.h"
162#include "base/path_service.h"
163#include "base/string_util.h"
164#include "base/task.h"
[email protected]d8e41ed2008-09-11 15:22:32165#include "chrome/browser/bookmarks/bookmark_model.h"
initial.commit09911bf2008-07-26 23:55:29166#include "chrome/browser/browser.h"
167#include "chrome/browser/browser_list.h"
168#include "chrome/browser/browser_process.h"
169#include "chrome/browser/load_notification_details.h"
170#include "chrome/browser/memory_details.h"
171#include "chrome/browser/plugin_process_info.h"
172#include "chrome/browser/plugin_service.h"
173#include "chrome/browser/profile.h"
174#include "chrome/browser/render_process_host.h"
175#include "chrome/browser/template_url.h"
176#include "chrome/browser/template_url_model.h"
177#include "chrome/common/chrome_paths.h"
[email protected]252873ef2008-08-04 21:59:45178#include "chrome/common/libxml_utils.h"
initial.commit09911bf2008-07-26 23:55:29179#include "chrome/common/pref_names.h"
180#include "chrome/common/pref_service.h"
[email protected]6e93e522008-08-14 19:28:17181#include "chrome/installer/util/google_update_settings.h"
initial.commit09911bf2008-07-26 23:55:29182#include "googleurl/src/gurl.h"
183#include "net/base/load_flags.h"
184#include "third_party/bzip2/bzlib.h"
185
[email protected]e1acf6f2008-10-27 20:43:33186using base::Time;
187using base::TimeDelta;
188
initial.commit09911bf2008-07-26 23:55:29189// Check to see that we're being called on only one thread.
190static bool IsSingleThreaded();
191
192static const char kMetricsURL[] =
193 "https://toolbarqueries.google.com/firefox/metrics/collect";
194
195static const char kMetricsType[] = "application/vnd.mozilla.metrics.bz2";
196
197// The delay, in seconds, after startup before sending the first log message.
[email protected]252873ef2008-08-04 21:59:45198static const int kInitialInterlogDuration = 60; // one minute
199
200// The default maximum number of events in a log uploaded to the UMA server.
[email protected]0b33f80b2008-12-17 21:34:36201static const int kInitialEventLimit = 2400;
[email protected]68475e602008-08-22 03:21:15202
203// If an upload fails, and the transmission was over this byte count, then we
204// will discard the log, and not try to retransmit it. We also don't persist
205// the log to the prefs for transmission during the next chrome session if this
206// limit is exceeded.
207static const int kUploadLogAvoidRetransmitSize = 50000;
initial.commit09911bf2008-07-26 23:55:29208
209// When we have logs from previous Chrome sessions to send, how long should we
210// delay (in seconds) between each log transmission.
211static const int kUnsentLogDelay = 15; // 15 seconds
212
213// Minimum time a log typically exists before sending, in seconds.
214// This number is supplied by the server, but until we parse it out of a server
215// response, we use this duration to specify how long we should wait before
216// sending the next log. If the channel is busy, such as when there is a
217// failure during an attempt to transmit a previous log, then a log may wait
218// (and continue to accrue now log entries) for a much greater period of time.
[email protected]0b33f80b2008-12-17 21:34:36219static const int kMinSecondsPerLog = 20 * 60; // twenty minutes
initial.commit09911bf2008-07-26 23:55:29220
initial.commit09911bf2008-07-26 23:55:29221// When we don't succeed at transmitting a log to a server, we progressively
222// wait longer and longer before sending the next log. This backoff process
223// help reduce load on the server, and makes the amount of backoff vary between
224// clients so that a collision (server overload?) on retransmit is less likely.
225// The following is the constant we use to expand that inter-log duration.
226static const double kBackoff = 1.1;
227// We limit the maximum backoff to be no greater than some multiple of the
228// default kMinSecondsPerLog. The following is that maximum ratio.
229static const int kMaxBackoff = 10;
230
231// Interval, in seconds, between state saves.
232static const int kSaveStateInterval = 5 * 60; // five minutes
233
234// The number of "initial" logs we're willing to save, and hope to send during
235// a future Chrome session. Initial logs contain crash stats, and are pretty
236// small.
237static const size_t kMaxInitialLogsPersisted = 20;
238
239// The number of ongoing logs we're willing to save persistently, and hope to
240// send during a this or future sessions. Note that each log will be pretty
241// large, as presumably the related "initial" log wasn't sent (probably nothing
242// was, as the user was probably off-line). As a result, the log probably kept
243// accumulating while the "initial" log was stalled (pending_), and couldn't be
244// sent. As a result, we don't want to save too many of these mega-logs.
245// A "standard shutdown" will create a small log, including just the data that
246// was not yet been transmitted, and that is normal (to have exactly one
247// ongoing_log_ at startup).
248static const size_t kMaxOngoingLogsPersisted = 4;
249
250
251// Handles asynchronous fetching of memory details.
252// Will run the provided task after finished.
253class MetricsMemoryDetails : public MemoryDetails {
254 public:
255 explicit MetricsMemoryDetails(Task* completion) : completion_(completion) {}
256
257 virtual void OnDetailsAvailable() {
258 MessageLoop::current()->PostTask(FROM_HERE, completion_);
259 }
260
261 private:
262 Task* completion_;
263 DISALLOW_EVIL_CONSTRUCTORS(MetricsMemoryDetails);
264};
265
266class MetricsService::GetPluginListTaskComplete : public Task {
267 virtual void Run() {
268 g_browser_process->metrics_service()->OnGetPluginListTaskComplete();
269 }
270};
271
272class MetricsService::GetPluginListTask : public Task {
273 public:
274 explicit GetPluginListTask(MessageLoop* callback_loop)
275 : callback_loop_(callback_loop) {}
276
277 virtual void Run() {
278 std::vector<WebPluginInfo> plugins;
279 PluginService::GetInstance()->GetPlugins(false, &plugins);
280
281 callback_loop_->PostTask(FROM_HERE, new GetPluginListTaskComplete());
282 }
283
284 private:
285 MessageLoop* callback_loop_;
286};
287
288// static
289void MetricsService::RegisterPrefs(PrefService* local_state) {
290 DCHECK(IsSingleThreaded());
291 local_state->RegisterStringPref(prefs::kMetricsClientID, L"");
292 local_state->RegisterStringPref(prefs::kMetricsClientIDTimestamp, L"0");
293 local_state->RegisterStringPref(prefs::kStabilityLaunchTimeSec, L"0");
294 local_state->RegisterStringPref(prefs::kStabilityLastTimestampSec, L"0");
295 local_state->RegisterStringPref(prefs::kStabilityUptimeSec, L"0");
296 local_state->RegisterBooleanPref(prefs::kStabilityExitedCleanly, true);
297 local_state->RegisterBooleanPref(prefs::kStabilitySessionEndCompleted, true);
298 local_state->RegisterIntegerPref(prefs::kMetricsSessionID, -1);
299 local_state->RegisterIntegerPref(prefs::kStabilityLaunchCount, 0);
300 local_state->RegisterIntegerPref(prefs::kStabilityCrashCount, 0);
301 local_state->RegisterIntegerPref(prefs::kStabilityIncompleteSessionEndCount,
302 0);
303 local_state->RegisterIntegerPref(prefs::kStabilityPageLoadCount, 0);
304 local_state->RegisterIntegerPref(prefs::kSecurityRendererOnSboxDesktop, 0);
305 local_state->RegisterIntegerPref(prefs::kSecurityRendererOnDefaultDesktop, 0);
306 local_state->RegisterIntegerPref(prefs::kStabilityRendererCrashCount, 0);
307 local_state->RegisterIntegerPref(prefs::kStabilityRendererHangCount, 0);
[email protected]e73c01972008-08-13 00:18:24308 local_state->RegisterIntegerPref(prefs::kStabilityBreakpadRegistrationFail,
309 0);
310 local_state->RegisterIntegerPref(prefs::kStabilityBreakpadRegistrationSuccess,
311 0);
312 local_state->RegisterIntegerPref(prefs::kStabilityDebuggerPresent, 0);
313 local_state->RegisterIntegerPref(prefs::kStabilityDebuggerNotPresent, 0);
314
initial.commit09911bf2008-07-26 23:55:29315 local_state->RegisterDictionaryPref(prefs::kProfileMetrics);
316 local_state->RegisterIntegerPref(prefs::kNumBookmarksOnBookmarkBar, 0);
317 local_state->RegisterIntegerPref(prefs::kNumFoldersOnBookmarkBar, 0);
318 local_state->RegisterIntegerPref(prefs::kNumBookmarksInOtherBookmarkFolder,
319 0);
320 local_state->RegisterIntegerPref(prefs::kNumFoldersInOtherBookmarkFolder, 0);
321 local_state->RegisterIntegerPref(prefs::kNumKeywords, 0);
322 local_state->RegisterListPref(prefs::kMetricsInitialLogs);
323 local_state->RegisterListPref(prefs::kMetricsOngoingLogs);
324}
325
326MetricsService::MetricsService()
[email protected]d01b8732008-10-16 02:18:07327 : recording_active_(false),
328 reporting_active_(false),
329 user_permits_upload_(false),
330 server_permits_upload_(true),
331 state_(INITIALIZED),
initial.commit09911bf2008-07-26 23:55:29332 pending_log_(NULL),
333 pending_log_text_(""),
334 current_fetch_(NULL),
335 current_log_(NULL),
[email protected]d01b8732008-10-16 02:18:07336 idle_since_last_transmission_(false),
initial.commit09911bf2008-07-26 23:55:29337 next_window_id_(0),
338 log_sender_factory_(this),
339 state_saver_factory_(this),
340 logged_samples_(),
[email protected]252873ef2008-08-04 21:59:45341 interlog_duration_(TimeDelta::FromSeconds(kInitialInterlogDuration)),
[email protected]d01b8732008-10-16 02:18:07342 log_event_limit_(kInitialEventLimit),
initial.commit09911bf2008-07-26 23:55:29343 timer_pending_(false) {
344 DCHECK(IsSingleThreaded());
345 InitializeMetricsState();
346}
347
348MetricsService::~MetricsService() {
349 SetRecording(false);
350}
351
[email protected]d01b8732008-10-16 02:18:07352void MetricsService::SetUserPermitsUpload(bool enabled) {
353 HandleIdleSinceLastTransmission(false);
354 user_permits_upload_ = enabled;
355}
356
357void MetricsService::Start() {
358 SetRecording(true);
359 SetReporting(true);
360}
361
362void MetricsService::StartRecordingOnly() {
363 SetRecording(true);
364 SetReporting(false);
365}
366
367void MetricsService::Stop() {
368 SetReporting(false);
369 SetRecording(false);
370}
371
initial.commit09911bf2008-07-26 23:55:29372void MetricsService::SetRecording(bool enabled) {
373 DCHECK(IsSingleThreaded());
374
[email protected]d01b8732008-10-16 02:18:07375 if (enabled == recording_active_)
initial.commit09911bf2008-07-26 23:55:29376 return;
377
378 if (enabled) {
379 StartRecording();
380 ListenerRegistration(true);
381 } else {
382 // Turn off all observers.
383 ListenerRegistration(false);
384 PushPendingLogsToUnsentLists();
385 DCHECK(!pending_log());
386 if (state_ > INITIAL_LOG_READY && unsent_logs())
387 state_ = SEND_OLD_INITIAL_LOGS;
388 }
[email protected]d01b8732008-10-16 02:18:07389 recording_active_ = enabled;
initial.commit09911bf2008-07-26 23:55:29390}
391
[email protected]d01b8732008-10-16 02:18:07392bool MetricsService::recording_active() const {
initial.commit09911bf2008-07-26 23:55:29393 DCHECK(IsSingleThreaded());
[email protected]d01b8732008-10-16 02:18:07394 return recording_active_;
initial.commit09911bf2008-07-26 23:55:29395}
396
[email protected]d01b8732008-10-16 02:18:07397void MetricsService::SetReporting(bool enable) {
398 if (reporting_active_ != enable) {
399 reporting_active_ = enable;
400 if (reporting_active_)
initial.commit09911bf2008-07-26 23:55:29401 StartLogTransmissionTimer();
402 }
[email protected]d01b8732008-10-16 02:18:07403}
404
405bool MetricsService::reporting_active() const {
406 DCHECK(IsSingleThreaded());
407 return reporting_active_;
initial.commit09911bf2008-07-26 23:55:29408}
409
410void MetricsService::Observe(NotificationType type,
411 const NotificationSource& source,
412 const NotificationDetails& details) {
413 DCHECK(current_log_);
414 DCHECK(IsSingleThreaded());
415
416 if (!CanLogNotification(type, source, details))
417 return;
418
419 switch (type) {
420 case NOTIFY_USER_ACTION:
421 current_log_->RecordUserAction(*Details<const wchar_t*>(details).ptr());
422 break;
423
424 case NOTIFY_BROWSER_OPENED:
425 case NOTIFY_BROWSER_CLOSED:
426 LogWindowChange(type, source, details);
427 break;
428
[email protected]534e54b2008-08-13 15:40:09429 case NOTIFY_TAB_PARENTED:
initial.commit09911bf2008-07-26 23:55:29430 case NOTIFY_TAB_CLOSING:
431 LogWindowChange(type, source, details);
432 break;
433
434 case NOTIFY_LOAD_STOP:
435 LogLoadComplete(type, source, details);
436 break;
437
438 case NOTIFY_LOAD_START:
439 LogLoadStarted();
440 break;
441
442 case NOTIFY_RENDERER_PROCESS_TERMINATED:
443 if (!*Details<bool>(details).ptr())
444 LogRendererCrash();
445 break;
446
447 case NOTIFY_RENDERER_PROCESS_HANG:
448 LogRendererHang();
449 break;
450
451 case NOTIFY_RENDERER_PROCESS_IN_SBOX:
452 LogRendererInSandbox(*Details<bool>(details).ptr());
453 break;
454
455 case NOTIFY_PLUGIN_PROCESS_HOST_CONNECTED:
456 case NOTIFY_PLUGIN_PROCESS_CRASHED:
457 case NOTIFY_PLUGIN_INSTANCE_CREATED:
458 LogPluginChange(type, source, details);
459 break;
460
461 case TEMPLATE_URL_MODEL_LOADED:
462 LogKeywords(Source<TemplateURLModel>(source).ptr());
463 break;
464
465 case NOTIFY_OMNIBOX_OPENED_URL:
466 current_log_->RecordOmniboxOpenedURL(
467 *Details<AutocompleteLog>(details).ptr());
468 break;
469
470 case NOTIFY_BOOKMARK_MODEL_LOADED:
[email protected]d8e41ed2008-09-11 15:22:32471 LogBookmarks(Source<Profile>(source)->GetBookmarkModel());
initial.commit09911bf2008-07-26 23:55:29472 break;
473
474 default:
475 NOTREACHED();
476 break;
477 }
[email protected]d01b8732008-10-16 02:18:07478
479 HandleIdleSinceLastTransmission(false);
480
481 if (current_log_)
482 DLOG(INFO) << "METRICS: NUMBER OF LOGS = " << current_log_->num_events();
483}
484
485void MetricsService::HandleIdleSinceLastTransmission(bool in_idle) {
486 // If there wasn't a lot of action, maybe the computer was asleep, in which
487 // case, the log transmissions should have stopped. Here we start them up
488 // again.
[email protected]cac78842008-11-27 01:02:20489 if (!in_idle && idle_since_last_transmission_)
490 StartLogTransmissionTimer();
491 idle_since_last_transmission_ = in_idle;
initial.commit09911bf2008-07-26 23:55:29492}
493
494void MetricsService::RecordCleanShutdown() {
495 RecordBooleanPrefValue(prefs::kStabilityExitedCleanly, true);
496}
497
498void MetricsService::RecordStartOfSessionEnd() {
499 RecordBooleanPrefValue(prefs::kStabilitySessionEndCompleted, false);
500}
501
502void MetricsService::RecordCompletedSessionEnd() {
503 RecordBooleanPrefValue(prefs::kStabilitySessionEndCompleted, true);
504}
505
[email protected]e73c01972008-08-13 00:18:24506void MetricsService:: RecordBreakpadRegistration(bool success) {
[email protected]68475e602008-08-22 03:21:15507 if (!success)
[email protected]e73c01972008-08-13 00:18:24508 IncrementPrefValue(prefs::kStabilityBreakpadRegistrationFail);
509 else
510 IncrementPrefValue(prefs::kStabilityBreakpadRegistrationSuccess);
511}
512
513void MetricsService::RecordBreakpadHasDebugger(bool has_debugger) {
514 if (!has_debugger)
515 IncrementPrefValue(prefs::kStabilityDebuggerNotPresent);
516 else
[email protected]68475e602008-08-22 03:21:15517 IncrementPrefValue(prefs::kStabilityDebuggerPresent);
[email protected]e73c01972008-08-13 00:18:24518}
519
initial.commit09911bf2008-07-26 23:55:29520//------------------------------------------------------------------------------
521// private methods
522//------------------------------------------------------------------------------
523
524
525//------------------------------------------------------------------------------
526// Initialization methods
527
528void MetricsService::InitializeMetricsState() {
529 PrefService* pref = g_browser_process->local_state();
530 DCHECK(pref);
531
532 client_id_ = WideToUTF8(pref->GetString(prefs::kMetricsClientID));
533 if (client_id_.empty()) {
534 client_id_ = GenerateClientID();
535 pref->SetString(prefs::kMetricsClientID, UTF8ToWide(client_id_));
536
537 // Might as well make a note of how long this ID has existed
538 pref->SetString(prefs::kMetricsClientIDTimestamp,
539 Int64ToWString(Time::Now().ToTimeT()));
540 }
541
542 // Update session ID
543 session_id_ = pref->GetInteger(prefs::kMetricsSessionID);
544 ++session_id_;
545 pref->SetInteger(prefs::kMetricsSessionID, session_id_);
546
initial.commit09911bf2008-07-26 23:55:29547 // Stability bookkeeping
[email protected]e73c01972008-08-13 00:18:24548 IncrementPrefValue(prefs::kStabilityLaunchCount);
initial.commit09911bf2008-07-26 23:55:29549
[email protected]e73c01972008-08-13 00:18:24550 if (!pref->GetBoolean(prefs::kStabilityExitedCleanly)) {
551 IncrementPrefValue(prefs::kStabilityCrashCount);
initial.commit09911bf2008-07-26 23:55:29552 }
[email protected]e73c01972008-08-13 00:18:24553
554 // This will be set to 'true' if we exit cleanly.
initial.commit09911bf2008-07-26 23:55:29555 pref->SetBoolean(prefs::kStabilityExitedCleanly, false);
556
[email protected]e73c01972008-08-13 00:18:24557 if (!pref->GetBoolean(prefs::kStabilitySessionEndCompleted)) {
558 IncrementPrefValue(prefs::kStabilityIncompleteSessionEndCount);
initial.commit09911bf2008-07-26 23:55:29559 }
560 // This is marked false when we get a WM_ENDSESSION.
561 pref->SetBoolean(prefs::kStabilitySessionEndCompleted, true);
562
563 int64 last_start_time =
564 StringToInt64(pref->GetString(prefs::kStabilityLaunchTimeSec));
565 int64 last_end_time =
566 StringToInt64(pref->GetString(prefs::kStabilityLastTimestampSec));
567 int64 uptime =
568 StringToInt64(pref->GetString(prefs::kStabilityUptimeSec));
569
570 if (last_start_time && last_end_time) {
571 // TODO(JAR): Exclude sleep time. ... which must be gathered in UI loop.
572 uptime += last_end_time - last_start_time;
573 pref->SetString(prefs::kStabilityUptimeSec, Int64ToWString(uptime));
574 }
575 pref->SetString(prefs::kStabilityLaunchTimeSec,
576 Int64ToWString(Time::Now().ToTimeT()));
577
578 // Save profile metrics.
579 PrefService* prefs = g_browser_process->local_state();
580 if (prefs) {
581 // Remove the current dictionary and store it for use when sending data to
582 // server. By removing the value we prune potentially dead profiles
583 // (and keys). All valid values are added back once services startup.
584 const DictionaryValue* profile_dictionary =
585 prefs->GetDictionary(prefs::kProfileMetrics);
586 if (profile_dictionary) {
587 // Do a deep copy of profile_dictionary since ClearPref will delete it.
588 profile_dictionary_.reset(static_cast<DictionaryValue*>(
589 profile_dictionary->DeepCopy()));
590 prefs->ClearPref(prefs::kProfileMetrics);
591 }
592 }
593
594 // Kick off the process of saving the state (so the uptime numbers keep
595 // getting updated) every n minutes.
596 ScheduleNextStateSave();
597}
598
599void MetricsService::OnGetPluginListTaskComplete() {
600 DCHECK(state_ == PLUGIN_LIST_REQUESTED);
601 if (state_ == PLUGIN_LIST_REQUESTED)
602 state_ = PLUGIN_LIST_ARRIVED;
603}
604
605std::string MetricsService::GenerateClientID() {
606 const int kGUIDSize = 39;
607
608 GUID guid;
609 HRESULT guid_result = CoCreateGuid(&guid);
610 DCHECK(SUCCEEDED(guid_result));
611
612 std::wstring guid_string;
613 int result = StringFromGUID2(guid,
614 WriteInto(&guid_string, kGUIDSize), kGUIDSize);
615 DCHECK(result == kGUIDSize);
616
617 return WideToUTF8(guid_string.substr(1, guid_string.length() - 2));
618}
619
620
621//------------------------------------------------------------------------------
622// State save methods
623
624void MetricsService::ScheduleNextStateSave() {
625 state_saver_factory_.RevokeAll();
626
627 MessageLoop::current()->PostDelayedTask(FROM_HERE,
628 state_saver_factory_.NewRunnableMethod(&MetricsService::SaveLocalState),
629 kSaveStateInterval * 1000);
630}
631
632void MetricsService::SaveLocalState() {
633 PrefService* pref = g_browser_process->local_state();
634 if (!pref) {
635 NOTREACHED();
636 return;
637 }
638
639 RecordCurrentState(pref);
640 pref->ScheduleSavePersistentPrefs(g_browser_process->file_thread());
641
642 ScheduleNextStateSave();
643}
644
645
646//------------------------------------------------------------------------------
647// Recording control methods
648
649void MetricsService::StartRecording() {
650 if (current_log_)
651 return;
652
653 current_log_ = new MetricsLog(client_id_, session_id_);
654 if (state_ == INITIALIZED) {
655 // We only need to schedule that run once.
656 state_ = PLUGIN_LIST_REQUESTED;
657
658 // Make sure the plugin list is loaded before the inital log is sent, so
659 // that the main thread isn't blocked generating the list.
660 g_browser_process->file_thread()->message_loop()->PostDelayedTask(FROM_HERE,
661 new GetPluginListTask(MessageLoop::current()),
[email protected]252873ef2008-08-04 21:59:45662 kInitialInterlogDuration * 1000 / 2);
initial.commit09911bf2008-07-26 23:55:29663 }
664}
665
666void MetricsService::StopRecording(MetricsLog** log) {
667 if (!current_log_)
668 return;
669
[email protected]68475e602008-08-22 03:21:15670 // TODO(jar): Integrate bounds on log recording more consistently, so that we
671 // can stop recording logs that are too big much sooner.
[email protected]d01b8732008-10-16 02:18:07672 if (current_log_->num_events() > log_event_limit_) {
[email protected]68475e602008-08-22 03:21:15673 UMA_HISTOGRAM_COUNTS(L"UMA.Discarded Log Events",
674 current_log_->num_events());
675 current_log_->CloseLog();
676 delete current_log_;
[email protected]294638782008-09-24 00:22:41677 current_log_ = NULL;
[email protected]68475e602008-08-22 03:21:15678 StartRecording(); // Start trivial log to hold our histograms.
679 }
680
[email protected]0b33f80b2008-12-17 21:34:36681 // Put incremental data (histogram deltas, and realtime stats deltas) at the
682 // end of every log transmission.
initial.commit09911bf2008-07-26 23:55:29683 // Don't bother if we're going to discard current_log_.
[email protected]0b33f80b2008-12-17 21:34:36684 if (log) {
685 current_log_->RecordIncrementalStabilityElements();
initial.commit09911bf2008-07-26 23:55:29686 RecordCurrentHistograms();
[email protected]0b33f80b2008-12-17 21:34:36687 }
initial.commit09911bf2008-07-26 23:55:29688
689 current_log_->CloseLog();
[email protected]cac78842008-11-27 01:02:20690 if (log)
initial.commit09911bf2008-07-26 23:55:29691 *log = current_log_;
[email protected]cac78842008-11-27 01:02:20692 else
initial.commit09911bf2008-07-26 23:55:29693 delete current_log_;
initial.commit09911bf2008-07-26 23:55:29694 current_log_ = NULL;
695}
696
697void MetricsService::ListenerRegistration(bool start_listening) {
698 AddOrRemoveObserver(this, NOTIFY_BROWSER_OPENED, start_listening);
699 AddOrRemoveObserver(this, NOTIFY_BROWSER_CLOSED, start_listening);
700 AddOrRemoveObserver(this, NOTIFY_USER_ACTION, start_listening);
[email protected]534e54b2008-08-13 15:40:09701 AddOrRemoveObserver(this, NOTIFY_TAB_PARENTED, start_listening);
initial.commit09911bf2008-07-26 23:55:29702 AddOrRemoveObserver(this, NOTIFY_TAB_CLOSING, start_listening);
703 AddOrRemoveObserver(this, NOTIFY_LOAD_START, start_listening);
704 AddOrRemoveObserver(this, NOTIFY_LOAD_STOP, start_listening);
705 AddOrRemoveObserver(this, NOTIFY_RENDERER_PROCESS_IN_SBOX, start_listening);
706 AddOrRemoveObserver(this, NOTIFY_RENDERER_PROCESS_TERMINATED,
707 start_listening);
708 AddOrRemoveObserver(this, NOTIFY_RENDERER_PROCESS_HANG, start_listening);
709 AddOrRemoveObserver(this, NOTIFY_PLUGIN_PROCESS_HOST_CONNECTED,
710 start_listening);
711 AddOrRemoveObserver(this, NOTIFY_PLUGIN_INSTANCE_CREATED, start_listening);
712 AddOrRemoveObserver(this, NOTIFY_PLUGIN_PROCESS_CRASHED, start_listening);
713 AddOrRemoveObserver(this, TEMPLATE_URL_MODEL_LOADED, start_listening);
714 AddOrRemoveObserver(this, NOTIFY_OMNIBOX_OPENED_URL, start_listening);
715 AddOrRemoveObserver(this, NOTIFY_BOOKMARK_MODEL_LOADED, start_listening);
716}
717
718// static
719void MetricsService::AddOrRemoveObserver(NotificationObserver* observer,
[email protected]cac78842008-11-27 01:02:20720 NotificationType type,
721 bool is_add) {
initial.commit09911bf2008-07-26 23:55:29722 NotificationService* service = NotificationService::current();
723
[email protected]cac78842008-11-27 01:02:20724 if (is_add)
initial.commit09911bf2008-07-26 23:55:29725 service->AddObserver(observer, type, NotificationService::AllSources());
[email protected]cac78842008-11-27 01:02:20726 else
initial.commit09911bf2008-07-26 23:55:29727 service->RemoveObserver(observer, type, NotificationService::AllSources());
initial.commit09911bf2008-07-26 23:55:29728}
729
730void MetricsService::PushPendingLogsToUnsentLists() {
731 if (state_ < INITIAL_LOG_READY)
732 return; // We didn't and still don't have time to get DLL list etc.
733
734 if (pending_log()) {
735 PreparePendingLogText();
736 if (state_ == INITIAL_LOG_READY) {
737 // We may race here, and send second copy of initial log later.
738 unsent_initial_logs_.push_back(pending_log_text_);
[email protected]d01b8732008-10-16 02:18:07739 state_ = SEND_OLD_INITIAL_LOGS;
initial.commit09911bf2008-07-26 23:55:29740 } else {
[email protected]68475e602008-08-22 03:21:15741 PushPendingLogTextToUnsentOngoingLogs();
initial.commit09911bf2008-07-26 23:55:29742 }
743 DiscardPendingLog();
744 }
745 DCHECK(!pending_log());
746 StopRecording(&pending_log_);
747 PreparePendingLogText();
[email protected]68475e602008-08-22 03:21:15748 PushPendingLogTextToUnsentOngoingLogs();
initial.commit09911bf2008-07-26 23:55:29749 DiscardPendingLog();
750 StoreUnsentLogs();
751}
752
[email protected]68475e602008-08-22 03:21:15753void MetricsService::PushPendingLogTextToUnsentOngoingLogs() {
[email protected]d01b8732008-10-16 02:18:07754 // If UMA response told us not to upload, there's no need to save the pending
755 // log. It wasn't supposed to be uploaded anyway.
756 if (!server_permits_upload_)
757 return;
758
[email protected]68475e602008-08-22 03:21:15759 if (pending_log_text_.length() > kUploadLogAvoidRetransmitSize) {
760 UMA_HISTOGRAM_COUNTS(L"UMA.Large Accumulated Log Not Persisted",
761 static_cast<int>(pending_log_text_.length()));
762 return;
763 }
764 unsent_ongoing_logs_.push_back(pending_log_text_);
765}
766
initial.commit09911bf2008-07-26 23:55:29767//------------------------------------------------------------------------------
768// Transmission of logs methods
769
770void MetricsService::StartLogTransmissionTimer() {
[email protected]d01b8732008-10-16 02:18:07771 // If we're not reporting, there's no point in starting a log transmission
772 // timer.
773 if (!reporting_active())
774 return;
775
initial.commit09911bf2008-07-26 23:55:29776 if (!current_log_)
777 return; // Recorder is shutdown.
[email protected]d01b8732008-10-16 02:18:07778
779 // If there is already a timer running, we leave it running.
780 // If timer_pending is true because the fetch is waiting for a response,
781 // we return for now and let the response handler start the timer.
782 if (timer_pending_)
initial.commit09911bf2008-07-26 23:55:29783 return;
[email protected]d01b8732008-10-16 02:18:07784
[email protected]d01b8732008-10-16 02:18:07785 // Before starting the timer, set timer_pending_ to true.
initial.commit09911bf2008-07-26 23:55:29786 timer_pending_ = true;
[email protected]d01b8732008-10-16 02:18:07787
788 // Right before the UMA transmission gets started, there's one more thing we'd
789 // like to record: the histogram of memory usage, so we spawn a task to
790 // collect the memory details and when that task is finished, we arrange for
791 // TryToStartTransmission to take over.
initial.commit09911bf2008-07-26 23:55:29792 MessageLoop::current()->PostDelayedTask(FROM_HERE,
793 log_sender_factory_.
794 NewRunnableMethod(&MetricsService::CollectMemoryDetails),
795 static_cast<int>(interlog_duration_.InMilliseconds()));
796}
797
798void MetricsService::TryToStartTransmission() {
799 DCHECK(IsSingleThreaded());
800
[email protected]d01b8732008-10-16 02:18:07801 // This function should only be called via timer, so timer_pending_
802 // should be true.
803 DCHECK(timer_pending_);
804 timer_pending_ = false;
initial.commit09911bf2008-07-26 23:55:29805
806 DCHECK(!current_fetch_.get());
initial.commit09911bf2008-07-26 23:55:29807
[email protected]d01b8732008-10-16 02:18:07808 // If we're getting no notifications, then the log won't have much in it, and
809 // it's possible the computer is about to go to sleep, so don't upload and
810 // don't restart the transmission timer.
811 if (idle_since_last_transmission_)
812 return;
813
814 // If somehow there is a fetch in progress, we return setting timer_pending_
815 // to true and hope things work out.
816 if (current_fetch_.get()) {
817 timer_pending_ = true;
818 return;
819 }
820
821 // If uploads are forbidden by UMA response, there's no point in keeping
822 // the current_log_, and the more often we delete it, the less likely it is
823 // to expand forever.
824 if (!server_permits_upload_ && current_log_) {
825 StopRecording(NULL);
826 StartRecording();
827 }
initial.commit09911bf2008-07-26 23:55:29828
829 if (!current_log_)
830 return; // Logging was disabled.
[email protected]d01b8732008-10-16 02:18:07831 if (!reporting_active())
initial.commit09911bf2008-07-26 23:55:29832 return; // Don't do work if we're not going to send anything now.
833
[email protected]d01b8732008-10-16 02:18:07834 MakePendingLog();
initial.commit09911bf2008-07-26 23:55:29835
[email protected]d01b8732008-10-16 02:18:07836 // MakePendingLog should have put something in the pending log, if it didn't,
837 // we start the timer again, return and hope things work out.
838 if (!pending_log()) {
839 StartLogTransmissionTimer();
840 return;
841 }
initial.commit09911bf2008-07-26 23:55:29842
[email protected]d01b8732008-10-16 02:18:07843 // If we're not supposed to upload any UMA data because the response or the
844 // user said so, cancel the upload at this point, but start the timer.
845 if (!TransmissionPermitted()) {
846 DiscardPendingLog();
847 StartLogTransmissionTimer();
848 return;
849 }
initial.commit09911bf2008-07-26 23:55:29850
[email protected]d01b8732008-10-16 02:18:07851 PrepareFetchWithPendingLog();
852
853 if (!current_fetch_.get()) {
854 // Compression failed, and log discarded :-/.
855 DiscardPendingLog();
856 StartLogTransmissionTimer(); // Maybe we'll do better next time
857 // TODO(jar): If compression failed, we should have created a tiny log and
858 // compressed that, so that we can signal that we're losing logs.
859 return;
860 }
861
862 DCHECK(!timer_pending_);
863
864 // The URL fetch is a like timer in that after a while we get called back
865 // so we set timer_pending_ true just as we start the url fetch.
866 timer_pending_ = true;
867 current_fetch_->Start();
868
869 HandleIdleSinceLastTransmission(true);
870}
871
872
873void MetricsService::MakePendingLog() {
874 if (pending_log())
875 return;
876
877 switch (state_) {
878 case INITIALIZED:
879 case PLUGIN_LIST_REQUESTED: // We should be further along by now.
880 DCHECK(false);
881 return;
882
883 case PLUGIN_LIST_ARRIVED:
884 // We need to wait for the initial log to be ready before sending
885 // anything, because the server will tell us whether it wants to hear
886 // from us.
887 PrepareInitialLog();
888 DCHECK(state_ == PLUGIN_LIST_ARRIVED);
889 RecallUnsentLogs();
890 state_ = INITIAL_LOG_READY;
891 break;
892
893 case SEND_OLD_INITIAL_LOGS:
[email protected]cac78842008-11-27 01:02:20894 if (!unsent_initial_logs_.empty()) {
895 pending_log_text_ = unsent_initial_logs_.back();
896 break;
897 }
[email protected]d01b8732008-10-16 02:18:07898 state_ = SENDING_OLD_LOGS;
899 // Fall through.
initial.commit09911bf2008-07-26 23:55:29900
[email protected]d01b8732008-10-16 02:18:07901 case SENDING_OLD_LOGS:
902 if (!unsent_ongoing_logs_.empty()) {
903 pending_log_text_ = unsent_ongoing_logs_.back();
904 break;
905 }
906 state_ = SENDING_CURRENT_LOGS;
907 // Fall through.
908
909 case SENDING_CURRENT_LOGS:
910 StopRecording(&pending_log_);
911 StartRecording();
912 break;
913
914 default:
915 DCHECK(false);
916 return;
917 }
918
919 DCHECK(pending_log());
920}
921
922bool MetricsService::TransmissionPermitted() const {
923 // If the user forbids uploading that's they're business, and we don't upload
924 // anything. If the server forbids uploading, that's our business, so we take
925 // that to mean it forbids current logs, but we still send up the inital logs
926 // and any old logs.
[email protected]d01b8732008-10-16 02:18:07927 if (!user_permits_upload_)
928 return false;
[email protected]cac78842008-11-27 01:02:20929 if (server_permits_upload_)
[email protected]d01b8732008-10-16 02:18:07930 return true;
initial.commit09911bf2008-07-26 23:55:29931
[email protected]cac78842008-11-27 01:02:20932 switch (state_) {
933 case INITIAL_LOG_READY:
934 case SEND_OLD_INITIAL_LOGS:
935 case SENDING_OLD_LOGS:
936 return true;
937
938 case SENDING_CURRENT_LOGS:
939 default:
940 return false;
[email protected]8c8824b2008-09-20 01:55:50941 }
initial.commit09911bf2008-07-26 23:55:29942}
943
944void MetricsService::CollectMemoryDetails() {
945 Task* task = log_sender_factory_.
946 NewRunnableMethod(&MetricsService::TryToStartTransmission);
947 MetricsMemoryDetails* details = new MetricsMemoryDetails(task);
948 details->StartFetch();
949
950 // Collect WebCore cache information to put into a histogram.
951 for (RenderProcessHost::iterator it = RenderProcessHost::begin();
952 it != RenderProcessHost::end(); ++it) {
953 it->second->Send(new ViewMsg_GetCacheResourceStats());
954 }
955}
956
957void MetricsService::PrepareInitialLog() {
958 DCHECK(state_ == PLUGIN_LIST_ARRIVED);
959 std::vector<WebPluginInfo> plugins;
960 PluginService::GetInstance()->GetPlugins(false, &plugins);
961
962 MetricsLog* log = new MetricsLog(client_id_, session_id_);
963 log->RecordEnvironment(plugins, profile_dictionary_.get());
964
965 // Histograms only get written to current_log_, so setup for the write.
966 MetricsLog* save_log = current_log_;
967 current_log_ = log;
968 RecordCurrentHistograms(); // Into current_log_... which is really log.
969 current_log_ = save_log;
970
971 log->CloseLog();
972 DCHECK(!pending_log());
973 pending_log_ = log;
974}
975
976void MetricsService::RecallUnsentLogs() {
977 DCHECK(unsent_initial_logs_.empty());
978 DCHECK(unsent_ongoing_logs_.empty());
979
980 PrefService* local_state = g_browser_process->local_state();
981 DCHECK(local_state);
982
983 ListValue* unsent_initial_logs = local_state->GetMutableList(
984 prefs::kMetricsInitialLogs);
985 for (ListValue::iterator it = unsent_initial_logs->begin();
986 it != unsent_initial_logs->end(); ++it) {
987 std::wstring wide_log;
988 (*it)->GetAsString(&wide_log);
989 unsent_initial_logs_.push_back(WideToUTF8(wide_log));
990 }
991
992 ListValue* unsent_ongoing_logs = local_state->GetMutableList(
993 prefs::kMetricsOngoingLogs);
994 for (ListValue::iterator it = unsent_ongoing_logs->begin();
995 it != unsent_ongoing_logs->end(); ++it) {
996 std::wstring wide_log;
997 (*it)->GetAsString(&wide_log);
998 unsent_ongoing_logs_.push_back(WideToUTF8(wide_log));
999 }
1000}
1001
1002void MetricsService::StoreUnsentLogs() {
1003 if (state_ < INITIAL_LOG_READY)
1004 return; // We never Recalled the prior unsent logs.
1005
1006 PrefService* local_state = g_browser_process->local_state();
1007 DCHECK(local_state);
1008
1009 ListValue* unsent_initial_logs = local_state->GetMutableList(
1010 prefs::kMetricsInitialLogs);
1011 unsent_initial_logs->Clear();
1012 size_t start = 0;
1013 if (unsent_initial_logs_.size() > kMaxInitialLogsPersisted)
1014 start = unsent_initial_logs_.size() - kMaxInitialLogsPersisted;
1015 for (size_t i = start; i < unsent_initial_logs_.size(); ++i)
1016 unsent_initial_logs->Append(
1017 Value::CreateStringValue(UTF8ToWide(unsent_initial_logs_[i])));
1018
1019 ListValue* unsent_ongoing_logs = local_state->GetMutableList(
1020 prefs::kMetricsOngoingLogs);
1021 unsent_ongoing_logs->Clear();
1022 start = 0;
1023 if (unsent_ongoing_logs_.size() > kMaxOngoingLogsPersisted)
1024 start = unsent_ongoing_logs_.size() - kMaxOngoingLogsPersisted;
1025 for (size_t i = start; i < unsent_ongoing_logs_.size(); ++i)
1026 unsent_ongoing_logs->Append(
1027 Value::CreateStringValue(UTF8ToWide(unsent_ongoing_logs_[i])));
1028}
1029
1030void MetricsService::PreparePendingLogText() {
1031 DCHECK(pending_log());
1032 if (!pending_log_text_.empty())
1033 return;
1034 int original_size = pending_log_->GetEncodedLogSize();
1035 pending_log_->GetEncodedLog(WriteInto(&pending_log_text_, original_size),
1036 original_size);
1037}
1038
[email protected]d01b8732008-10-16 02:18:071039void MetricsService::PrepareFetchWithPendingLog() {
initial.commit09911bf2008-07-26 23:55:291040 DCHECK(pending_log());
1041 DCHECK(!current_fetch_.get());
1042 PreparePendingLogText();
1043 DCHECK(!pending_log_text_.empty());
1044
1045 // Allow security conscious users to see all metrics logs that we send.
1046 LOG(INFO) << "METRICS LOG: " << pending_log_text_;
1047
1048 std::string compressed_log;
[email protected]cac78842008-11-27 01:02:201049 if (!Bzip2Compress(pending_log_text_, &compressed_log)) {
initial.commit09911bf2008-07-26 23:55:291050 NOTREACHED() << "Failed to compress log for transmission.";
1051 DiscardPendingLog();
1052 StartLogTransmissionTimer(); // Maybe we'll do better on next log :-/.
1053 return;
1054 }
[email protected]cac78842008-11-27 01:02:201055
initial.commit09911bf2008-07-26 23:55:291056 current_fetch_.reset(new URLFetcher(GURL(kMetricsURL), URLFetcher::POST,
1057 this));
1058 current_fetch_->set_request_context(Profile::GetDefaultRequestContext());
1059 current_fetch_->set_upload_data(kMetricsType, compressed_log);
1060 // This flag works around the cert mismatch on toolbarqueries.google.com.
1061 current_fetch_->set_load_flags(net::LOAD_IGNORE_CERT_COMMON_NAME_INVALID);
1062}
1063
1064void MetricsService::DiscardPendingLog() {
1065 if (pending_log_) { // Shutdown might have deleted it!
1066 delete pending_log_;
1067 pending_log_ = NULL;
1068 }
1069 pending_log_text_.clear();
1070}
1071
1072// This implementation is based on the Firefox MetricsService implementation.
1073bool MetricsService::Bzip2Compress(const std::string& input,
1074 std::string* output) {
1075 bz_stream stream = {0};
1076 // As long as our input is smaller than the bzip2 block size, we should get
1077 // the best compression. For example, if your input was 250k, using a block
1078 // size of 300k or 500k should result in the same compression ratio. Since
1079 // our data should be under 100k, using the minimum block size of 100k should
1080 // allocate less temporary memory, but result in the same compression ratio.
1081 int result = BZ2_bzCompressInit(&stream,
1082 1, // 100k (min) block size
1083 0, // quiet
1084 0); // default "work factor"
1085 if (result != BZ_OK) { // out of memory?
1086 return false;
1087 }
1088
1089 output->clear();
1090
1091 stream.next_in = const_cast<char*>(input.data());
1092 stream.avail_in = static_cast<int>(input.size());
1093 // NOTE: we don't need a BZ_RUN phase since our input buffer contains
1094 // the entire input
1095 do {
1096 output->resize(output->size() + 1024);
1097 stream.next_out = &((*output)[stream.total_out_lo32]);
1098 stream.avail_out = static_cast<int>(output->size()) - stream.total_out_lo32;
1099 result = BZ2_bzCompress(&stream, BZ_FINISH);
1100 } while (result == BZ_FINISH_OK);
1101 if (result != BZ_STREAM_END) // unknown failure?
1102 return false;
1103 result = BZ2_bzCompressEnd(&stream);
1104 DCHECK(result == BZ_OK);
1105
1106 output->resize(stream.total_out_lo32);
1107
1108 return true;
1109}
1110
1111static const char* StatusToString(const URLRequestStatus& status) {
1112 switch (status.status()) {
1113 case URLRequestStatus::SUCCESS:
1114 return "SUCCESS";
1115
1116 case URLRequestStatus::IO_PENDING:
1117 return "IO_PENDING";
1118
1119 case URLRequestStatus::HANDLED_EXTERNALLY:
1120 return "HANDLED_EXTERNALLY";
1121
1122 case URLRequestStatus::CANCELED:
1123 return "CANCELED";
1124
1125 case URLRequestStatus::FAILED:
1126 return "FAILED";
1127
1128 default:
1129 NOTREACHED();
1130 return "Unknown";
1131 }
1132}
1133
1134void MetricsService::OnURLFetchComplete(const URLFetcher* source,
1135 const GURL& url,
1136 const URLRequestStatus& status,
1137 int response_code,
1138 const ResponseCookies& cookies,
1139 const std::string& data) {
1140 DCHECK(timer_pending_);
1141 timer_pending_ = false;
1142 DCHECK(current_fetch_.get());
1143 current_fetch_.reset(NULL); // We're not allowed to re-use it.
1144
1145 // Confirm send so that we can move on.
[email protected]cac78842008-11-27 01:02:201146 DLOG(INFO) << "METRICS RESPONSE CODE: " << response_code << " status=" <<
1147 StatusToString(status);
[email protected]252873ef2008-08-04 21:59:451148
[email protected]68475e602008-08-22 03:21:151149 // TODO(petersont): Refactor or remove the following so that we don't have to
1150 // fake a valid response code.
1151 if (response_code != 200 &&
1152 pending_log_text_.length() > kUploadLogAvoidRetransmitSize) {
1153 UMA_HISTOGRAM_COUNTS(L"UMA.Large Rejected Log was Discarded",
1154 static_cast<int>(pending_log_text_.length()));
1155 response_code = 200; // Simulate transmission so we will discard log.
1156 }
1157
[email protected]252873ef2008-08-04 21:59:451158 if (response_code != 200) {
1159 HandleBadResponseCode();
1160 } else { // Success.
[email protected]d01b8732008-10-16 02:18:071161 DLOG(INFO) << "METRICS RESPONSE DATA: " << data;
initial.commit09911bf2008-07-26 23:55:291162 switch (state_) {
1163 case INITIAL_LOG_READY:
1164 state_ = SEND_OLD_INITIAL_LOGS;
1165 break;
1166
1167 case SEND_OLD_INITIAL_LOGS:
1168 DCHECK(!unsent_initial_logs_.empty());
1169 unsent_initial_logs_.pop_back();
1170 StoreUnsentLogs();
1171 break;
1172
1173 case SENDING_OLD_LOGS:
1174 DCHECK(!unsent_ongoing_logs_.empty());
1175 unsent_ongoing_logs_.pop_back();
1176 StoreUnsentLogs();
1177 break;
1178
1179 case SENDING_CURRENT_LOGS:
1180 break;
1181
1182 default:
1183 DCHECK(false);
1184 break;
1185 }
[email protected]d01b8732008-10-16 02:18:071186
initial.commit09911bf2008-07-26 23:55:291187 DiscardPendingLog();
[email protected]29be92552008-08-07 22:49:271188 // Since we sent a log, make sure our in-memory state is recorded to disk.
1189 PrefService* local_state = g_browser_process->local_state();
1190 DCHECK(local_state);
1191 if (local_state)
1192 local_state->ScheduleSavePersistentPrefs(
1193 g_browser_process->file_thread());
[email protected]252873ef2008-08-04 21:59:451194
1195 GetSettingsFromResponseData(data);
[email protected]252873ef2008-08-04 21:59:451196 // Override server specified interlog delay if there are unsent logs to
[email protected]29be92552008-08-07 22:49:271197 // transmit.
initial.commit09911bf2008-07-26 23:55:291198 if (unsent_logs()) {
1199 DCHECK(state_ < SENDING_CURRENT_LOGS);
1200 interlog_duration_ = TimeDelta::FromSeconds(kUnsentLogDelay);
initial.commit09911bf2008-07-26 23:55:291201 }
1202 }
[email protected]252873ef2008-08-04 21:59:451203
initial.commit09911bf2008-07-26 23:55:291204 StartLogTransmissionTimer();
1205}
1206
[email protected]252873ef2008-08-04 21:59:451207void MetricsService::HandleBadResponseCode() {
1208 DLOG(INFO) << "METRICS: transmission attempt returned a failure code. "
1209 "Verify network connectivity";
1210#ifndef NDEBUG
[email protected]cac78842008-11-27 01:02:201211 DLOG(INFO) << "Verify your metrics logs are formatted correctly. "
1212 "Verify server is active at " << kMetricsURL;
[email protected]252873ef2008-08-04 21:59:451213#endif
1214 if (!pending_log()) {
1215 DLOG(INFO) << "METRICS: Recorder shutdown during log transmission.";
1216 } else {
1217 // Send progressively less frequently.
1218 DCHECK(kBackoff > 1.0);
1219 interlog_duration_ = TimeDelta::FromMicroseconds(
1220 static_cast<int64>(kBackoff * interlog_duration_.InMicroseconds()));
1221
1222 if (kMaxBackoff * TimeDelta::FromSeconds(kMinSecondsPerLog) <
[email protected]cac78842008-11-27 01:02:201223 interlog_duration_) {
[email protected]252873ef2008-08-04 21:59:451224 interlog_duration_ = kMaxBackoff *
1225 TimeDelta::FromSeconds(kMinSecondsPerLog);
[email protected]cac78842008-11-27 01:02:201226 }
[email protected]252873ef2008-08-04 21:59:451227
1228 DLOG(INFO) << "METRICS: transmission retry being scheduled in " <<
1229 interlog_duration_.InSeconds() << " seconds for " <<
1230 pending_log_text_;
initial.commit09911bf2008-07-26 23:55:291231 }
initial.commit09911bf2008-07-26 23:55:291232}
1233
[email protected]252873ef2008-08-04 21:59:451234void MetricsService::GetSettingsFromResponseData(const std::string& data) {
1235 // We assume that the file is structured as a block opened by <response>
[email protected]d01b8732008-10-16 02:18:071236 // and that inside response, there is a block opened by tag <chrome_config>
1237 // other tags are ignored for now except the content of <chrome_config>.
1238 DLOG(INFO) << "METRICS: getting settings from response data: " << data;
1239
[email protected]252873ef2008-08-04 21:59:451240 int data_size = static_cast<int>(data.size());
1241 if (data_size < 0) {
[email protected]cac78842008-11-27 01:02:201242 DLOG(INFO) << "METRICS: server response data bad size: " << data_size <<
1243 "; aborting extraction of settings";
[email protected]252873ef2008-08-04 21:59:451244 return;
1245 }
[email protected]cac78842008-11-27 01:02:201246 xmlDocPtr doc = xmlReadMemory(data.c_str(), data_size, "", NULL, 0);
[email protected]252873ef2008-08-04 21:59:451247 DCHECK(doc);
[email protected]d01b8732008-10-16 02:18:071248 // If the document is malformed, we just use the settings that were there.
1249 if (!doc) {
1250 DLOG(INFO) << "METRICS: reading xml from server response data failed";
[email protected]252873ef2008-08-04 21:59:451251 return;
[email protected]d01b8732008-10-16 02:18:071252 }
[email protected]252873ef2008-08-04 21:59:451253
[email protected]d01b8732008-10-16 02:18:071254 xmlNodePtr top_node = xmlDocGetRootElement(doc), chrome_config_node = NULL;
1255 // Here, we find the chrome_config node by name.
[email protected]252873ef2008-08-04 21:59:451256 for (xmlNodePtr p = top_node->children; p; p = p->next) {
[email protected]d01b8732008-10-16 02:18:071257 if (xmlStrEqual(p->name, BAD_CAST "chrome_config")) {
1258 chrome_config_node = p;
[email protected]252873ef2008-08-04 21:59:451259 break;
1260 }
1261 }
1262 // If the server data is formatted wrong and there is no
1263 // config node where we expect, we just drop out.
[email protected]d01b8732008-10-16 02:18:071264 if (chrome_config_node != NULL)
1265 GetSettingsFromChromeConfigNode(chrome_config_node);
[email protected]252873ef2008-08-04 21:59:451266 xmlFreeDoc(doc);
1267}
1268
[email protected]d01b8732008-10-16 02:18:071269void MetricsService::GetSettingsFromChromeConfigNode(
1270 xmlNodePtr chrome_config_node) {
1271 // Iterate through all children of the config node.
1272 for (xmlNodePtr current_node = chrome_config_node->children;
1273 current_node;
1274 current_node = current_node->next) {
1275 // If we find the upload tag, we appeal to another function
1276 // GetSettingsFromUploadNode to read all the data in it.
[email protected]252873ef2008-08-04 21:59:451277 if (xmlStrEqual(current_node->name, BAD_CAST "upload")) {
[email protected]d01b8732008-10-16 02:18:071278 GetSettingsFromUploadNode(current_node);
[email protected]252873ef2008-08-04 21:59:451279 continue;
1280 }
1281 }
1282}
initial.commit09911bf2008-07-26 23:55:291283
[email protected]d01b8732008-10-16 02:18:071284void MetricsService::InheritedProperties::OverwriteWhereNeeded(
1285 xmlNodePtr node) {
1286 xmlChar* salt_value = xmlGetProp(node, BAD_CAST "salt");
1287 if (salt_value) // If the property isn't there, xmlGetProp returns NULL.
1288 salt = atoi(reinterpret_cast<char*>(salt_value));
1289 // If the property isn't there, we keep the value the property had before
1290
1291 xmlChar* denominator_value = xmlGetProp(node, BAD_CAST "denominator");
1292 if (denominator_value)
1293 denominator = atoi(reinterpret_cast<char*>(denominator_value));
1294}
1295
1296void MetricsService::GetSettingsFromUploadNode(xmlNodePtr upload_node) {
1297 InheritedProperties props;
1298 GetSettingsFromUploadNodeRecursive(upload_node, props, "", true);
1299}
1300
[email protected]cac78842008-11-27 01:02:201301void MetricsService::GetSettingsFromUploadNodeRecursive(
1302 xmlNodePtr node,
1303 InheritedProperties props,
1304 std::string path_prefix,
1305 bool uploadOn) {
[email protected]d01b8732008-10-16 02:18:071306 props.OverwriteWhereNeeded(node);
1307
1308 // The bool uploadOn is set to true if the data represented by current
1309 // node should be uploaded. This gets inherited in the tree; the children
1310 // of a node that has already been rejected for upload get rejected for
1311 // upload.
1312 uploadOn = uploadOn && NodeProbabilityTest(node, props);
1313
1314 // The path is a / separated list of the node names ancestral to the current
1315 // one. So, if you want to check if the current node has a certain name,
1316 // compare to name. If you want to check if it is a certan tag at a certain
1317 // place in the tree, compare to the whole path.
1318 std::string name = std::string(reinterpret_cast<const char*>(node->name));
1319 std::string path = path_prefix + "/" + name;
1320
1321 if (path == "/upload") {
1322 xmlChar* upload_interval_val = xmlGetProp(node, BAD_CAST "interval");
1323 if (upload_interval_val) {
1324 interlog_duration_ = TimeDelta::FromSeconds(
1325 atoi(reinterpret_cast<char*>(upload_interval_val)));
1326 }
1327
1328 server_permits_upload_ = uploadOn;
1329 }
1330 if (path == "/upload/logs") {
1331 xmlChar* log_event_limit_val = xmlGetProp(node, BAD_CAST "event_limit");
1332 if (log_event_limit_val)
1333 log_event_limit_ = atoi(reinterpret_cast<char*>(log_event_limit_val));
1334 }
1335 if (name == "histogram") {
1336 xmlChar* type_value = xmlGetProp(node, BAD_CAST "type");
1337 if (type_value) {
1338 std::string type = (reinterpret_cast<char*>(type_value));
1339 if (uploadOn)
1340 histograms_to_upload_.insert(type);
1341 else
1342 histograms_to_omit_.insert(type);
1343 }
1344 }
1345 if (name == "log") {
1346 xmlChar* type_value = xmlGetProp(node, BAD_CAST "type");
1347 if (type_value) {
1348 std::string type = (reinterpret_cast<char*>(type_value));
1349 if (uploadOn)
1350 logs_to_upload_.insert(type);
1351 else
1352 logs_to_omit_.insert(type);
1353 }
1354 }
1355
1356 // Recursive call. If the node is a leaf i.e. if it ends in a "/>", then it
1357 // doesn't have children, so node->children is NULL, and this loop doesn't
1358 // call (that's how the recursion ends).
1359 for (xmlNodePtr child_node = node->children;
[email protected]cac78842008-11-27 01:02:201360 child_node;
1361 child_node = child_node->next) {
[email protected]d01b8732008-10-16 02:18:071362 GetSettingsFromUploadNodeRecursive(child_node, props, path, uploadOn);
1363 }
1364}
1365
1366bool MetricsService::NodeProbabilityTest(xmlNodePtr node,
[email protected]cac78842008-11-27 01:02:201367 InheritedProperties props) const {
[email protected]d01b8732008-10-16 02:18:071368 // Default value of probability on any node is 1, but recall that
1369 // its parents can already have been rejected for upload.
1370 double probability = 1;
1371
1372 // If a probability is specified in the node, we use it instead.
1373 xmlChar* probability_value = xmlGetProp(node, BAD_CAST "probability");
1374 if (probability_value)
[email protected]0b33f80b2008-12-17 21:34:361375 probability = atoi(reinterpret_cast<char*>(probability_value));
[email protected]d01b8732008-10-16 02:18:071376
1377 return ProbabilityTest(probability, props.salt, props.denominator);
1378}
1379
1380bool MetricsService::ProbabilityTest(double probability,
1381 int salt,
1382 int denominator) const {
1383 // Okay, first we figure out how many of the digits of the
1384 // client_id_ we need in order to make a nice pseudorandomish
1385 // number in the range [0,denominator). Too many digits is
1386 // fine.
[email protected]cac78842008-11-27 01:02:201387 int relevant_digits =
1388 static_cast<int>(log10(static_cast<double>(denominator)) + 1.0);
[email protected]d01b8732008-10-16 02:18:071389
1390 // n is the length of the client_id_ string
1391 size_t n = client_id_.size();
1392
1393 // idnumber is a positive integer generated from the client_id_.
1394 // It plus salt is going to give us our pseudorandom number.
1395 int idnumber = 0;
1396 const char* client_id_c_str = client_id_.c_str();
1397
1398 // Here we hash the relevant digits of the client_id_
1399 // string somehow to get a big integer idnumber (could be negative
1400 // from wraparound)
1401 int big = 1;
[email protected]cac78842008-11-27 01:02:201402 for (size_t j = n - 1; j >= 0; --j) {
1403 idnumber += static_cast<int>(client_id_c_str[j]) * big;
[email protected]d01b8732008-10-16 02:18:071404 big *= 10;
1405 }
1406
1407 // Mod id number by denominator making sure to get a non-negative
1408 // answer.
[email protected]cac78842008-11-27 01:02:201409 idnumber = ((idnumber % denominator) + denominator) % denominator;
[email protected]d01b8732008-10-16 02:18:071410
[email protected]cac78842008-11-27 01:02:201411 // ((idnumber + salt) % denominator) / denominator is in the range [0,1]
[email protected]d01b8732008-10-16 02:18:071412 // if it's less than probability we call that an affirmative coin
1413 // toss.
[email protected]cac78842008-11-27 01:02:201414 return static_cast<double>((idnumber + salt) % denominator) <
1415 probability * denominator;
[email protected]d01b8732008-10-16 02:18:071416}
1417
initial.commit09911bf2008-07-26 23:55:291418void MetricsService::LogWindowChange(NotificationType type,
1419 const NotificationSource& source,
1420 const NotificationDetails& details) {
[email protected]534e54b2008-08-13 15:40:091421 int controller_id = -1;
1422 uintptr_t window_or_tab = source.map_key();
initial.commit09911bf2008-07-26 23:55:291423 MetricsLog::WindowEventType window_type;
1424
1425 // Note: since we stop all logging when a single OTR session is active, it is
1426 // possible that we start getting notifications about a window that we don't
1427 // know about.
[email protected]534e54b2008-08-13 15:40:091428 if (window_map_.find(window_or_tab) == window_map_.end()) {
1429 controller_id = next_window_id_++;
1430 window_map_[window_or_tab] = controller_id;
initial.commit09911bf2008-07-26 23:55:291431 } else {
[email protected]534e54b2008-08-13 15:40:091432 controller_id = window_map_[window_or_tab];
initial.commit09911bf2008-07-26 23:55:291433 }
[email protected]534e54b2008-08-13 15:40:091434 DCHECK(controller_id != -1);
initial.commit09911bf2008-07-26 23:55:291435
1436 switch (type) {
[email protected]534e54b2008-08-13 15:40:091437 case NOTIFY_TAB_PARENTED:
initial.commit09911bf2008-07-26 23:55:291438 case NOTIFY_BROWSER_OPENED:
1439 window_type = MetricsLog::WINDOW_CREATE;
1440 break;
1441
1442 case NOTIFY_TAB_CLOSING:
1443 case NOTIFY_BROWSER_CLOSED:
[email protected]534e54b2008-08-13 15:40:091444 window_map_.erase(window_map_.find(window_or_tab));
initial.commit09911bf2008-07-26 23:55:291445 window_type = MetricsLog::WINDOW_DESTROY;
1446 break;
1447
1448 default:
1449 NOTREACHED();
1450 break;
1451 }
1452
[email protected]534e54b2008-08-13 15:40:091453 // TODO(brettw) we should have some kind of ID for the parent.
1454 current_log_->RecordWindowEvent(window_type, controller_id, 0);
initial.commit09911bf2008-07-26 23:55:291455}
1456
1457void MetricsService::LogLoadComplete(NotificationType type,
1458 const NotificationSource& source,
1459 const NotificationDetails& details) {
1460 if (details == NotificationService::NoDetails())
1461 return;
1462
[email protected]68475e602008-08-22 03:21:151463 // TODO(jar): There is a bug causing this to be called too many times, and
1464 // the log overflows. For now, we won't record these events.
1465 UMA_HISTOGRAM_COUNTS(L"UMA.LogLoadComplete called", 1);
1466 return;
1467
initial.commit09911bf2008-07-26 23:55:291468 const Details<LoadNotificationDetails> load_details(details);
[email protected]534e54b2008-08-13 15:40:091469 int controller_id = window_map_[details.map_key()];
1470 current_log_->RecordLoadEvent(controller_id,
initial.commit09911bf2008-07-26 23:55:291471 load_details->url(),
1472 load_details->origin(),
1473 load_details->session_index(),
1474 load_details->load_time());
1475}
1476
[email protected]e73c01972008-08-13 00:18:241477void MetricsService::IncrementPrefValue(const wchar_t* path) {
1478 PrefService* pref = g_browser_process->local_state();
1479 DCHECK(pref);
1480 int value = pref->GetInteger(path);
1481 pref->SetInteger(path, value + 1);
1482}
1483
initial.commit09911bf2008-07-26 23:55:291484void MetricsService::LogLoadStarted() {
[email protected]e73c01972008-08-13 00:18:241485 IncrementPrefValue(prefs::kStabilityPageLoadCount);
[email protected]0b33f80b2008-12-17 21:34:361486 // We need to save the prefs, as page load count is a critical stat, and it
1487 // might be lost due to a crash :-(.
initial.commit09911bf2008-07-26 23:55:291488}
1489
1490void MetricsService::LogRendererInSandbox(bool on_sandbox_desktop) {
1491 PrefService* prefs = g_browser_process->local_state();
1492 DCHECK(prefs);
[email protected]e73c01972008-08-13 00:18:241493 if (on_sandbox_desktop)
1494 IncrementPrefValue(prefs::kSecurityRendererOnSboxDesktop);
1495 else
1496 IncrementPrefValue(prefs::kSecurityRendererOnDefaultDesktop);
initial.commit09911bf2008-07-26 23:55:291497}
1498
1499void MetricsService::LogRendererCrash() {
[email protected]e73c01972008-08-13 00:18:241500 IncrementPrefValue(prefs::kStabilityRendererCrashCount);
initial.commit09911bf2008-07-26 23:55:291501}
1502
1503void MetricsService::LogRendererHang() {
[email protected]e73c01972008-08-13 00:18:241504 IncrementPrefValue(prefs::kStabilityRendererHangCount);
initial.commit09911bf2008-07-26 23:55:291505}
1506
1507void MetricsService::LogPluginChange(NotificationType type,
1508 const NotificationSource& source,
1509 const NotificationDetails& details) {
1510 std::wstring plugin = Details<PluginProcessInfo>(details)->dll_path();
1511
1512 if (plugin_stats_buffer_.find(plugin) == plugin_stats_buffer_.end()) {
1513 plugin_stats_buffer_[plugin] = PluginStats();
1514 }
1515
1516 PluginStats& stats = plugin_stats_buffer_[plugin];
1517 switch (type) {
1518 case NOTIFY_PLUGIN_PROCESS_HOST_CONNECTED:
1519 stats.process_launches++;
1520 break;
1521
1522 case NOTIFY_PLUGIN_INSTANCE_CREATED:
1523 stats.instances++;
1524 break;
1525
1526 case NOTIFY_PLUGIN_PROCESS_CRASHED:
1527 stats.process_crashes++;
1528 break;
1529
1530 default:
1531 NOTREACHED() << "Unexpected notification type " << type;
1532 return;
1533 }
1534}
1535
1536// Recursively counts the number of bookmarks and folders in node.
[email protected]d8e41ed2008-09-11 15:22:321537static void CountBookmarks(BookmarkNode* node, int* bookmarks, int* folders) {
initial.commit09911bf2008-07-26 23:55:291538 if (node->GetType() == history::StarredEntry::URL)
1539 (*bookmarks)++;
1540 else
1541 (*folders)++;
1542 for (int i = 0; i < node->GetChildCount(); ++i)
1543 CountBookmarks(node->GetChild(i), bookmarks, folders);
1544}
1545
[email protected]d8e41ed2008-09-11 15:22:321546void MetricsService::LogBookmarks(BookmarkNode* node,
initial.commit09911bf2008-07-26 23:55:291547 const wchar_t* num_bookmarks_key,
1548 const wchar_t* num_folders_key) {
1549 DCHECK(node);
1550 int num_bookmarks = 0;
1551 int num_folders = 0;
1552 CountBookmarks(node, &num_bookmarks, &num_folders);
1553 num_folders--; // Don't include the root folder in the count.
1554
1555 PrefService* pref = g_browser_process->local_state();
1556 DCHECK(pref);
1557 pref->SetInteger(num_bookmarks_key, num_bookmarks);
1558 pref->SetInteger(num_folders_key, num_folders);
1559}
1560
[email protected]d8e41ed2008-09-11 15:22:321561void MetricsService::LogBookmarks(BookmarkModel* model) {
initial.commit09911bf2008-07-26 23:55:291562 DCHECK(model);
1563 LogBookmarks(model->GetBookmarkBarNode(),
1564 prefs::kNumBookmarksOnBookmarkBar,
1565 prefs::kNumFoldersOnBookmarkBar);
1566 LogBookmarks(model->other_node(),
1567 prefs::kNumBookmarksInOtherBookmarkFolder,
1568 prefs::kNumFoldersInOtherBookmarkFolder);
1569 ScheduleNextStateSave();
1570}
1571
1572void MetricsService::LogKeywords(const TemplateURLModel* url_model) {
1573 DCHECK(url_model);
1574
1575 PrefService* pref = g_browser_process->local_state();
1576 DCHECK(pref);
1577 pref->SetInteger(prefs::kNumKeywords,
1578 static_cast<int>(url_model->GetTemplateURLs().size()));
1579 ScheduleNextStateSave();
1580}
1581
1582void MetricsService::RecordPluginChanges(PrefService* pref) {
1583 ListValue* plugins = pref->GetMutableList(prefs::kStabilityPluginStats);
1584 DCHECK(plugins);
1585
1586 for (ListValue::iterator value_iter = plugins->begin();
1587 value_iter != plugins->end(); ++value_iter) {
1588 if (!(*value_iter)->IsType(Value::TYPE_DICTIONARY)) {
1589 NOTREACHED();
1590 continue;
1591 }
1592
1593 DictionaryValue* plugin_dict = static_cast<DictionaryValue*>(*value_iter);
1594 std::wstring plugin_path;
1595 plugin_dict->GetString(prefs::kStabilityPluginPath, &plugin_path);
1596 if (plugin_path.empty()) {
1597 NOTREACHED();
1598 continue;
1599 }
1600
1601 if (plugin_stats_buffer_.find(plugin_path) == plugin_stats_buffer_.end())
1602 continue;
1603
1604 PluginStats stats = plugin_stats_buffer_[plugin_path];
1605 if (stats.process_launches) {
1606 int launches = 0;
1607 plugin_dict->GetInteger(prefs::kStabilityPluginLaunches, &launches);
1608 launches += stats.process_launches;
1609 plugin_dict->SetInteger(prefs::kStabilityPluginLaunches, launches);
1610 }
1611 if (stats.process_crashes) {
1612 int crashes = 0;
1613 plugin_dict->GetInteger(prefs::kStabilityPluginCrashes, &crashes);
1614 crashes += stats.process_crashes;
1615 plugin_dict->SetInteger(prefs::kStabilityPluginCrashes, crashes);
1616 }
1617 if (stats.instances) {
1618 int instances = 0;
1619 plugin_dict->GetInteger(prefs::kStabilityPluginInstances, &instances);
1620 instances += stats.instances;
1621 plugin_dict->SetInteger(prefs::kStabilityPluginInstances, instances);
1622 }
1623
1624 plugin_stats_buffer_.erase(plugin_path);
1625 }
1626
1627 // Now go through and add dictionaries for plugins that didn't already have
1628 // reports in Local State.
1629 for (std::map<std::wstring, PluginStats>::iterator cache_iter =
1630 plugin_stats_buffer_.begin();
1631 cache_iter != plugin_stats_buffer_.end(); ++cache_iter) {
1632 std::wstring plugin_path = cache_iter->first;
1633 PluginStats stats = cache_iter->second;
1634 DictionaryValue* plugin_dict = new DictionaryValue;
1635
1636 plugin_dict->SetString(prefs::kStabilityPluginPath, plugin_path);
1637 plugin_dict->SetInteger(prefs::kStabilityPluginLaunches,
1638 stats.process_launches);
1639 plugin_dict->SetInteger(prefs::kStabilityPluginCrashes,
1640 stats.process_crashes);
1641 plugin_dict->SetInteger(prefs::kStabilityPluginInstances,
1642 stats.instances);
1643 plugins->Append(plugin_dict);
1644 }
1645 plugin_stats_buffer_.clear();
1646}
1647
1648bool MetricsService::CanLogNotification(NotificationType type,
1649 const NotificationSource& source,
1650 const NotificationDetails& details) {
1651 // We simply don't log anything to UMA if there is a single off the record
1652 // session visible. The problem is that we always notify using the orginal
1653 // profile in order to simplify notification processing.
1654 return !BrowserList::IsOffTheRecordSessionActive();
1655}
1656
1657void MetricsService::RecordBooleanPrefValue(const wchar_t* path, bool value) {
1658 DCHECK(IsSingleThreaded());
1659
1660 PrefService* pref = g_browser_process->local_state();
1661 DCHECK(pref);
1662
1663 pref->SetBoolean(path, value);
1664 RecordCurrentState(pref);
1665}
1666
1667void MetricsService::RecordCurrentState(PrefService* pref) {
1668 pref->SetString(prefs::kStabilityLastTimestampSec,
1669 Int64ToWString(Time::Now().ToTimeT()));
1670
1671 RecordPluginChanges(pref);
1672}
1673
1674void MetricsService::RecordCurrentHistograms() {
1675 DCHECK(current_log_);
1676
1677 StatisticsRecorder::Histograms histograms;
1678 StatisticsRecorder::GetHistograms(&histograms);
1679 for (StatisticsRecorder::Histograms::iterator it = histograms.begin();
1680 histograms.end() != it;
[email protected]cac78842008-11-27 01:02:201681 ++it) {
initial.commit09911bf2008-07-26 23:55:291682 if ((*it)->flags() & kUmaTargetedHistogramFlag)
[email protected]0b33f80b2008-12-17 21:34:361683 // TODO(petersont): Only record historgrams if they are not precluded by
1684 // the UMA response data.
[email protected]d01b8732008-10-16 02:18:071685 // Bug http://code.google.com/p/chromium/issues/detail?id=2739.
initial.commit09911bf2008-07-26 23:55:291686 RecordHistogram(**it);
1687 }
1688}
1689
1690void MetricsService::RecordHistogram(const Histogram& histogram) {
1691 // Get up-to-date snapshot of sample stats.
1692 Histogram::SampleSet snapshot;
1693 histogram.SnapshotSample(&snapshot);
1694
1695 const std::string& histogram_name = histogram.histogram_name();
1696
1697 // Find the already sent stats, or create an empty set.
1698 LoggedSampleMap::iterator it = logged_samples_.find(histogram_name);
1699 Histogram::SampleSet* already_logged;
1700 if (logged_samples_.end() == it) {
1701 // Add new entry
1702 already_logged = &logged_samples_[histogram.histogram_name()];
1703 already_logged->Resize(histogram); // Complete initialization.
1704 } else {
1705 already_logged = &(it->second);
1706 // Deduct any stats we've already logged from our snapshot.
1707 snapshot.Subtract(*already_logged);
1708 }
1709
1710 // snapshot now contains only a delta to what we've already_logged.
1711
1712 if (snapshot.TotalCount() > 0) {
1713 current_log_->RecordHistogramDelta(histogram, snapshot);
1714 // Add new data into our running total.
1715 already_logged->Add(snapshot);
1716 }
1717}
1718
1719void MetricsService::AddProfileMetric(Profile* profile,
1720 const std::wstring& key,
1721 int value) {
1722 // Restriction of types is needed for writing values. See
1723 // MetricsLog::WriteProfileMetrics.
1724 DCHECK(profile && !key.empty());
1725 PrefService* prefs = g_browser_process->local_state();
1726 DCHECK(prefs);
1727
1728 // Key is stored in prefs, which interpret '.'s as paths. As such, key
1729 // shouldn't have any '.'s in it.
1730 DCHECK(key.find(L'.') == std::wstring::npos);
1731 // The id is most likely an email address. We shouldn't send it to the server.
1732 const std::wstring id_hash =
1733 UTF8ToWide(MetricsLog::CreateBase64Hash(WideToUTF8(profile->GetID())));
1734 DCHECK(id_hash.find('.') == std::string::npos);
1735
1736 DictionaryValue* prof_prefs = prefs->GetMutableDictionary(
1737 prefs::kProfileMetrics);
1738 DCHECK(prof_prefs);
1739 const std::wstring pref_key = std::wstring(prefs::kProfilePrefix) + id_hash +
1740 L"." + key;
1741 prof_prefs->SetInteger(pref_key.c_str(), value);
1742}
1743
1744static bool IsSingleThreaded() {
1745 static int thread_id = 0;
1746 if (!thread_id)
1747 thread_id = GetCurrentThreadId();
1748 return GetCurrentThreadId() == thread_id;
1749}