blob: b25b5b1d3e4f3ad687f44d63deb22c726ea46f68 [file] [log] [blame]
license.botbf09a502008-08-24 00:55:551// Copyright (c) 2006-2008 The Chromium Authors. All rights reserved.
2// Use of this source code is governed by a BSD-style license that can be
3// found in the LICENSE file.
initial.commit09911bf2008-07-26 23:55:294
5
6
7//------------------------------------------------------------------------------
8// Description of the life cycle of a instance of MetricsService.
9//
10// OVERVIEW
11//
12// A MetricsService instance is typically created at application startup. It
13// is the central controller for the acquisition of log data, and the automatic
14// transmission of that log data to an external server. Its major job is to
15// manage logs, grouping them for transmission, and transmitting them. As part
16// of its grouping, MS finalizes logs by including some just-in-time gathered
17// memory statistics, snapshotting the current stats of numerous histograms,
18// closing the logs, translating to XML text, and compressing the results for
19// transmission. Transmission includes submitting a compressed log as data in a
[email protected]281d2882009-01-20 20:32:4220// URL-post, and retransmitting (or retaining at process termination) if the
initial.commit09911bf2008-07-26 23:55:2921// attempted transmission failed. Retention across process terminations is done
22// using the the PrefServices facilities. The format for the retained
23// logs (ones that never got transmitted) is always the uncompressed textual
24// representation.
25//
[email protected]281d2882009-01-20 20:32:4226// Logs fall into one of two categories: "initial logs," and "ongoing logs."
27// There is at most one initial log sent for each complete run of the chromium
initial.commit09911bf2008-07-26 23:55:2928// product (from startup, to browser shutdown). An initial log is generally
29// transmitted some short time (1 minute?) after startup, and includes stats
30// such as recent crash info, the number and types of plugins, etc. The
[email protected]281d2882009-01-20 20:32:4231// external server's response to the initial log conceptually tells this MS if
32// it should continue transmitting logs (during this session). The server
33// response can actually be much more detailed, and always includes (at a
34// minimum) how often additional ongoing logs should be sent.
initial.commit09911bf2008-07-26 23:55:2935//
36// After the above initial log, a series of ongoing logs will be transmitted.
37// The first ongoing log actually begins to accumulate information stating when
38// the MS was first constructed. Note that even though the initial log is
39// commonly sent a full minute after startup, the initial log does not include
40// much in the way of user stats. The most common interlog period (delay)
[email protected]0b33f80b2008-12-17 21:34:3641// is 20 minutes. That time period starts when the first user action causes a
initial.commit09911bf2008-07-26 23:55:2942// logging event. This means that if there is no user action, there may be long
[email protected]281d2882009-01-20 20:32:4243// periods without any (ongoing) log transmissions. Ongoing logs typically
initial.commit09911bf2008-07-26 23:55:2944// contain very detailed records of user activities (ex: opened tab, closed
45// tab, fetched URL, maximized window, etc.) In addition, just before an
46// ongoing log is closed out, a call is made to gather memory statistics. Those
47// memory statistics are deposited into a histogram, and the log finalization
48// code is then called. In the finalization, a call to a Histogram server
49// acquires a list of all local histograms that have been flagged for upload
[email protected]281d2882009-01-20 20:32:4250// to the UMA server. The finalization also acquires a the most recent number
51// of page loads, along with any counts of renderer or plugin crashes.
initial.commit09911bf2008-07-26 23:55:2952//
53// When the browser shuts down, there will typically be a fragment of an ongoing
54// log that has not yet been transmitted. At shutdown time, that fragment
55// is closed (including snapshotting histograms), and converted to text. Note
56// that memory stats are not gathered during shutdown, as gathering *might* be
57// too time consuming. The textual representation of the fragment of the
58// ongoing log is then stored persistently as a string in the PrefServices, for
59// potential transmission during a future run of the product.
60//
61// There are two slightly abnormal shutdown conditions. There is a
62// "disconnected scenario," and a "really fast startup and shutdown" scenario.
63// In the "never connected" situation, the user has (during the running of the
64// process) never established an internet connection. As a result, attempts to
65// transmit the initial log have failed, and a lot(?) of data has accumulated in
66// the ongoing log (which didn't yet get closed, because there was never even a
67// contemplation of sending it). There is also a kindred "lost connection"
68// situation, where a loss of connection prevented an ongoing log from being
69// transmitted, and a (still open) log was stuck accumulating a lot(?) of data,
70// while the earlier log retried its transmission. In both of these
71// disconnected situations, two logs need to be, and are, persistently stored
72// for future transmission.
73//
74// The other unusual shutdown condition, termed "really fast startup and
75// shutdown," involves the deliberate user termination of the process before
76// the initial log is even formed or transmitted. In that situation, no logging
77// is done, but the historical crash statistics remain (unlogged) for inclusion
78// in a future run's initial log. (i.e., we don't lose crash stats).
79//
80// With the above overview, we can now describe the state machine's various
81// stats, based on the State enum specified in the state_ member. Those states
82// are:
83//
84// INITIALIZED, // Constructor was called.
[email protected]28ab7f92009-01-06 21:39:0485// PLUGIN_LIST_REQUESTED, // Waiting for plugin list to be loaded.
initial.commit09911bf2008-07-26 23:55:2986// PLUGIN_LIST_ARRIVED, // Waiting for timer to send initial log.
87// INITIAL_LOG_READY, // Initial log generated, and waiting for reply.
88// SEND_OLD_INITIAL_LOGS, // Sending unsent logs from previous session.
89// SENDING_OLD_LOGS, // Sending unsent logs from previous session.
90// SENDING_CURRENT_LOGS, // Sending standard current logs as they accrue.
91//
92// In more detail, we have:
93//
94// INITIALIZED, // Constructor was called.
95// The MS has been constructed, but has taken no actions to compose the
96// initial log.
97//
[email protected]28ab7f92009-01-06 21:39:0498// PLUGIN_LIST_REQUESTED, // Waiting for plugin list to be loaded.
initial.commit09911bf2008-07-26 23:55:2999// Typically about 30 seconds after startup, a task is sent to a second thread
100// to get the list of plugins. That task will (when complete) make an async
101// callback (via a Task) to indicate the completion.
102//
103// PLUGIN_LIST_ARRIVED, // Waiting for timer to send initial log.
104// The callback has arrived, and it is now possible for an initial log to be
105// created. This callback typically arrives back less than one second after
106// the task is dispatched.
107//
108// INITIAL_LOG_READY, // Initial log generated, and waiting for reply.
109// This state is entered only after an initial log has been composed, and
110// prepared for transmission. It is also the case that any previously unsent
111// logs have been loaded into instance variables for possible transmission.
112//
113// SEND_OLD_INITIAL_LOGS, // Sending unsent logs from previous session.
114// This state indicates that the initial log for this session has been
115// successfully sent and it is now time to send any "initial logs" that were
116// saved from previous sessions. Most commonly, there are none, but all old
117// logs that were "initial logs" must be sent before this state is exited.
118//
119// SENDING_OLD_LOGS, // Sending unsent logs from previous session.
120// This state indicates that there are no more unsent initial logs, and now any
121// ongoing logs from previous sessions should be transmitted. All such logs
122// will be transmitted before exiting this state, and proceeding with ongoing
123// logs from the current session (see next state).
124//
125// SENDING_CURRENT_LOGS, // Sending standard current logs as they accrue.
[email protected]0b33f80b2008-12-17 21:34:36126// Current logs are being accumulated. Typically every 20 minutes a log is
initial.commit09911bf2008-07-26 23:55:29127// closed and finalized for transmission, at the same time as a new log is
128// started.
129//
130// The progression through the above states is simple, and sequential, in the
131// most common use cases. States proceed from INITIAL to SENDING_CURRENT_LOGS,
132// and remain in the latter until shutdown.
133//
134// The one unusual case is when the user asks that we stop logging. When that
135// happens, any pending (transmission in progress) log is pushed into the list
136// of old unsent logs (the appropriate list, depending on whether it is an
137// initial log, or an ongoing log). An addition, any log that is currently
138// accumulating is also finalized, and pushed into the unsent log list. With
[email protected]281d2882009-01-20 20:32:42139// those pushes performed, we regress back to the SEND_OLD_INITIAL_LOGS state in
initial.commit09911bf2008-07-26 23:55:29140// case the user enables log recording again during this session. This way
141// anything we have "pushed back" will be sent automatically if/when we progress
142// back to SENDING_CURRENT_LOG state.
143//
144// Also note that whenever the member variables containing unsent logs are
145// modified (i.e., when we send an old log), we mirror the list of logs into
146// the PrefServices. This ensures that IF we crash, we won't start up and
147// retransmit our old logs again.
148//
149// Due to race conditions, it is always possible that a log file could be sent
150// twice. For example, if a log file is sent, but not yet acknowledged by
151// the external server, and the user shuts down, then a copy of the log may be
152// saved for re-transmission. These duplicates could be filtered out server
[email protected]281d2882009-01-20 20:32:42153// side, but are not expected to be a significant problem.
initial.commit09911bf2008-07-26 23:55:29154//
155//
156//------------------------------------------------------------------------------
157
158#include <windows.h>
159
[email protected]cd1adc22009-01-16 01:29:22160#include "chrome/browser/metrics/metrics_service.h"
initial.commit09911bf2008-07-26 23:55:29161
[email protected]690a99c2009-01-06 16:48:45162#include "base/file_path.h"
initial.commit09911bf2008-07-26 23:55:29163#include "base/histogram.h"
164#include "base/path_service.h"
165#include "base/string_util.h"
166#include "base/task.h"
[email protected]d8e41ed2008-09-11 15:22:32167#include "chrome/browser/bookmarks/bookmark_model.h"
initial.commit09911bf2008-07-26 23:55:29168#include "chrome/browser/browser.h"
169#include "chrome/browser/browser_list.h"
170#include "chrome/browser/browser_process.h"
171#include "chrome/browser/load_notification_details.h"
172#include "chrome/browser/memory_details.h"
173#include "chrome/browser/plugin_process_info.h"
174#include "chrome/browser/plugin_service.h"
175#include "chrome/browser/profile.h"
[email protected]8c8657d62009-01-16 18:31:26176#include "chrome/browser/renderer_host/render_process_host.h"
[email protected]d54e03a52009-01-16 00:31:04177#include "chrome/browser/search_engines/template_url.h"
178#include "chrome/browser/search_engines/template_url_model.h"
initial.commit09911bf2008-07-26 23:55:29179#include "chrome/common/chrome_paths.h"
[email protected]252873ef2008-08-04 21:59:45180#include "chrome/common/libxml_utils.h"
[email protected]bfd04a62009-02-01 18:16:56181#include "chrome/common/notification_service.h"
initial.commit09911bf2008-07-26 23:55:29182#include "chrome/common/pref_names.h"
183#include "chrome/common/pref_service.h"
[email protected]e09ba552009-02-05 03:26:29184#include "chrome/common/render_messages.h"
[email protected]6e93e522008-08-14 19:28:17185#include "chrome/installer/util/google_update_settings.h"
initial.commit09911bf2008-07-26 23:55:29186#include "googleurl/src/gurl.h"
187#include "net/base/load_flags.h"
188#include "third_party/bzip2/bzlib.h"
189
[email protected]e1acf6f2008-10-27 20:43:33190using base::Time;
191using base::TimeDelta;
192
initial.commit09911bf2008-07-26 23:55:29193// Check to see that we're being called on only one thread.
194static bool IsSingleThreaded();
195
196static const char kMetricsURL[] =
[email protected]0acdfc42009-01-30 01:13:22197 "https://clients4.google.com/firefox/metrics/collect";
initial.commit09911bf2008-07-26 23:55:29198
199static const char kMetricsType[] = "application/vnd.mozilla.metrics.bz2";
200
201// The delay, in seconds, after startup before sending the first log message.
[email protected]252873ef2008-08-04 21:59:45202static const int kInitialInterlogDuration = 60; // one minute
203
204// The default maximum number of events in a log uploaded to the UMA server.
[email protected]0b33f80b2008-12-17 21:34:36205static const int kInitialEventLimit = 2400;
[email protected]68475e602008-08-22 03:21:15206
207// If an upload fails, and the transmission was over this byte count, then we
208// will discard the log, and not try to retransmit it. We also don't persist
209// the log to the prefs for transmission during the next chrome session if this
210// limit is exceeded.
211static const int kUploadLogAvoidRetransmitSize = 50000;
initial.commit09911bf2008-07-26 23:55:29212
213// When we have logs from previous Chrome sessions to send, how long should we
214// delay (in seconds) between each log transmission.
215static const int kUnsentLogDelay = 15; // 15 seconds
216
217// Minimum time a log typically exists before sending, in seconds.
218// This number is supplied by the server, but until we parse it out of a server
219// response, we use this duration to specify how long we should wait before
220// sending the next log. If the channel is busy, such as when there is a
221// failure during an attempt to transmit a previous log, then a log may wait
222// (and continue to accrue now log entries) for a much greater period of time.
[email protected]0eb34fee2009-01-21 08:04:38223static const int kMinSecondsPerLog = 20 * 60; // Twenty minutes.
initial.commit09911bf2008-07-26 23:55:29224
initial.commit09911bf2008-07-26 23:55:29225// When we don't succeed at transmitting a log to a server, we progressively
226// wait longer and longer before sending the next log. This backoff process
227// help reduce load on the server, and makes the amount of backoff vary between
228// clients so that a collision (server overload?) on retransmit is less likely.
229// The following is the constant we use to expand that inter-log duration.
230static const double kBackoff = 1.1;
231// We limit the maximum backoff to be no greater than some multiple of the
232// default kMinSecondsPerLog. The following is that maximum ratio.
233static const int kMaxBackoff = 10;
234
235// Interval, in seconds, between state saves.
236static const int kSaveStateInterval = 5 * 60; // five minutes
237
238// The number of "initial" logs we're willing to save, and hope to send during
239// a future Chrome session. Initial logs contain crash stats, and are pretty
240// small.
241static const size_t kMaxInitialLogsPersisted = 20;
242
243// The number of ongoing logs we're willing to save persistently, and hope to
[email protected]281d2882009-01-20 20:32:42244// send during a this or future sessions. Note that each log may be pretty
initial.commit09911bf2008-07-26 23:55:29245// large, as presumably the related "initial" log wasn't sent (probably nothing
246// was, as the user was probably off-line). As a result, the log probably kept
247// accumulating while the "initial" log was stalled (pending_), and couldn't be
248// sent. As a result, we don't want to save too many of these mega-logs.
249// A "standard shutdown" will create a small log, including just the data that
250// was not yet been transmitted, and that is normal (to have exactly one
251// ongoing_log_ at startup).
[email protected]281d2882009-01-20 20:32:42252static const size_t kMaxOngoingLogsPersisted = 8;
initial.commit09911bf2008-07-26 23:55:29253
254
255// Handles asynchronous fetching of memory details.
256// Will run the provided task after finished.
257class MetricsMemoryDetails : public MemoryDetails {
258 public:
259 explicit MetricsMemoryDetails(Task* completion) : completion_(completion) {}
260
261 virtual void OnDetailsAvailable() {
262 MessageLoop::current()->PostTask(FROM_HERE, completion_);
263 }
264
265 private:
266 Task* completion_;
267 DISALLOW_EVIL_CONSTRUCTORS(MetricsMemoryDetails);
268};
269
270class MetricsService::GetPluginListTaskComplete : public Task {
271 virtual void Run() {
272 g_browser_process->metrics_service()->OnGetPluginListTaskComplete();
273 }
274};
275
276class MetricsService::GetPluginListTask : public Task {
277 public:
278 explicit GetPluginListTask(MessageLoop* callback_loop)
279 : callback_loop_(callback_loop) {}
280
281 virtual void Run() {
282 std::vector<WebPluginInfo> plugins;
283 PluginService::GetInstance()->GetPlugins(false, &plugins);
284
285 callback_loop_->PostTask(FROM_HERE, new GetPluginListTaskComplete());
286 }
287
288 private:
289 MessageLoop* callback_loop_;
290};
291
292// static
293void MetricsService::RegisterPrefs(PrefService* local_state) {
294 DCHECK(IsSingleThreaded());
295 local_state->RegisterStringPref(prefs::kMetricsClientID, L"");
296 local_state->RegisterStringPref(prefs::kMetricsClientIDTimestamp, L"0");
297 local_state->RegisterStringPref(prefs::kStabilityLaunchTimeSec, L"0");
298 local_state->RegisterStringPref(prefs::kStabilityLastTimestampSec, L"0");
299 local_state->RegisterStringPref(prefs::kStabilityUptimeSec, L"0");
300 local_state->RegisterBooleanPref(prefs::kStabilityExitedCleanly, true);
301 local_state->RegisterBooleanPref(prefs::kStabilitySessionEndCompleted, true);
302 local_state->RegisterIntegerPref(prefs::kMetricsSessionID, -1);
303 local_state->RegisterIntegerPref(prefs::kStabilityLaunchCount, 0);
304 local_state->RegisterIntegerPref(prefs::kStabilityCrashCount, 0);
305 local_state->RegisterIntegerPref(prefs::kStabilityIncompleteSessionEndCount,
306 0);
307 local_state->RegisterIntegerPref(prefs::kStabilityPageLoadCount, 0);
308 local_state->RegisterIntegerPref(prefs::kSecurityRendererOnSboxDesktop, 0);
309 local_state->RegisterIntegerPref(prefs::kSecurityRendererOnDefaultDesktop, 0);
310 local_state->RegisterIntegerPref(prefs::kStabilityRendererCrashCount, 0);
311 local_state->RegisterIntegerPref(prefs::kStabilityRendererHangCount, 0);
[email protected]e73c01972008-08-13 00:18:24312 local_state->RegisterIntegerPref(prefs::kStabilityBreakpadRegistrationFail,
313 0);
314 local_state->RegisterIntegerPref(prefs::kStabilityBreakpadRegistrationSuccess,
315 0);
316 local_state->RegisterIntegerPref(prefs::kStabilityDebuggerPresent, 0);
317 local_state->RegisterIntegerPref(prefs::kStabilityDebuggerNotPresent, 0);
318
initial.commit09911bf2008-07-26 23:55:29319 local_state->RegisterDictionaryPref(prefs::kProfileMetrics);
320 local_state->RegisterIntegerPref(prefs::kNumBookmarksOnBookmarkBar, 0);
321 local_state->RegisterIntegerPref(prefs::kNumFoldersOnBookmarkBar, 0);
322 local_state->RegisterIntegerPref(prefs::kNumBookmarksInOtherBookmarkFolder,
323 0);
324 local_state->RegisterIntegerPref(prefs::kNumFoldersInOtherBookmarkFolder, 0);
325 local_state->RegisterIntegerPref(prefs::kNumKeywords, 0);
326 local_state->RegisterListPref(prefs::kMetricsInitialLogs);
327 local_state->RegisterListPref(prefs::kMetricsOngoingLogs);
328}
329
330MetricsService::MetricsService()
[email protected]d01b8732008-10-16 02:18:07331 : recording_active_(false),
332 reporting_active_(false),
333 user_permits_upload_(false),
334 server_permits_upload_(true),
335 state_(INITIALIZED),
initial.commit09911bf2008-07-26 23:55:29336 pending_log_(NULL),
337 pending_log_text_(""),
338 current_fetch_(NULL),
339 current_log_(NULL),
[email protected]d01b8732008-10-16 02:18:07340 idle_since_last_transmission_(false),
initial.commit09911bf2008-07-26 23:55:29341 next_window_id_(0),
342 log_sender_factory_(this),
343 state_saver_factory_(this),
344 logged_samples_(),
[email protected]252873ef2008-08-04 21:59:45345 interlog_duration_(TimeDelta::FromSeconds(kInitialInterlogDuration)),
[email protected]d01b8732008-10-16 02:18:07346 log_event_limit_(kInitialEventLimit),
initial.commit09911bf2008-07-26 23:55:29347 timer_pending_(false) {
348 DCHECK(IsSingleThreaded());
349 InitializeMetricsState();
350}
351
352MetricsService::~MetricsService() {
353 SetRecording(false);
[email protected]d8bc79bf2009-01-28 01:17:58354 if (pending_log_) {
355 delete pending_log_;
356 pending_log_ = NULL;
357 }
358 if (current_log_) {
359 delete current_log_;
360 current_log_ = NULL;
361 }
initial.commit09911bf2008-07-26 23:55:29362}
363
[email protected]d01b8732008-10-16 02:18:07364void MetricsService::SetUserPermitsUpload(bool enabled) {
365 HandleIdleSinceLastTransmission(false);
366 user_permits_upload_ = enabled;
367}
368
369void MetricsService::Start() {
370 SetRecording(true);
371 SetReporting(true);
372}
373
374void MetricsService::StartRecordingOnly() {
375 SetRecording(true);
376 SetReporting(false);
377}
378
379void MetricsService::Stop() {
380 SetReporting(false);
381 SetRecording(false);
382}
383
initial.commit09911bf2008-07-26 23:55:29384void MetricsService::SetRecording(bool enabled) {
385 DCHECK(IsSingleThreaded());
386
[email protected]d01b8732008-10-16 02:18:07387 if (enabled == recording_active_)
initial.commit09911bf2008-07-26 23:55:29388 return;
389
390 if (enabled) {
391 StartRecording();
392 ListenerRegistration(true);
393 } else {
394 // Turn off all observers.
395 ListenerRegistration(false);
396 PushPendingLogsToUnsentLists();
397 DCHECK(!pending_log());
398 if (state_ > INITIAL_LOG_READY && unsent_logs())
399 state_ = SEND_OLD_INITIAL_LOGS;
400 }
[email protected]d01b8732008-10-16 02:18:07401 recording_active_ = enabled;
initial.commit09911bf2008-07-26 23:55:29402}
403
[email protected]d01b8732008-10-16 02:18:07404bool MetricsService::recording_active() const {
initial.commit09911bf2008-07-26 23:55:29405 DCHECK(IsSingleThreaded());
[email protected]d01b8732008-10-16 02:18:07406 return recording_active_;
initial.commit09911bf2008-07-26 23:55:29407}
408
[email protected]d01b8732008-10-16 02:18:07409void MetricsService::SetReporting(bool enable) {
410 if (reporting_active_ != enable) {
411 reporting_active_ = enable;
412 if (reporting_active_)
initial.commit09911bf2008-07-26 23:55:29413 StartLogTransmissionTimer();
414 }
[email protected]d01b8732008-10-16 02:18:07415}
416
417bool MetricsService::reporting_active() const {
418 DCHECK(IsSingleThreaded());
419 return reporting_active_;
initial.commit09911bf2008-07-26 23:55:29420}
421
422void MetricsService::Observe(NotificationType type,
423 const NotificationSource& source,
424 const NotificationDetails& details) {
425 DCHECK(current_log_);
426 DCHECK(IsSingleThreaded());
427
428 if (!CanLogNotification(type, source, details))
429 return;
430
[email protected]bfd04a62009-02-01 18:16:56431 switch (type.value) {
432 case NotificationType::USER_ACTION:
initial.commit09911bf2008-07-26 23:55:29433 current_log_->RecordUserAction(*Details<const wchar_t*>(details).ptr());
434 break;
435
[email protected]bfd04a62009-02-01 18:16:56436 case NotificationType::BROWSER_OPENED:
437 case NotificationType::BROWSER_CLOSED:
initial.commit09911bf2008-07-26 23:55:29438 LogWindowChange(type, source, details);
439 break;
440
[email protected]bfd04a62009-02-01 18:16:56441 case NotificationType::TAB_PARENTED:
442 case NotificationType::TAB_CLOSING:
initial.commit09911bf2008-07-26 23:55:29443 LogWindowChange(type, source, details);
444 break;
445
[email protected]bfd04a62009-02-01 18:16:56446 case NotificationType::LOAD_STOP:
initial.commit09911bf2008-07-26 23:55:29447 LogLoadComplete(type, source, details);
448 break;
449
[email protected]bfd04a62009-02-01 18:16:56450 case NotificationType::LOAD_START:
initial.commit09911bf2008-07-26 23:55:29451 LogLoadStarted();
452 break;
453
[email protected]bfd04a62009-02-01 18:16:56454 case NotificationType::RENDERER_PROCESS_TERMINATED:
initial.commit09911bf2008-07-26 23:55:29455 if (!*Details<bool>(details).ptr())
456 LogRendererCrash();
457 break;
458
[email protected]bfd04a62009-02-01 18:16:56459 case NotificationType::RENDERER_PROCESS_HANG:
initial.commit09911bf2008-07-26 23:55:29460 LogRendererHang();
461 break;
462
[email protected]bfd04a62009-02-01 18:16:56463 case NotificationType::RENDERER_PROCESS_IN_SBOX:
initial.commit09911bf2008-07-26 23:55:29464 LogRendererInSandbox(*Details<bool>(details).ptr());
465 break;
466
[email protected]bfd04a62009-02-01 18:16:56467 case NotificationType::PLUGIN_PROCESS_HOST_CONNECTED:
468 case NotificationType::PLUGIN_PROCESS_CRASHED:
469 case NotificationType::PLUGIN_INSTANCE_CREATED:
initial.commit09911bf2008-07-26 23:55:29470 LogPluginChange(type, source, details);
471 break;
472
[email protected]bfd04a62009-02-01 18:16:56473 case NotificationType::TEMPLATE_URL_MODEL_LOADED:
initial.commit09911bf2008-07-26 23:55:29474 LogKeywords(Source<TemplateURLModel>(source).ptr());
475 break;
476
[email protected]bfd04a62009-02-01 18:16:56477 case NotificationType::OMNIBOX_OPENED_URL:
initial.commit09911bf2008-07-26 23:55:29478 current_log_->RecordOmniboxOpenedURL(
479 *Details<AutocompleteLog>(details).ptr());
480 break;
481
[email protected]bfd04a62009-02-01 18:16:56482 case NotificationType::BOOKMARK_MODEL_LOADED:
[email protected]d8e41ed2008-09-11 15:22:32483 LogBookmarks(Source<Profile>(source)->GetBookmarkModel());
initial.commit09911bf2008-07-26 23:55:29484 break;
485
486 default:
487 NOTREACHED();
488 break;
489 }
[email protected]d01b8732008-10-16 02:18:07490
491 HandleIdleSinceLastTransmission(false);
492
493 if (current_log_)
[email protected]281d2882009-01-20 20:32:42494 DLOG(INFO) << "METRICS: NUMBER OF EVENTS = " << current_log_->num_events();
[email protected]d01b8732008-10-16 02:18:07495}
496
497void MetricsService::HandleIdleSinceLastTransmission(bool in_idle) {
498 // If there wasn't a lot of action, maybe the computer was asleep, in which
499 // case, the log transmissions should have stopped. Here we start them up
500 // again.
[email protected]cac78842008-11-27 01:02:20501 if (!in_idle && idle_since_last_transmission_)
502 StartLogTransmissionTimer();
503 idle_since_last_transmission_ = in_idle;
initial.commit09911bf2008-07-26 23:55:29504}
505
506void MetricsService::RecordCleanShutdown() {
507 RecordBooleanPrefValue(prefs::kStabilityExitedCleanly, true);
508}
509
510void MetricsService::RecordStartOfSessionEnd() {
511 RecordBooleanPrefValue(prefs::kStabilitySessionEndCompleted, false);
512}
513
514void MetricsService::RecordCompletedSessionEnd() {
515 RecordBooleanPrefValue(prefs::kStabilitySessionEndCompleted, true);
516}
517
[email protected]e73c01972008-08-13 00:18:24518void MetricsService:: RecordBreakpadRegistration(bool success) {
[email protected]68475e602008-08-22 03:21:15519 if (!success)
[email protected]e73c01972008-08-13 00:18:24520 IncrementPrefValue(prefs::kStabilityBreakpadRegistrationFail);
521 else
522 IncrementPrefValue(prefs::kStabilityBreakpadRegistrationSuccess);
523}
524
525void MetricsService::RecordBreakpadHasDebugger(bool has_debugger) {
526 if (!has_debugger)
527 IncrementPrefValue(prefs::kStabilityDebuggerNotPresent);
528 else
[email protected]68475e602008-08-22 03:21:15529 IncrementPrefValue(prefs::kStabilityDebuggerPresent);
[email protected]e73c01972008-08-13 00:18:24530}
531
initial.commit09911bf2008-07-26 23:55:29532//------------------------------------------------------------------------------
533// private methods
534//------------------------------------------------------------------------------
535
536
537//------------------------------------------------------------------------------
538// Initialization methods
539
540void MetricsService::InitializeMetricsState() {
541 PrefService* pref = g_browser_process->local_state();
542 DCHECK(pref);
543
544 client_id_ = WideToUTF8(pref->GetString(prefs::kMetricsClientID));
545 if (client_id_.empty()) {
546 client_id_ = GenerateClientID();
547 pref->SetString(prefs::kMetricsClientID, UTF8ToWide(client_id_));
548
549 // Might as well make a note of how long this ID has existed
550 pref->SetString(prefs::kMetricsClientIDTimestamp,
551 Int64ToWString(Time::Now().ToTimeT()));
552 }
553
554 // Update session ID
555 session_id_ = pref->GetInteger(prefs::kMetricsSessionID);
556 ++session_id_;
557 pref->SetInteger(prefs::kMetricsSessionID, session_id_);
558
initial.commit09911bf2008-07-26 23:55:29559 // Stability bookkeeping
[email protected]e73c01972008-08-13 00:18:24560 IncrementPrefValue(prefs::kStabilityLaunchCount);
initial.commit09911bf2008-07-26 23:55:29561
[email protected]e73c01972008-08-13 00:18:24562 if (!pref->GetBoolean(prefs::kStabilityExitedCleanly)) {
563 IncrementPrefValue(prefs::kStabilityCrashCount);
initial.commit09911bf2008-07-26 23:55:29564 }
[email protected]e73c01972008-08-13 00:18:24565
566 // This will be set to 'true' if we exit cleanly.
initial.commit09911bf2008-07-26 23:55:29567 pref->SetBoolean(prefs::kStabilityExitedCleanly, false);
568
[email protected]e73c01972008-08-13 00:18:24569 if (!pref->GetBoolean(prefs::kStabilitySessionEndCompleted)) {
570 IncrementPrefValue(prefs::kStabilityIncompleteSessionEndCount);
initial.commit09911bf2008-07-26 23:55:29571 }
572 // This is marked false when we get a WM_ENDSESSION.
573 pref->SetBoolean(prefs::kStabilitySessionEndCompleted, true);
574
575 int64 last_start_time =
576 StringToInt64(pref->GetString(prefs::kStabilityLaunchTimeSec));
577 int64 last_end_time =
578 StringToInt64(pref->GetString(prefs::kStabilityLastTimestampSec));
579 int64 uptime =
580 StringToInt64(pref->GetString(prefs::kStabilityUptimeSec));
581
582 if (last_start_time && last_end_time) {
583 // TODO(JAR): Exclude sleep time. ... which must be gathered in UI loop.
584 uptime += last_end_time - last_start_time;
585 pref->SetString(prefs::kStabilityUptimeSec, Int64ToWString(uptime));
586 }
587 pref->SetString(prefs::kStabilityLaunchTimeSec,
588 Int64ToWString(Time::Now().ToTimeT()));
589
590 // Save profile metrics.
591 PrefService* prefs = g_browser_process->local_state();
592 if (prefs) {
593 // Remove the current dictionary and store it for use when sending data to
594 // server. By removing the value we prune potentially dead profiles
595 // (and keys). All valid values are added back once services startup.
596 const DictionaryValue* profile_dictionary =
597 prefs->GetDictionary(prefs::kProfileMetrics);
598 if (profile_dictionary) {
599 // Do a deep copy of profile_dictionary since ClearPref will delete it.
600 profile_dictionary_.reset(static_cast<DictionaryValue*>(
601 profile_dictionary->DeepCopy()));
602 prefs->ClearPref(prefs::kProfileMetrics);
603 }
604 }
605
606 // Kick off the process of saving the state (so the uptime numbers keep
607 // getting updated) every n minutes.
608 ScheduleNextStateSave();
609}
610
611void MetricsService::OnGetPluginListTaskComplete() {
612 DCHECK(state_ == PLUGIN_LIST_REQUESTED);
613 if (state_ == PLUGIN_LIST_REQUESTED)
614 state_ = PLUGIN_LIST_ARRIVED;
615}
616
617std::string MetricsService::GenerateClientID() {
618 const int kGUIDSize = 39;
619
620 GUID guid;
621 HRESULT guid_result = CoCreateGuid(&guid);
622 DCHECK(SUCCEEDED(guid_result));
623
624 std::wstring guid_string;
625 int result = StringFromGUID2(guid,
626 WriteInto(&guid_string, kGUIDSize), kGUIDSize);
627 DCHECK(result == kGUIDSize);
628
629 return WideToUTF8(guid_string.substr(1, guid_string.length() - 2));
630}
631
632
633//------------------------------------------------------------------------------
634// State save methods
635
636void MetricsService::ScheduleNextStateSave() {
637 state_saver_factory_.RevokeAll();
638
639 MessageLoop::current()->PostDelayedTask(FROM_HERE,
640 state_saver_factory_.NewRunnableMethod(&MetricsService::SaveLocalState),
641 kSaveStateInterval * 1000);
642}
643
644void MetricsService::SaveLocalState() {
645 PrefService* pref = g_browser_process->local_state();
646 if (!pref) {
647 NOTREACHED();
648 return;
649 }
650
651 RecordCurrentState(pref);
652 pref->ScheduleSavePersistentPrefs(g_browser_process->file_thread());
653
[email protected]281d2882009-01-20 20:32:42654 // TODO(jar): Does this run down the batteries????
initial.commit09911bf2008-07-26 23:55:29655 ScheduleNextStateSave();
656}
657
658
659//------------------------------------------------------------------------------
660// Recording control methods
661
662void MetricsService::StartRecording() {
663 if (current_log_)
664 return;
665
666 current_log_ = new MetricsLog(client_id_, session_id_);
667 if (state_ == INITIALIZED) {
668 // We only need to schedule that run once.
669 state_ = PLUGIN_LIST_REQUESTED;
670
671 // Make sure the plugin list is loaded before the inital log is sent, so
672 // that the main thread isn't blocked generating the list.
673 g_browser_process->file_thread()->message_loop()->PostDelayedTask(FROM_HERE,
674 new GetPluginListTask(MessageLoop::current()),
[email protected]252873ef2008-08-04 21:59:45675 kInitialInterlogDuration * 1000 / 2);
initial.commit09911bf2008-07-26 23:55:29676 }
677}
678
679void MetricsService::StopRecording(MetricsLog** log) {
680 if (!current_log_)
681 return;
682
[email protected]68475e602008-08-22 03:21:15683 // TODO(jar): Integrate bounds on log recording more consistently, so that we
684 // can stop recording logs that are too big much sooner.
[email protected]d01b8732008-10-16 02:18:07685 if (current_log_->num_events() > log_event_limit_) {
[email protected]68475e602008-08-22 03:21:15686 UMA_HISTOGRAM_COUNTS(L"UMA.Discarded Log Events",
687 current_log_->num_events());
688 current_log_->CloseLog();
689 delete current_log_;
[email protected]294638782008-09-24 00:22:41690 current_log_ = NULL;
[email protected]68475e602008-08-22 03:21:15691 StartRecording(); // Start trivial log to hold our histograms.
692 }
693
[email protected]0b33f80b2008-12-17 21:34:36694 // Put incremental data (histogram deltas, and realtime stats deltas) at the
[email protected]147bbc0b2009-01-06 19:37:40695 // end of all log transmissions (initial log handles this separately).
initial.commit09911bf2008-07-26 23:55:29696 // Don't bother if we're going to discard current_log_.
[email protected]0b33f80b2008-12-17 21:34:36697 if (log) {
[email protected]54131d252009-02-09 05:49:22698 // TODO(jar): when initial logs and ongoing logs have equal survivability,
699 // uncomment the following line to expedite stability data uploads.
700 // current_log_->RecordIncrementalStabilityElements();
initial.commit09911bf2008-07-26 23:55:29701 RecordCurrentHistograms();
[email protected]0b33f80b2008-12-17 21:34:36702 }
initial.commit09911bf2008-07-26 23:55:29703
704 current_log_->CloseLog();
[email protected]cac78842008-11-27 01:02:20705 if (log)
initial.commit09911bf2008-07-26 23:55:29706 *log = current_log_;
[email protected]cac78842008-11-27 01:02:20707 else
initial.commit09911bf2008-07-26 23:55:29708 delete current_log_;
initial.commit09911bf2008-07-26 23:55:29709 current_log_ = NULL;
710}
711
712void MetricsService::ListenerRegistration(bool start_listening) {
[email protected]bfd04a62009-02-01 18:16:56713 AddOrRemoveObserver(this, NotificationType::BROWSER_OPENED, start_listening);
714 AddOrRemoveObserver(this, NotificationType::BROWSER_CLOSED, start_listening);
715 AddOrRemoveObserver(this, NotificationType::USER_ACTION, start_listening);
716 AddOrRemoveObserver(this, NotificationType::TAB_PARENTED, start_listening);
717 AddOrRemoveObserver(this, NotificationType::TAB_CLOSING, start_listening);
718 AddOrRemoveObserver(this, NotificationType::LOAD_START, start_listening);
719 AddOrRemoveObserver(this, NotificationType::LOAD_STOP, start_listening);
720 AddOrRemoveObserver(this, NotificationType::RENDERER_PROCESS_IN_SBOX,
initial.commit09911bf2008-07-26 23:55:29721 start_listening);
[email protected]bfd04a62009-02-01 18:16:56722 AddOrRemoveObserver(this, NotificationType::RENDERER_PROCESS_TERMINATED,
initial.commit09911bf2008-07-26 23:55:29723 start_listening);
[email protected]bfd04a62009-02-01 18:16:56724 AddOrRemoveObserver(this, NotificationType::RENDERER_PROCESS_HANG,
725 start_listening);
726 AddOrRemoveObserver(this, NotificationType::PLUGIN_PROCESS_HOST_CONNECTED,
727 start_listening);
728 AddOrRemoveObserver(this, NotificationType::PLUGIN_INSTANCE_CREATED,
729 start_listening);
730 AddOrRemoveObserver(this, NotificationType::PLUGIN_PROCESS_CRASHED,
731 start_listening);
732 AddOrRemoveObserver(this, NotificationType::TEMPLATE_URL_MODEL_LOADED,
733 start_listening);
734 AddOrRemoveObserver(this, NotificationType::OMNIBOX_OPENED_URL,
735 start_listening);
736 AddOrRemoveObserver(this, NotificationType::BOOKMARK_MODEL_LOADED,
737 start_listening);
initial.commit09911bf2008-07-26 23:55:29738}
739
740// static
741void MetricsService::AddOrRemoveObserver(NotificationObserver* observer,
[email protected]cac78842008-11-27 01:02:20742 NotificationType type,
743 bool is_add) {
initial.commit09911bf2008-07-26 23:55:29744 NotificationService* service = NotificationService::current();
745
[email protected]cac78842008-11-27 01:02:20746 if (is_add)
initial.commit09911bf2008-07-26 23:55:29747 service->AddObserver(observer, type, NotificationService::AllSources());
[email protected]cac78842008-11-27 01:02:20748 else
initial.commit09911bf2008-07-26 23:55:29749 service->RemoveObserver(observer, type, NotificationService::AllSources());
initial.commit09911bf2008-07-26 23:55:29750}
751
752void MetricsService::PushPendingLogsToUnsentLists() {
753 if (state_ < INITIAL_LOG_READY)
[email protected]28ab7f92009-01-06 21:39:04754 return; // We didn't and still don't have time to get plugin list etc.
initial.commit09911bf2008-07-26 23:55:29755
756 if (pending_log()) {
757 PreparePendingLogText();
758 if (state_ == INITIAL_LOG_READY) {
759 // We may race here, and send second copy of initial log later.
760 unsent_initial_logs_.push_back(pending_log_text_);
[email protected]d01b8732008-10-16 02:18:07761 state_ = SEND_OLD_INITIAL_LOGS;
initial.commit09911bf2008-07-26 23:55:29762 } else {
[email protected]281d2882009-01-20 20:32:42763 // TODO(jar): Verify correctness in other states, including sending unsent
764 // iniitial logs.
[email protected]68475e602008-08-22 03:21:15765 PushPendingLogTextToUnsentOngoingLogs();
initial.commit09911bf2008-07-26 23:55:29766 }
767 DiscardPendingLog();
768 }
769 DCHECK(!pending_log());
770 StopRecording(&pending_log_);
771 PreparePendingLogText();
[email protected]68475e602008-08-22 03:21:15772 PushPendingLogTextToUnsentOngoingLogs();
initial.commit09911bf2008-07-26 23:55:29773 DiscardPendingLog();
774 StoreUnsentLogs();
775}
776
[email protected]68475e602008-08-22 03:21:15777void MetricsService::PushPendingLogTextToUnsentOngoingLogs() {
[email protected]d01b8732008-10-16 02:18:07778 // If UMA response told us not to upload, there's no need to save the pending
779 // log. It wasn't supposed to be uploaded anyway.
780 if (!server_permits_upload_)
781 return;
782
[email protected]68475e602008-08-22 03:21:15783 if (pending_log_text_.length() > kUploadLogAvoidRetransmitSize) {
784 UMA_HISTOGRAM_COUNTS(L"UMA.Large Accumulated Log Not Persisted",
785 static_cast<int>(pending_log_text_.length()));
786 return;
787 }
788 unsent_ongoing_logs_.push_back(pending_log_text_);
789}
790
initial.commit09911bf2008-07-26 23:55:29791//------------------------------------------------------------------------------
792// Transmission of logs methods
793
794void MetricsService::StartLogTransmissionTimer() {
[email protected]d01b8732008-10-16 02:18:07795 // If we're not reporting, there's no point in starting a log transmission
796 // timer.
797 if (!reporting_active())
798 return;
799
initial.commit09911bf2008-07-26 23:55:29800 if (!current_log_)
801 return; // Recorder is shutdown.
[email protected]d01b8732008-10-16 02:18:07802
803 // If there is already a timer running, we leave it running.
804 // If timer_pending is true because the fetch is waiting for a response,
805 // we return for now and let the response handler start the timer.
806 if (timer_pending_)
initial.commit09911bf2008-07-26 23:55:29807 return;
[email protected]d01b8732008-10-16 02:18:07808
[email protected]d01b8732008-10-16 02:18:07809 // Before starting the timer, set timer_pending_ to true.
initial.commit09911bf2008-07-26 23:55:29810 timer_pending_ = true;
[email protected]d01b8732008-10-16 02:18:07811
812 // Right before the UMA transmission gets started, there's one more thing we'd
813 // like to record: the histogram of memory usage, so we spawn a task to
814 // collect the memory details and when that task is finished, we arrange for
815 // TryToStartTransmission to take over.
initial.commit09911bf2008-07-26 23:55:29816 MessageLoop::current()->PostDelayedTask(FROM_HERE,
817 log_sender_factory_.
818 NewRunnableMethod(&MetricsService::CollectMemoryDetails),
819 static_cast<int>(interlog_duration_.InMilliseconds()));
820}
821
822void MetricsService::TryToStartTransmission() {
823 DCHECK(IsSingleThreaded());
824
[email protected]d01b8732008-10-16 02:18:07825 // This function should only be called via timer, so timer_pending_
826 // should be true.
827 DCHECK(timer_pending_);
828 timer_pending_ = false;
initial.commit09911bf2008-07-26 23:55:29829
830 DCHECK(!current_fetch_.get());
initial.commit09911bf2008-07-26 23:55:29831
[email protected]d01b8732008-10-16 02:18:07832 // If we're getting no notifications, then the log won't have much in it, and
833 // it's possible the computer is about to go to sleep, so don't upload and
834 // don't restart the transmission timer.
835 if (idle_since_last_transmission_)
836 return;
837
838 // If somehow there is a fetch in progress, we return setting timer_pending_
839 // to true and hope things work out.
840 if (current_fetch_.get()) {
841 timer_pending_ = true;
842 return;
843 }
844
845 // If uploads are forbidden by UMA response, there's no point in keeping
846 // the current_log_, and the more often we delete it, the less likely it is
847 // to expand forever.
848 if (!server_permits_upload_ && current_log_) {
849 StopRecording(NULL);
850 StartRecording();
851 }
initial.commit09911bf2008-07-26 23:55:29852
853 if (!current_log_)
854 return; // Logging was disabled.
[email protected]d01b8732008-10-16 02:18:07855 if (!reporting_active())
initial.commit09911bf2008-07-26 23:55:29856 return; // Don't do work if we're not going to send anything now.
857
[email protected]d01b8732008-10-16 02:18:07858 MakePendingLog();
initial.commit09911bf2008-07-26 23:55:29859
[email protected]d01b8732008-10-16 02:18:07860 // MakePendingLog should have put something in the pending log, if it didn't,
861 // we start the timer again, return and hope things work out.
862 if (!pending_log()) {
863 StartLogTransmissionTimer();
864 return;
865 }
initial.commit09911bf2008-07-26 23:55:29866
[email protected]d01b8732008-10-16 02:18:07867 // If we're not supposed to upload any UMA data because the response or the
868 // user said so, cancel the upload at this point, but start the timer.
869 if (!TransmissionPermitted()) {
870 DiscardPendingLog();
871 StartLogTransmissionTimer();
872 return;
873 }
initial.commit09911bf2008-07-26 23:55:29874
[email protected]d01b8732008-10-16 02:18:07875 PrepareFetchWithPendingLog();
876
877 if (!current_fetch_.get()) {
878 // Compression failed, and log discarded :-/.
879 DiscardPendingLog();
880 StartLogTransmissionTimer(); // Maybe we'll do better next time
881 // TODO(jar): If compression failed, we should have created a tiny log and
882 // compressed that, so that we can signal that we're losing logs.
883 return;
884 }
885
886 DCHECK(!timer_pending_);
887
888 // The URL fetch is a like timer in that after a while we get called back
889 // so we set timer_pending_ true just as we start the url fetch.
890 timer_pending_ = true;
891 current_fetch_->Start();
892
893 HandleIdleSinceLastTransmission(true);
894}
895
896
897void MetricsService::MakePendingLog() {
898 if (pending_log())
899 return;
900
901 switch (state_) {
902 case INITIALIZED:
903 case PLUGIN_LIST_REQUESTED: // We should be further along by now.
904 DCHECK(false);
905 return;
906
907 case PLUGIN_LIST_ARRIVED:
908 // We need to wait for the initial log to be ready before sending
909 // anything, because the server will tell us whether it wants to hear
910 // from us.
911 PrepareInitialLog();
912 DCHECK(state_ == PLUGIN_LIST_ARRIVED);
913 RecallUnsentLogs();
914 state_ = INITIAL_LOG_READY;
915 break;
916
917 case SEND_OLD_INITIAL_LOGS:
[email protected]cac78842008-11-27 01:02:20918 if (!unsent_initial_logs_.empty()) {
919 pending_log_text_ = unsent_initial_logs_.back();
920 break;
921 }
[email protected]d01b8732008-10-16 02:18:07922 state_ = SENDING_OLD_LOGS;
923 // Fall through.
initial.commit09911bf2008-07-26 23:55:29924
[email protected]d01b8732008-10-16 02:18:07925 case SENDING_OLD_LOGS:
926 if (!unsent_ongoing_logs_.empty()) {
927 pending_log_text_ = unsent_ongoing_logs_.back();
928 break;
929 }
930 state_ = SENDING_CURRENT_LOGS;
931 // Fall through.
932
933 case SENDING_CURRENT_LOGS:
934 StopRecording(&pending_log_);
935 StartRecording();
936 break;
937
938 default:
939 DCHECK(false);
940 return;
941 }
942
943 DCHECK(pending_log());
944}
945
946bool MetricsService::TransmissionPermitted() const {
947 // If the user forbids uploading that's they're business, and we don't upload
948 // anything. If the server forbids uploading, that's our business, so we take
949 // that to mean it forbids current logs, but we still send up the inital logs
950 // and any old logs.
[email protected]d01b8732008-10-16 02:18:07951 if (!user_permits_upload_)
952 return false;
[email protected]cac78842008-11-27 01:02:20953 if (server_permits_upload_)
[email protected]d01b8732008-10-16 02:18:07954 return true;
initial.commit09911bf2008-07-26 23:55:29955
[email protected]cac78842008-11-27 01:02:20956 switch (state_) {
957 case INITIAL_LOG_READY:
958 case SEND_OLD_INITIAL_LOGS:
959 case SENDING_OLD_LOGS:
960 return true;
961
962 case SENDING_CURRENT_LOGS:
963 default:
964 return false;
[email protected]8c8824b2008-09-20 01:55:50965 }
initial.commit09911bf2008-07-26 23:55:29966}
967
968void MetricsService::CollectMemoryDetails() {
969 Task* task = log_sender_factory_.
970 NewRunnableMethod(&MetricsService::TryToStartTransmission);
971 MetricsMemoryDetails* details = new MetricsMemoryDetails(task);
972 details->StartFetch();
973
974 // Collect WebCore cache information to put into a histogram.
975 for (RenderProcessHost::iterator it = RenderProcessHost::begin();
976 it != RenderProcessHost::end(); ++it) {
977 it->second->Send(new ViewMsg_GetCacheResourceStats());
978 }
979}
980
981void MetricsService::PrepareInitialLog() {
982 DCHECK(state_ == PLUGIN_LIST_ARRIVED);
983 std::vector<WebPluginInfo> plugins;
984 PluginService::GetInstance()->GetPlugins(false, &plugins);
985
986 MetricsLog* log = new MetricsLog(client_id_, session_id_);
987 log->RecordEnvironment(plugins, profile_dictionary_.get());
988
989 // Histograms only get written to current_log_, so setup for the write.
990 MetricsLog* save_log = current_log_;
991 current_log_ = log;
992 RecordCurrentHistograms(); // Into current_log_... which is really log.
993 current_log_ = save_log;
994
995 log->CloseLog();
996 DCHECK(!pending_log());
997 pending_log_ = log;
998}
999
1000void MetricsService::RecallUnsentLogs() {
1001 DCHECK(unsent_initial_logs_.empty());
1002 DCHECK(unsent_ongoing_logs_.empty());
1003
1004 PrefService* local_state = g_browser_process->local_state();
1005 DCHECK(local_state);
1006
1007 ListValue* unsent_initial_logs = local_state->GetMutableList(
1008 prefs::kMetricsInitialLogs);
1009 for (ListValue::iterator it = unsent_initial_logs->begin();
1010 it != unsent_initial_logs->end(); ++it) {
[email protected]5e324b72008-12-18 00:07:591011 std::string log;
1012 (*it)->GetAsString(&log);
1013 unsent_initial_logs_.push_back(log);
initial.commit09911bf2008-07-26 23:55:291014 }
1015
1016 ListValue* unsent_ongoing_logs = local_state->GetMutableList(
1017 prefs::kMetricsOngoingLogs);
1018 for (ListValue::iterator it = unsent_ongoing_logs->begin();
1019 it != unsent_ongoing_logs->end(); ++it) {
[email protected]5e324b72008-12-18 00:07:591020 std::string log;
1021 (*it)->GetAsString(&log);
1022 unsent_ongoing_logs_.push_back(log);
initial.commit09911bf2008-07-26 23:55:291023 }
1024}
1025
1026void MetricsService::StoreUnsentLogs() {
1027 if (state_ < INITIAL_LOG_READY)
1028 return; // We never Recalled the prior unsent logs.
1029
1030 PrefService* local_state = g_browser_process->local_state();
1031 DCHECK(local_state);
1032
1033 ListValue* unsent_initial_logs = local_state->GetMutableList(
1034 prefs::kMetricsInitialLogs);
1035 unsent_initial_logs->Clear();
1036 size_t start = 0;
1037 if (unsent_initial_logs_.size() > kMaxInitialLogsPersisted)
1038 start = unsent_initial_logs_.size() - kMaxInitialLogsPersisted;
1039 for (size_t i = start; i < unsent_initial_logs_.size(); ++i)
1040 unsent_initial_logs->Append(
[email protected]5e324b72008-12-18 00:07:591041 Value::CreateStringValue(unsent_initial_logs_[i]));
initial.commit09911bf2008-07-26 23:55:291042
1043 ListValue* unsent_ongoing_logs = local_state->GetMutableList(
1044 prefs::kMetricsOngoingLogs);
1045 unsent_ongoing_logs->Clear();
1046 start = 0;
1047 if (unsent_ongoing_logs_.size() > kMaxOngoingLogsPersisted)
1048 start = unsent_ongoing_logs_.size() - kMaxOngoingLogsPersisted;
1049 for (size_t i = start; i < unsent_ongoing_logs_.size(); ++i)
1050 unsent_ongoing_logs->Append(
[email protected]5e324b72008-12-18 00:07:591051 Value::CreateStringValue(unsent_ongoing_logs_[i]));
initial.commit09911bf2008-07-26 23:55:291052}
1053
1054void MetricsService::PreparePendingLogText() {
1055 DCHECK(pending_log());
1056 if (!pending_log_text_.empty())
1057 return;
1058 int original_size = pending_log_->GetEncodedLogSize();
1059 pending_log_->GetEncodedLog(WriteInto(&pending_log_text_, original_size),
1060 original_size);
1061}
1062
[email protected]d01b8732008-10-16 02:18:071063void MetricsService::PrepareFetchWithPendingLog() {
initial.commit09911bf2008-07-26 23:55:291064 DCHECK(pending_log());
1065 DCHECK(!current_fetch_.get());
1066 PreparePendingLogText();
1067 DCHECK(!pending_log_text_.empty());
1068
1069 // Allow security conscious users to see all metrics logs that we send.
1070 LOG(INFO) << "METRICS LOG: " << pending_log_text_;
1071
1072 std::string compressed_log;
[email protected]cac78842008-11-27 01:02:201073 if (!Bzip2Compress(pending_log_text_, &compressed_log)) {
initial.commit09911bf2008-07-26 23:55:291074 NOTREACHED() << "Failed to compress log for transmission.";
1075 DiscardPendingLog();
1076 StartLogTransmissionTimer(); // Maybe we'll do better on next log :-/.
1077 return;
1078 }
[email protected]cac78842008-11-27 01:02:201079
initial.commit09911bf2008-07-26 23:55:291080 current_fetch_.reset(new URLFetcher(GURL(kMetricsURL), URLFetcher::POST,
1081 this));
1082 current_fetch_->set_request_context(Profile::GetDefaultRequestContext());
1083 current_fetch_->set_upload_data(kMetricsType, compressed_log);
initial.commit09911bf2008-07-26 23:55:291084}
1085
1086void MetricsService::DiscardPendingLog() {
1087 if (pending_log_) { // Shutdown might have deleted it!
1088 delete pending_log_;
1089 pending_log_ = NULL;
1090 }
1091 pending_log_text_.clear();
1092}
1093
1094// This implementation is based on the Firefox MetricsService implementation.
1095bool MetricsService::Bzip2Compress(const std::string& input,
1096 std::string* output) {
1097 bz_stream stream = {0};
1098 // As long as our input is smaller than the bzip2 block size, we should get
1099 // the best compression. For example, if your input was 250k, using a block
1100 // size of 300k or 500k should result in the same compression ratio. Since
1101 // our data should be under 100k, using the minimum block size of 100k should
1102 // allocate less temporary memory, but result in the same compression ratio.
1103 int result = BZ2_bzCompressInit(&stream,
1104 1, // 100k (min) block size
1105 0, // quiet
1106 0); // default "work factor"
1107 if (result != BZ_OK) { // out of memory?
1108 return false;
1109 }
1110
1111 output->clear();
1112
1113 stream.next_in = const_cast<char*>(input.data());
1114 stream.avail_in = static_cast<int>(input.size());
1115 // NOTE: we don't need a BZ_RUN phase since our input buffer contains
1116 // the entire input
1117 do {
1118 output->resize(output->size() + 1024);
1119 stream.next_out = &((*output)[stream.total_out_lo32]);
1120 stream.avail_out = static_cast<int>(output->size()) - stream.total_out_lo32;
1121 result = BZ2_bzCompress(&stream, BZ_FINISH);
1122 } while (result == BZ_FINISH_OK);
1123 if (result != BZ_STREAM_END) // unknown failure?
1124 return false;
1125 result = BZ2_bzCompressEnd(&stream);
1126 DCHECK(result == BZ_OK);
1127
1128 output->resize(stream.total_out_lo32);
1129
1130 return true;
1131}
1132
1133static const char* StatusToString(const URLRequestStatus& status) {
1134 switch (status.status()) {
1135 case URLRequestStatus::SUCCESS:
1136 return "SUCCESS";
1137
1138 case URLRequestStatus::IO_PENDING:
1139 return "IO_PENDING";
1140
1141 case URLRequestStatus::HANDLED_EXTERNALLY:
1142 return "HANDLED_EXTERNALLY";
1143
1144 case URLRequestStatus::CANCELED:
1145 return "CANCELED";
1146
1147 case URLRequestStatus::FAILED:
1148 return "FAILED";
1149
1150 default:
1151 NOTREACHED();
1152 return "Unknown";
1153 }
1154}
1155
1156void MetricsService::OnURLFetchComplete(const URLFetcher* source,
1157 const GURL& url,
1158 const URLRequestStatus& status,
1159 int response_code,
1160 const ResponseCookies& cookies,
1161 const std::string& data) {
1162 DCHECK(timer_pending_);
1163 timer_pending_ = false;
1164 DCHECK(current_fetch_.get());
1165 current_fetch_.reset(NULL); // We're not allowed to re-use it.
1166
1167 // Confirm send so that we can move on.
[email protected]281d2882009-01-20 20:32:421168 LOG(INFO) << "METRICS RESPONSE CODE: " << response_code << " status=" <<
[email protected]cac78842008-11-27 01:02:201169 StatusToString(status);
[email protected]252873ef2008-08-04 21:59:451170
[email protected]0eb34fee2009-01-21 08:04:381171 // Provide boolean for error recovery (allow us to ignore response_code).
1172 boolean discard_log = false;
1173
[email protected]68475e602008-08-22 03:21:151174 if (response_code != 200 &&
1175 pending_log_text_.length() > kUploadLogAvoidRetransmitSize) {
1176 UMA_HISTOGRAM_COUNTS(L"UMA.Large Rejected Log was Discarded",
1177 static_cast<int>(pending_log_text_.length()));
[email protected]0eb34fee2009-01-21 08:04:381178 discard_log = true;
1179 } else if (response_code == 400) {
1180 // Bad syntax. Retransmission won't work.
1181 UMA_HISTOGRAM_COUNTS(L"UMA.Unacceptable_Log_Discarded", state_);
1182 discard_log = true;
[email protected]68475e602008-08-22 03:21:151183 }
1184
[email protected]0eb34fee2009-01-21 08:04:381185 if (response_code != 200 && !discard_log) {
[email protected]281d2882009-01-20 20:32:421186 LOG(INFO) << "METRICS: transmission attempt returned a failure code: "
1187 << response_code << ". Verify network connectivity";
[email protected]252873ef2008-08-04 21:59:451188 HandleBadResponseCode();
[email protected]0eb34fee2009-01-21 08:04:381189 } else { // Successful receipt (or we are discarding log).
[email protected]281d2882009-01-20 20:32:421190 LOG(INFO) << "METRICS RESPONSE DATA: " << data;
initial.commit09911bf2008-07-26 23:55:291191 switch (state_) {
1192 case INITIAL_LOG_READY:
1193 state_ = SEND_OLD_INITIAL_LOGS;
1194 break;
1195
1196 case SEND_OLD_INITIAL_LOGS:
1197 DCHECK(!unsent_initial_logs_.empty());
1198 unsent_initial_logs_.pop_back();
1199 StoreUnsentLogs();
1200 break;
1201
1202 case SENDING_OLD_LOGS:
1203 DCHECK(!unsent_ongoing_logs_.empty());
1204 unsent_ongoing_logs_.pop_back();
1205 StoreUnsentLogs();
1206 break;
1207
1208 case SENDING_CURRENT_LOGS:
1209 break;
1210
1211 default:
1212 DCHECK(false);
1213 break;
1214 }
[email protected]d01b8732008-10-16 02:18:071215
initial.commit09911bf2008-07-26 23:55:291216 DiscardPendingLog();
[email protected]29be92552008-08-07 22:49:271217 // Since we sent a log, make sure our in-memory state is recorded to disk.
1218 PrefService* local_state = g_browser_process->local_state();
1219 DCHECK(local_state);
1220 if (local_state)
1221 local_state->ScheduleSavePersistentPrefs(
1222 g_browser_process->file_thread());
[email protected]252873ef2008-08-04 21:59:451223
[email protected]147bbc0b2009-01-06 19:37:401224 // Provide a default (free of exponetial backoff, other varances) in case
1225 // the server does not specify a value.
1226 interlog_duration_ = TimeDelta::FromSeconds(kMinSecondsPerLog);
1227
[email protected]252873ef2008-08-04 21:59:451228 GetSettingsFromResponseData(data);
[email protected]252873ef2008-08-04 21:59:451229 // Override server specified interlog delay if there are unsent logs to
[email protected]29be92552008-08-07 22:49:271230 // transmit.
initial.commit09911bf2008-07-26 23:55:291231 if (unsent_logs()) {
1232 DCHECK(state_ < SENDING_CURRENT_LOGS);
1233 interlog_duration_ = TimeDelta::FromSeconds(kUnsentLogDelay);
initial.commit09911bf2008-07-26 23:55:291234 }
1235 }
[email protected]252873ef2008-08-04 21:59:451236
initial.commit09911bf2008-07-26 23:55:291237 StartLogTransmissionTimer();
1238}
1239
[email protected]252873ef2008-08-04 21:59:451240void MetricsService::HandleBadResponseCode() {
[email protected]281d2882009-01-20 20:32:421241 LOG(INFO) << "Verify your metrics logs are formatted correctly. "
[email protected]cac78842008-11-27 01:02:201242 "Verify server is active at " << kMetricsURL;
[email protected]252873ef2008-08-04 21:59:451243 if (!pending_log()) {
[email protected]281d2882009-01-20 20:32:421244 LOG(INFO) << "METRICS: Recorder shutdown during log transmission.";
[email protected]252873ef2008-08-04 21:59:451245 } else {
1246 // Send progressively less frequently.
1247 DCHECK(kBackoff > 1.0);
1248 interlog_duration_ = TimeDelta::FromMicroseconds(
1249 static_cast<int64>(kBackoff * interlog_duration_.InMicroseconds()));
1250
1251 if (kMaxBackoff * TimeDelta::FromSeconds(kMinSecondsPerLog) <
[email protected]cac78842008-11-27 01:02:201252 interlog_duration_) {
[email protected]252873ef2008-08-04 21:59:451253 interlog_duration_ = kMaxBackoff *
1254 TimeDelta::FromSeconds(kMinSecondsPerLog);
[email protected]cac78842008-11-27 01:02:201255 }
[email protected]252873ef2008-08-04 21:59:451256
[email protected]281d2882009-01-20 20:32:421257 LOG(INFO) << "METRICS: transmission retry being scheduled in " <<
[email protected]252873ef2008-08-04 21:59:451258 interlog_duration_.InSeconds() << " seconds for " <<
1259 pending_log_text_;
initial.commit09911bf2008-07-26 23:55:291260 }
initial.commit09911bf2008-07-26 23:55:291261}
1262
[email protected]252873ef2008-08-04 21:59:451263void MetricsService::GetSettingsFromResponseData(const std::string& data) {
1264 // We assume that the file is structured as a block opened by <response>
[email protected]d01b8732008-10-16 02:18:071265 // and that inside response, there is a block opened by tag <chrome_config>
1266 // other tags are ignored for now except the content of <chrome_config>.
[email protected]281d2882009-01-20 20:32:421267 LOG(INFO) << "METRICS: getting settings from response data: " << data;
[email protected]d01b8732008-10-16 02:18:071268
[email protected]252873ef2008-08-04 21:59:451269 int data_size = static_cast<int>(data.size());
1270 if (data_size < 0) {
[email protected]281d2882009-01-20 20:32:421271 LOG(INFO) << "METRICS: server response data bad size: " << data_size <<
[email protected]cac78842008-11-27 01:02:201272 "; aborting extraction of settings";
[email protected]252873ef2008-08-04 21:59:451273 return;
1274 }
[email protected]cac78842008-11-27 01:02:201275 xmlDocPtr doc = xmlReadMemory(data.c_str(), data_size, "", NULL, 0);
[email protected]252873ef2008-08-04 21:59:451276 DCHECK(doc);
[email protected]d01b8732008-10-16 02:18:071277 // If the document is malformed, we just use the settings that were there.
1278 if (!doc) {
[email protected]281d2882009-01-20 20:32:421279 LOG(INFO) << "METRICS: reading xml from server response data failed";
[email protected]252873ef2008-08-04 21:59:451280 return;
[email protected]d01b8732008-10-16 02:18:071281 }
[email protected]252873ef2008-08-04 21:59:451282
[email protected]d01b8732008-10-16 02:18:071283 xmlNodePtr top_node = xmlDocGetRootElement(doc), chrome_config_node = NULL;
1284 // Here, we find the chrome_config node by name.
[email protected]252873ef2008-08-04 21:59:451285 for (xmlNodePtr p = top_node->children; p; p = p->next) {
[email protected]d01b8732008-10-16 02:18:071286 if (xmlStrEqual(p->name, BAD_CAST "chrome_config")) {
1287 chrome_config_node = p;
[email protected]252873ef2008-08-04 21:59:451288 break;
1289 }
1290 }
1291 // If the server data is formatted wrong and there is no
1292 // config node where we expect, we just drop out.
[email protected]d01b8732008-10-16 02:18:071293 if (chrome_config_node != NULL)
1294 GetSettingsFromChromeConfigNode(chrome_config_node);
[email protected]252873ef2008-08-04 21:59:451295 xmlFreeDoc(doc);
1296}
1297
[email protected]d01b8732008-10-16 02:18:071298void MetricsService::GetSettingsFromChromeConfigNode(
1299 xmlNodePtr chrome_config_node) {
1300 // Iterate through all children of the config node.
1301 for (xmlNodePtr current_node = chrome_config_node->children;
1302 current_node;
1303 current_node = current_node->next) {
1304 // If we find the upload tag, we appeal to another function
1305 // GetSettingsFromUploadNode to read all the data in it.
[email protected]252873ef2008-08-04 21:59:451306 if (xmlStrEqual(current_node->name, BAD_CAST "upload")) {
[email protected]d01b8732008-10-16 02:18:071307 GetSettingsFromUploadNode(current_node);
[email protected]252873ef2008-08-04 21:59:451308 continue;
1309 }
1310 }
1311}
initial.commit09911bf2008-07-26 23:55:291312
[email protected]d01b8732008-10-16 02:18:071313void MetricsService::InheritedProperties::OverwriteWhereNeeded(
1314 xmlNodePtr node) {
1315 xmlChar* salt_value = xmlGetProp(node, BAD_CAST "salt");
1316 if (salt_value) // If the property isn't there, xmlGetProp returns NULL.
1317 salt = atoi(reinterpret_cast<char*>(salt_value));
1318 // If the property isn't there, we keep the value the property had before
1319
1320 xmlChar* denominator_value = xmlGetProp(node, BAD_CAST "denominator");
1321 if (denominator_value)
1322 denominator = atoi(reinterpret_cast<char*>(denominator_value));
1323}
1324
1325void MetricsService::GetSettingsFromUploadNode(xmlNodePtr upload_node) {
1326 InheritedProperties props;
1327 GetSettingsFromUploadNodeRecursive(upload_node, props, "", true);
1328}
1329
[email protected]cac78842008-11-27 01:02:201330void MetricsService::GetSettingsFromUploadNodeRecursive(
1331 xmlNodePtr node,
1332 InheritedProperties props,
1333 std::string path_prefix,
1334 bool uploadOn) {
[email protected]d01b8732008-10-16 02:18:071335 props.OverwriteWhereNeeded(node);
1336
1337 // The bool uploadOn is set to true if the data represented by current
1338 // node should be uploaded. This gets inherited in the tree; the children
1339 // of a node that has already been rejected for upload get rejected for
1340 // upload.
1341 uploadOn = uploadOn && NodeProbabilityTest(node, props);
1342
1343 // The path is a / separated list of the node names ancestral to the current
1344 // one. So, if you want to check if the current node has a certain name,
1345 // compare to name. If you want to check if it is a certan tag at a certain
1346 // place in the tree, compare to the whole path.
1347 std::string name = std::string(reinterpret_cast<const char*>(node->name));
1348 std::string path = path_prefix + "/" + name;
1349
1350 if (path == "/upload") {
1351 xmlChar* upload_interval_val = xmlGetProp(node, BAD_CAST "interval");
1352 if (upload_interval_val) {
1353 interlog_duration_ = TimeDelta::FromSeconds(
1354 atoi(reinterpret_cast<char*>(upload_interval_val)));
1355 }
1356
1357 server_permits_upload_ = uploadOn;
1358 }
1359 if (path == "/upload/logs") {
1360 xmlChar* log_event_limit_val = xmlGetProp(node, BAD_CAST "event_limit");
1361 if (log_event_limit_val)
1362 log_event_limit_ = atoi(reinterpret_cast<char*>(log_event_limit_val));
1363 }
1364 if (name == "histogram") {
1365 xmlChar* type_value = xmlGetProp(node, BAD_CAST "type");
1366 if (type_value) {
1367 std::string type = (reinterpret_cast<char*>(type_value));
1368 if (uploadOn)
1369 histograms_to_upload_.insert(type);
1370 else
1371 histograms_to_omit_.insert(type);
1372 }
1373 }
1374 if (name == "log") {
1375 xmlChar* type_value = xmlGetProp(node, BAD_CAST "type");
1376 if (type_value) {
1377 std::string type = (reinterpret_cast<char*>(type_value));
1378 if (uploadOn)
1379 logs_to_upload_.insert(type);
1380 else
1381 logs_to_omit_.insert(type);
1382 }
1383 }
1384
1385 // Recursive call. If the node is a leaf i.e. if it ends in a "/>", then it
1386 // doesn't have children, so node->children is NULL, and this loop doesn't
1387 // call (that's how the recursion ends).
1388 for (xmlNodePtr child_node = node->children;
[email protected]cac78842008-11-27 01:02:201389 child_node;
1390 child_node = child_node->next) {
[email protected]d01b8732008-10-16 02:18:071391 GetSettingsFromUploadNodeRecursive(child_node, props, path, uploadOn);
1392 }
1393}
1394
1395bool MetricsService::NodeProbabilityTest(xmlNodePtr node,
[email protected]cac78842008-11-27 01:02:201396 InheritedProperties props) const {
[email protected]d01b8732008-10-16 02:18:071397 // Default value of probability on any node is 1, but recall that
1398 // its parents can already have been rejected for upload.
1399 double probability = 1;
1400
1401 // If a probability is specified in the node, we use it instead.
1402 xmlChar* probability_value = xmlGetProp(node, BAD_CAST "probability");
1403 if (probability_value)
[email protected]0b33f80b2008-12-17 21:34:361404 probability = atoi(reinterpret_cast<char*>(probability_value));
[email protected]d01b8732008-10-16 02:18:071405
1406 return ProbabilityTest(probability, props.salt, props.denominator);
1407}
1408
1409bool MetricsService::ProbabilityTest(double probability,
1410 int salt,
1411 int denominator) const {
1412 // Okay, first we figure out how many of the digits of the
1413 // client_id_ we need in order to make a nice pseudorandomish
1414 // number in the range [0,denominator). Too many digits is
1415 // fine.
[email protected]cac78842008-11-27 01:02:201416 int relevant_digits =
1417 static_cast<int>(log10(static_cast<double>(denominator)) + 1.0);
[email protected]d01b8732008-10-16 02:18:071418
1419 // n is the length of the client_id_ string
1420 size_t n = client_id_.size();
1421
1422 // idnumber is a positive integer generated from the client_id_.
1423 // It plus salt is going to give us our pseudorandom number.
1424 int idnumber = 0;
1425 const char* client_id_c_str = client_id_.c_str();
1426
1427 // Here we hash the relevant digits of the client_id_
1428 // string somehow to get a big integer idnumber (could be negative
1429 // from wraparound)
1430 int big = 1;
[email protected]cac78842008-11-27 01:02:201431 for (size_t j = n - 1; j >= 0; --j) {
1432 idnumber += static_cast<int>(client_id_c_str[j]) * big;
[email protected]d01b8732008-10-16 02:18:071433 big *= 10;
1434 }
1435
1436 // Mod id number by denominator making sure to get a non-negative
1437 // answer.
[email protected]cac78842008-11-27 01:02:201438 idnumber = ((idnumber % denominator) + denominator) % denominator;
[email protected]d01b8732008-10-16 02:18:071439
[email protected]cac78842008-11-27 01:02:201440 // ((idnumber + salt) % denominator) / denominator is in the range [0,1]
[email protected]d01b8732008-10-16 02:18:071441 // if it's less than probability we call that an affirmative coin
1442 // toss.
[email protected]cac78842008-11-27 01:02:201443 return static_cast<double>((idnumber + salt) % denominator) <
1444 probability * denominator;
[email protected]d01b8732008-10-16 02:18:071445}
1446
initial.commit09911bf2008-07-26 23:55:291447void MetricsService::LogWindowChange(NotificationType type,
1448 const NotificationSource& source,
1449 const NotificationDetails& details) {
[email protected]534e54b2008-08-13 15:40:091450 int controller_id = -1;
1451 uintptr_t window_or_tab = source.map_key();
initial.commit09911bf2008-07-26 23:55:291452 MetricsLog::WindowEventType window_type;
1453
1454 // Note: since we stop all logging when a single OTR session is active, it is
1455 // possible that we start getting notifications about a window that we don't
1456 // know about.
[email protected]534e54b2008-08-13 15:40:091457 if (window_map_.find(window_or_tab) == window_map_.end()) {
1458 controller_id = next_window_id_++;
1459 window_map_[window_or_tab] = controller_id;
initial.commit09911bf2008-07-26 23:55:291460 } else {
[email protected]534e54b2008-08-13 15:40:091461 controller_id = window_map_[window_or_tab];
initial.commit09911bf2008-07-26 23:55:291462 }
[email protected]534e54b2008-08-13 15:40:091463 DCHECK(controller_id != -1);
initial.commit09911bf2008-07-26 23:55:291464
[email protected]bfd04a62009-02-01 18:16:561465 switch (type.value) {
1466 case NotificationType::TAB_PARENTED:
1467 case NotificationType::BROWSER_OPENED:
initial.commit09911bf2008-07-26 23:55:291468 window_type = MetricsLog::WINDOW_CREATE;
1469 break;
1470
[email protected]bfd04a62009-02-01 18:16:561471 case NotificationType::TAB_CLOSING:
1472 case NotificationType::BROWSER_CLOSED:
[email protected]534e54b2008-08-13 15:40:091473 window_map_.erase(window_map_.find(window_or_tab));
initial.commit09911bf2008-07-26 23:55:291474 window_type = MetricsLog::WINDOW_DESTROY;
1475 break;
1476
1477 default:
1478 NOTREACHED();
1479 break;
1480 }
1481
[email protected]534e54b2008-08-13 15:40:091482 // TODO(brettw) we should have some kind of ID for the parent.
1483 current_log_->RecordWindowEvent(window_type, controller_id, 0);
initial.commit09911bf2008-07-26 23:55:291484}
1485
1486void MetricsService::LogLoadComplete(NotificationType type,
1487 const NotificationSource& source,
1488 const NotificationDetails& details) {
1489 if (details == NotificationService::NoDetails())
1490 return;
1491
[email protected]68475e602008-08-22 03:21:151492 // TODO(jar): There is a bug causing this to be called too many times, and
1493 // the log overflows. For now, we won't record these events.
1494 UMA_HISTOGRAM_COUNTS(L"UMA.LogLoadComplete called", 1);
1495 return;
1496
initial.commit09911bf2008-07-26 23:55:291497 const Details<LoadNotificationDetails> load_details(details);
[email protected]534e54b2008-08-13 15:40:091498 int controller_id = window_map_[details.map_key()];
1499 current_log_->RecordLoadEvent(controller_id,
initial.commit09911bf2008-07-26 23:55:291500 load_details->url(),
1501 load_details->origin(),
1502 load_details->session_index(),
1503 load_details->load_time());
1504}
1505
[email protected]e73c01972008-08-13 00:18:241506void MetricsService::IncrementPrefValue(const wchar_t* path) {
1507 PrefService* pref = g_browser_process->local_state();
1508 DCHECK(pref);
1509 int value = pref->GetInteger(path);
1510 pref->SetInteger(path, value + 1);
1511}
1512
initial.commit09911bf2008-07-26 23:55:291513void MetricsService::LogLoadStarted() {
[email protected]e73c01972008-08-13 00:18:241514 IncrementPrefValue(prefs::kStabilityPageLoadCount);
[email protected]0b33f80b2008-12-17 21:34:361515 // We need to save the prefs, as page load count is a critical stat, and it
1516 // might be lost due to a crash :-(.
initial.commit09911bf2008-07-26 23:55:291517}
1518
1519void MetricsService::LogRendererInSandbox(bool on_sandbox_desktop) {
1520 PrefService* prefs = g_browser_process->local_state();
1521 DCHECK(prefs);
[email protected]e73c01972008-08-13 00:18:241522 if (on_sandbox_desktop)
1523 IncrementPrefValue(prefs::kSecurityRendererOnSboxDesktop);
1524 else
1525 IncrementPrefValue(prefs::kSecurityRendererOnDefaultDesktop);
initial.commit09911bf2008-07-26 23:55:291526}
1527
1528void MetricsService::LogRendererCrash() {
[email protected]e73c01972008-08-13 00:18:241529 IncrementPrefValue(prefs::kStabilityRendererCrashCount);
initial.commit09911bf2008-07-26 23:55:291530}
1531
1532void MetricsService::LogRendererHang() {
[email protected]e73c01972008-08-13 00:18:241533 IncrementPrefValue(prefs::kStabilityRendererHangCount);
initial.commit09911bf2008-07-26 23:55:291534}
1535
1536void MetricsService::LogPluginChange(NotificationType type,
1537 const NotificationSource& source,
1538 const NotificationDetails& details) {
[email protected]690a99c2009-01-06 16:48:451539 FilePath plugin = Details<PluginProcessInfo>(details)->plugin_path();
initial.commit09911bf2008-07-26 23:55:291540
1541 if (plugin_stats_buffer_.find(plugin) == plugin_stats_buffer_.end()) {
1542 plugin_stats_buffer_[plugin] = PluginStats();
1543 }
1544
1545 PluginStats& stats = plugin_stats_buffer_[plugin];
[email protected]bfd04a62009-02-01 18:16:561546 switch (type.value) {
1547 case NotificationType::PLUGIN_PROCESS_HOST_CONNECTED:
initial.commit09911bf2008-07-26 23:55:291548 stats.process_launches++;
1549 break;
1550
[email protected]bfd04a62009-02-01 18:16:561551 case NotificationType::PLUGIN_INSTANCE_CREATED:
initial.commit09911bf2008-07-26 23:55:291552 stats.instances++;
1553 break;
1554
[email protected]bfd04a62009-02-01 18:16:561555 case NotificationType::PLUGIN_PROCESS_CRASHED:
initial.commit09911bf2008-07-26 23:55:291556 stats.process_crashes++;
1557 break;
1558
1559 default:
[email protected]bfd04a62009-02-01 18:16:561560 NOTREACHED() << "Unexpected notification type " << type.value;
initial.commit09911bf2008-07-26 23:55:291561 return;
1562 }
1563}
1564
1565// Recursively counts the number of bookmarks and folders in node.
[email protected]d8e41ed2008-09-11 15:22:321566static void CountBookmarks(BookmarkNode* node, int* bookmarks, int* folders) {
initial.commit09911bf2008-07-26 23:55:291567 if (node->GetType() == history::StarredEntry::URL)
1568 (*bookmarks)++;
1569 else
1570 (*folders)++;
1571 for (int i = 0; i < node->GetChildCount(); ++i)
1572 CountBookmarks(node->GetChild(i), bookmarks, folders);
1573}
1574
[email protected]d8e41ed2008-09-11 15:22:321575void MetricsService::LogBookmarks(BookmarkNode* node,
initial.commit09911bf2008-07-26 23:55:291576 const wchar_t* num_bookmarks_key,
1577 const wchar_t* num_folders_key) {
1578 DCHECK(node);
1579 int num_bookmarks = 0;
1580 int num_folders = 0;
1581 CountBookmarks(node, &num_bookmarks, &num_folders);
1582 num_folders--; // Don't include the root folder in the count.
1583
1584 PrefService* pref = g_browser_process->local_state();
1585 DCHECK(pref);
1586 pref->SetInteger(num_bookmarks_key, num_bookmarks);
1587 pref->SetInteger(num_folders_key, num_folders);
1588}
1589
[email protected]d8e41ed2008-09-11 15:22:321590void MetricsService::LogBookmarks(BookmarkModel* model) {
initial.commit09911bf2008-07-26 23:55:291591 DCHECK(model);
1592 LogBookmarks(model->GetBookmarkBarNode(),
1593 prefs::kNumBookmarksOnBookmarkBar,
1594 prefs::kNumFoldersOnBookmarkBar);
1595 LogBookmarks(model->other_node(),
1596 prefs::kNumBookmarksInOtherBookmarkFolder,
1597 prefs::kNumFoldersInOtherBookmarkFolder);
1598 ScheduleNextStateSave();
1599}
1600
1601void MetricsService::LogKeywords(const TemplateURLModel* url_model) {
1602 DCHECK(url_model);
1603
1604 PrefService* pref = g_browser_process->local_state();
1605 DCHECK(pref);
1606 pref->SetInteger(prefs::kNumKeywords,
1607 static_cast<int>(url_model->GetTemplateURLs().size()));
1608 ScheduleNextStateSave();
1609}
1610
1611void MetricsService::RecordPluginChanges(PrefService* pref) {
1612 ListValue* plugins = pref->GetMutableList(prefs::kStabilityPluginStats);
1613 DCHECK(plugins);
1614
1615 for (ListValue::iterator value_iter = plugins->begin();
1616 value_iter != plugins->end(); ++value_iter) {
1617 if (!(*value_iter)->IsType(Value::TYPE_DICTIONARY)) {
1618 NOTREACHED();
1619 continue;
1620 }
1621
1622 DictionaryValue* plugin_dict = static_cast<DictionaryValue*>(*value_iter);
[email protected]690a99c2009-01-06 16:48:451623 FilePath::StringType plugin_path_str;
1624 plugin_dict->GetString(prefs::kStabilityPluginPath, &plugin_path_str);
1625 if (plugin_path_str.empty()) {
initial.commit09911bf2008-07-26 23:55:291626 NOTREACHED();
1627 continue;
1628 }
1629
[email protected]690a99c2009-01-06 16:48:451630 FilePath plugin_path(plugin_path_str);
initial.commit09911bf2008-07-26 23:55:291631 if (plugin_stats_buffer_.find(plugin_path) == plugin_stats_buffer_.end())
1632 continue;
1633
1634 PluginStats stats = plugin_stats_buffer_[plugin_path];
1635 if (stats.process_launches) {
1636 int launches = 0;
1637 plugin_dict->GetInteger(prefs::kStabilityPluginLaunches, &launches);
1638 launches += stats.process_launches;
1639 plugin_dict->SetInteger(prefs::kStabilityPluginLaunches, launches);
1640 }
1641 if (stats.process_crashes) {
1642 int crashes = 0;
1643 plugin_dict->GetInteger(prefs::kStabilityPluginCrashes, &crashes);
1644 crashes += stats.process_crashes;
1645 plugin_dict->SetInteger(prefs::kStabilityPluginCrashes, crashes);
1646 }
1647 if (stats.instances) {
1648 int instances = 0;
1649 plugin_dict->GetInteger(prefs::kStabilityPluginInstances, &instances);
1650 instances += stats.instances;
1651 plugin_dict->SetInteger(prefs::kStabilityPluginInstances, instances);
1652 }
1653
1654 plugin_stats_buffer_.erase(plugin_path);
1655 }
1656
1657 // Now go through and add dictionaries for plugins that didn't already have
1658 // reports in Local State.
[email protected]690a99c2009-01-06 16:48:451659 for (std::map<FilePath, PluginStats>::iterator cache_iter =
initial.commit09911bf2008-07-26 23:55:291660 plugin_stats_buffer_.begin();
1661 cache_iter != plugin_stats_buffer_.end(); ++cache_iter) {
[email protected]690a99c2009-01-06 16:48:451662 FilePath plugin_path = cache_iter->first;
initial.commit09911bf2008-07-26 23:55:291663 PluginStats stats = cache_iter->second;
1664 DictionaryValue* plugin_dict = new DictionaryValue;
1665
[email protected]690a99c2009-01-06 16:48:451666 plugin_dict->SetString(prefs::kStabilityPluginPath, plugin_path.value());
initial.commit09911bf2008-07-26 23:55:291667 plugin_dict->SetInteger(prefs::kStabilityPluginLaunches,
1668 stats.process_launches);
1669 plugin_dict->SetInteger(prefs::kStabilityPluginCrashes,
1670 stats.process_crashes);
1671 plugin_dict->SetInteger(prefs::kStabilityPluginInstances,
1672 stats.instances);
1673 plugins->Append(plugin_dict);
1674 }
1675 plugin_stats_buffer_.clear();
1676}
1677
1678bool MetricsService::CanLogNotification(NotificationType type,
1679 const NotificationSource& source,
1680 const NotificationDetails& details) {
1681 // We simply don't log anything to UMA if there is a single off the record
1682 // session visible. The problem is that we always notify using the orginal
1683 // profile in order to simplify notification processing.
1684 return !BrowserList::IsOffTheRecordSessionActive();
1685}
1686
1687void MetricsService::RecordBooleanPrefValue(const wchar_t* path, bool value) {
1688 DCHECK(IsSingleThreaded());
1689
1690 PrefService* pref = g_browser_process->local_state();
1691 DCHECK(pref);
1692
1693 pref->SetBoolean(path, value);
1694 RecordCurrentState(pref);
1695}
1696
1697void MetricsService::RecordCurrentState(PrefService* pref) {
1698 pref->SetString(prefs::kStabilityLastTimestampSec,
1699 Int64ToWString(Time::Now().ToTimeT()));
1700
1701 RecordPluginChanges(pref);
1702}
1703
1704void MetricsService::RecordCurrentHistograms() {
1705 DCHECK(current_log_);
1706
1707 StatisticsRecorder::Histograms histograms;
1708 StatisticsRecorder::GetHistograms(&histograms);
1709 for (StatisticsRecorder::Histograms::iterator it = histograms.begin();
1710 histograms.end() != it;
[email protected]cac78842008-11-27 01:02:201711 ++it) {
initial.commit09911bf2008-07-26 23:55:291712 if ((*it)->flags() & kUmaTargetedHistogramFlag)
[email protected]0b33f80b2008-12-17 21:34:361713 // TODO(petersont): Only record historgrams if they are not precluded by
1714 // the UMA response data.
[email protected]d01b8732008-10-16 02:18:071715 // Bug http://code.google.com/p/chromium/issues/detail?id=2739.
initial.commit09911bf2008-07-26 23:55:291716 RecordHistogram(**it);
1717 }
1718}
1719
1720void MetricsService::RecordHistogram(const Histogram& histogram) {
1721 // Get up-to-date snapshot of sample stats.
1722 Histogram::SampleSet snapshot;
1723 histogram.SnapshotSample(&snapshot);
1724
1725 const std::string& histogram_name = histogram.histogram_name();
1726
1727 // Find the already sent stats, or create an empty set.
1728 LoggedSampleMap::iterator it = logged_samples_.find(histogram_name);
1729 Histogram::SampleSet* already_logged;
1730 if (logged_samples_.end() == it) {
1731 // Add new entry
1732 already_logged = &logged_samples_[histogram.histogram_name()];
1733 already_logged->Resize(histogram); // Complete initialization.
1734 } else {
1735 already_logged = &(it->second);
1736 // Deduct any stats we've already logged from our snapshot.
1737 snapshot.Subtract(*already_logged);
1738 }
1739
1740 // snapshot now contains only a delta to what we've already_logged.
1741
1742 if (snapshot.TotalCount() > 0) {
1743 current_log_->RecordHistogramDelta(histogram, snapshot);
1744 // Add new data into our running total.
1745 already_logged->Add(snapshot);
1746 }
1747}
1748
1749void MetricsService::AddProfileMetric(Profile* profile,
1750 const std::wstring& key,
1751 int value) {
1752 // Restriction of types is needed for writing values. See
1753 // MetricsLog::WriteProfileMetrics.
1754 DCHECK(profile && !key.empty());
1755 PrefService* prefs = g_browser_process->local_state();
1756 DCHECK(prefs);
1757
1758 // Key is stored in prefs, which interpret '.'s as paths. As such, key
1759 // shouldn't have any '.'s in it.
1760 DCHECK(key.find(L'.') == std::wstring::npos);
1761 // The id is most likely an email address. We shouldn't send it to the server.
1762 const std::wstring id_hash =
1763 UTF8ToWide(MetricsLog::CreateBase64Hash(WideToUTF8(profile->GetID())));
1764 DCHECK(id_hash.find('.') == std::string::npos);
1765
1766 DictionaryValue* prof_prefs = prefs->GetMutableDictionary(
1767 prefs::kProfileMetrics);
1768 DCHECK(prof_prefs);
1769 const std::wstring pref_key = std::wstring(prefs::kProfilePrefix) + id_hash +
1770 L"." + key;
1771 prof_prefs->SetInteger(pref_key.c_str(), value);
1772}
1773
1774static bool IsSingleThreaded() {
1775 static int thread_id = 0;
1776 if (!thread_id)
1777 thread_id = GetCurrentThreadId();
1778 return GetCurrentThreadId() == thread_id;
1779}