blob: f2b3323ac529b91c226899c28fd329b6c9c88c89 [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"
initial.commit09911bf2008-07-26 23:55:29181#include "chrome/common/pref_names.h"
182#include "chrome/common/pref_service.h"
[email protected]6e93e522008-08-14 19:28:17183#include "chrome/installer/util/google_update_settings.h"
initial.commit09911bf2008-07-26 23:55:29184#include "googleurl/src/gurl.h"
185#include "net/base/load_flags.h"
186#include "third_party/bzip2/bzlib.h"
187
[email protected]e1acf6f2008-10-27 20:43:33188using base::Time;
189using base::TimeDelta;
190
initial.commit09911bf2008-07-26 23:55:29191// Check to see that we're being called on only one thread.
192static bool IsSingleThreaded();
193
194static const char kMetricsURL[] =
[email protected]0acdfc42009-01-30 01:13:22195 "https://clients4.google.com/firefox/metrics/collect";
initial.commit09911bf2008-07-26 23:55:29196
197static const char kMetricsType[] = "application/vnd.mozilla.metrics.bz2";
198
199// The delay, in seconds, after startup before sending the first log message.
[email protected]252873ef2008-08-04 21:59:45200static const int kInitialInterlogDuration = 60; // one minute
201
202// The default maximum number of events in a log uploaded to the UMA server.
[email protected]0b33f80b2008-12-17 21:34:36203static const int kInitialEventLimit = 2400;
[email protected]68475e602008-08-22 03:21:15204
205// If an upload fails, and the transmission was over this byte count, then we
206// will discard the log, and not try to retransmit it. We also don't persist
207// the log to the prefs for transmission during the next chrome session if this
208// limit is exceeded.
209static const int kUploadLogAvoidRetransmitSize = 50000;
initial.commit09911bf2008-07-26 23:55:29210
211// When we have logs from previous Chrome sessions to send, how long should we
212// delay (in seconds) between each log transmission.
213static const int kUnsentLogDelay = 15; // 15 seconds
214
215// Minimum time a log typically exists before sending, in seconds.
216// This number is supplied by the server, but until we parse it out of a server
217// response, we use this duration to specify how long we should wait before
218// sending the next log. If the channel is busy, such as when there is a
219// failure during an attempt to transmit a previous log, then a log may wait
220// (and continue to accrue now log entries) for a much greater period of time.
[email protected]0eb34fee2009-01-21 08:04:38221static const int kMinSecondsPerLog = 20 * 60; // Twenty minutes.
initial.commit09911bf2008-07-26 23:55:29222
initial.commit09911bf2008-07-26 23:55:29223// When we don't succeed at transmitting a log to a server, we progressively
224// wait longer and longer before sending the next log. This backoff process
225// help reduce load on the server, and makes the amount of backoff vary between
226// clients so that a collision (server overload?) on retransmit is less likely.
227// The following is the constant we use to expand that inter-log duration.
228static const double kBackoff = 1.1;
229// We limit the maximum backoff to be no greater than some multiple of the
230// default kMinSecondsPerLog. The following is that maximum ratio.
231static const int kMaxBackoff = 10;
232
233// Interval, in seconds, between state saves.
234static const int kSaveStateInterval = 5 * 60; // five minutes
235
236// The number of "initial" logs we're willing to save, and hope to send during
237// a future Chrome session. Initial logs contain crash stats, and are pretty
238// small.
239static const size_t kMaxInitialLogsPersisted = 20;
240
241// The number of ongoing logs we're willing to save persistently, and hope to
[email protected]281d2882009-01-20 20:32:42242// send during a this or future sessions. Note that each log may be pretty
initial.commit09911bf2008-07-26 23:55:29243// large, as presumably the related "initial" log wasn't sent (probably nothing
244// was, as the user was probably off-line). As a result, the log probably kept
245// accumulating while the "initial" log was stalled (pending_), and couldn't be
246// sent. As a result, we don't want to save too many of these mega-logs.
247// A "standard shutdown" will create a small log, including just the data that
248// was not yet been transmitted, and that is normal (to have exactly one
249// ongoing_log_ at startup).
[email protected]281d2882009-01-20 20:32:42250static const size_t kMaxOngoingLogsPersisted = 8;
initial.commit09911bf2008-07-26 23:55:29251
252
253// Handles asynchronous fetching of memory details.
254// Will run the provided task after finished.
255class MetricsMemoryDetails : public MemoryDetails {
256 public:
257 explicit MetricsMemoryDetails(Task* completion) : completion_(completion) {}
258
259 virtual void OnDetailsAvailable() {
260 MessageLoop::current()->PostTask(FROM_HERE, completion_);
261 }
262
263 private:
264 Task* completion_;
265 DISALLOW_EVIL_CONSTRUCTORS(MetricsMemoryDetails);
266};
267
268class MetricsService::GetPluginListTaskComplete : public Task {
269 virtual void Run() {
270 g_browser_process->metrics_service()->OnGetPluginListTaskComplete();
271 }
272};
273
274class MetricsService::GetPluginListTask : public Task {
275 public:
276 explicit GetPluginListTask(MessageLoop* callback_loop)
277 : callback_loop_(callback_loop) {}
278
279 virtual void Run() {
280 std::vector<WebPluginInfo> plugins;
281 PluginService::GetInstance()->GetPlugins(false, &plugins);
282
283 callback_loop_->PostTask(FROM_HERE, new GetPluginListTaskComplete());
284 }
285
286 private:
287 MessageLoop* callback_loop_;
288};
289
290// static
291void MetricsService::RegisterPrefs(PrefService* local_state) {
292 DCHECK(IsSingleThreaded());
293 local_state->RegisterStringPref(prefs::kMetricsClientID, L"");
294 local_state->RegisterStringPref(prefs::kMetricsClientIDTimestamp, L"0");
295 local_state->RegisterStringPref(prefs::kStabilityLaunchTimeSec, L"0");
296 local_state->RegisterStringPref(prefs::kStabilityLastTimestampSec, L"0");
297 local_state->RegisterStringPref(prefs::kStabilityUptimeSec, L"0");
298 local_state->RegisterBooleanPref(prefs::kStabilityExitedCleanly, true);
299 local_state->RegisterBooleanPref(prefs::kStabilitySessionEndCompleted, true);
300 local_state->RegisterIntegerPref(prefs::kMetricsSessionID, -1);
301 local_state->RegisterIntegerPref(prefs::kStabilityLaunchCount, 0);
302 local_state->RegisterIntegerPref(prefs::kStabilityCrashCount, 0);
303 local_state->RegisterIntegerPref(prefs::kStabilityIncompleteSessionEndCount,
304 0);
305 local_state->RegisterIntegerPref(prefs::kStabilityPageLoadCount, 0);
306 local_state->RegisterIntegerPref(prefs::kSecurityRendererOnSboxDesktop, 0);
307 local_state->RegisterIntegerPref(prefs::kSecurityRendererOnDefaultDesktop, 0);
308 local_state->RegisterIntegerPref(prefs::kStabilityRendererCrashCount, 0);
309 local_state->RegisterIntegerPref(prefs::kStabilityRendererHangCount, 0);
[email protected]e73c01972008-08-13 00:18:24310 local_state->RegisterIntegerPref(prefs::kStabilityBreakpadRegistrationFail,
311 0);
312 local_state->RegisterIntegerPref(prefs::kStabilityBreakpadRegistrationSuccess,
313 0);
314 local_state->RegisterIntegerPref(prefs::kStabilityDebuggerPresent, 0);
315 local_state->RegisterIntegerPref(prefs::kStabilityDebuggerNotPresent, 0);
316
initial.commit09911bf2008-07-26 23:55:29317 local_state->RegisterDictionaryPref(prefs::kProfileMetrics);
318 local_state->RegisterIntegerPref(prefs::kNumBookmarksOnBookmarkBar, 0);
319 local_state->RegisterIntegerPref(prefs::kNumFoldersOnBookmarkBar, 0);
320 local_state->RegisterIntegerPref(prefs::kNumBookmarksInOtherBookmarkFolder,
321 0);
322 local_state->RegisterIntegerPref(prefs::kNumFoldersInOtherBookmarkFolder, 0);
323 local_state->RegisterIntegerPref(prefs::kNumKeywords, 0);
324 local_state->RegisterListPref(prefs::kMetricsInitialLogs);
325 local_state->RegisterListPref(prefs::kMetricsOngoingLogs);
326}
327
328MetricsService::MetricsService()
[email protected]d01b8732008-10-16 02:18:07329 : recording_active_(false),
330 reporting_active_(false),
331 user_permits_upload_(false),
332 server_permits_upload_(true),
333 state_(INITIALIZED),
initial.commit09911bf2008-07-26 23:55:29334 pending_log_(NULL),
335 pending_log_text_(""),
336 current_fetch_(NULL),
337 current_log_(NULL),
[email protected]d01b8732008-10-16 02:18:07338 idle_since_last_transmission_(false),
initial.commit09911bf2008-07-26 23:55:29339 next_window_id_(0),
340 log_sender_factory_(this),
341 state_saver_factory_(this),
342 logged_samples_(),
[email protected]252873ef2008-08-04 21:59:45343 interlog_duration_(TimeDelta::FromSeconds(kInitialInterlogDuration)),
[email protected]d01b8732008-10-16 02:18:07344 log_event_limit_(kInitialEventLimit),
initial.commit09911bf2008-07-26 23:55:29345 timer_pending_(false) {
346 DCHECK(IsSingleThreaded());
347 InitializeMetricsState();
348}
349
350MetricsService::~MetricsService() {
351 SetRecording(false);
[email protected]d8bc79bf2009-01-28 01:17:58352 if (pending_log_) {
353 delete pending_log_;
354 pending_log_ = NULL;
355 }
356 if (current_log_) {
357 delete current_log_;
358 current_log_ = NULL;
359 }
initial.commit09911bf2008-07-26 23:55:29360}
361
[email protected]d01b8732008-10-16 02:18:07362void MetricsService::SetUserPermitsUpload(bool enabled) {
363 HandleIdleSinceLastTransmission(false);
364 user_permits_upload_ = enabled;
365}
366
367void MetricsService::Start() {
368 SetRecording(true);
369 SetReporting(true);
370}
371
372void MetricsService::StartRecordingOnly() {
373 SetRecording(true);
374 SetReporting(false);
375}
376
377void MetricsService::Stop() {
378 SetReporting(false);
379 SetRecording(false);
380}
381
initial.commit09911bf2008-07-26 23:55:29382void MetricsService::SetRecording(bool enabled) {
383 DCHECK(IsSingleThreaded());
384
[email protected]d01b8732008-10-16 02:18:07385 if (enabled == recording_active_)
initial.commit09911bf2008-07-26 23:55:29386 return;
387
388 if (enabled) {
389 StartRecording();
390 ListenerRegistration(true);
391 } else {
392 // Turn off all observers.
393 ListenerRegistration(false);
394 PushPendingLogsToUnsentLists();
395 DCHECK(!pending_log());
396 if (state_ > INITIAL_LOG_READY && unsent_logs())
397 state_ = SEND_OLD_INITIAL_LOGS;
398 }
[email protected]d01b8732008-10-16 02:18:07399 recording_active_ = enabled;
initial.commit09911bf2008-07-26 23:55:29400}
401
[email protected]d01b8732008-10-16 02:18:07402bool MetricsService::recording_active() const {
initial.commit09911bf2008-07-26 23:55:29403 DCHECK(IsSingleThreaded());
[email protected]d01b8732008-10-16 02:18:07404 return recording_active_;
initial.commit09911bf2008-07-26 23:55:29405}
406
[email protected]d01b8732008-10-16 02:18:07407void MetricsService::SetReporting(bool enable) {
408 if (reporting_active_ != enable) {
409 reporting_active_ = enable;
410 if (reporting_active_)
initial.commit09911bf2008-07-26 23:55:29411 StartLogTransmissionTimer();
412 }
[email protected]d01b8732008-10-16 02:18:07413}
414
415bool MetricsService::reporting_active() const {
416 DCHECK(IsSingleThreaded());
417 return reporting_active_;
initial.commit09911bf2008-07-26 23:55:29418}
419
420void MetricsService::Observe(NotificationType type,
421 const NotificationSource& source,
422 const NotificationDetails& details) {
423 DCHECK(current_log_);
424 DCHECK(IsSingleThreaded());
425
426 if (!CanLogNotification(type, source, details))
427 return;
428
429 switch (type) {
430 case NOTIFY_USER_ACTION:
431 current_log_->RecordUserAction(*Details<const wchar_t*>(details).ptr());
432 break;
433
434 case NOTIFY_BROWSER_OPENED:
435 case NOTIFY_BROWSER_CLOSED:
436 LogWindowChange(type, source, details);
437 break;
438
[email protected]534e54b2008-08-13 15:40:09439 case NOTIFY_TAB_PARENTED:
initial.commit09911bf2008-07-26 23:55:29440 case NOTIFY_TAB_CLOSING:
441 LogWindowChange(type, source, details);
442 break;
443
444 case NOTIFY_LOAD_STOP:
445 LogLoadComplete(type, source, details);
446 break;
447
448 case NOTIFY_LOAD_START:
449 LogLoadStarted();
450 break;
451
452 case NOTIFY_RENDERER_PROCESS_TERMINATED:
453 if (!*Details<bool>(details).ptr())
454 LogRendererCrash();
455 break;
456
457 case NOTIFY_RENDERER_PROCESS_HANG:
458 LogRendererHang();
459 break;
460
461 case NOTIFY_RENDERER_PROCESS_IN_SBOX:
462 LogRendererInSandbox(*Details<bool>(details).ptr());
463 break;
464
465 case NOTIFY_PLUGIN_PROCESS_HOST_CONNECTED:
466 case NOTIFY_PLUGIN_PROCESS_CRASHED:
467 case NOTIFY_PLUGIN_INSTANCE_CREATED:
468 LogPluginChange(type, source, details);
469 break;
470
471 case TEMPLATE_URL_MODEL_LOADED:
472 LogKeywords(Source<TemplateURLModel>(source).ptr());
473 break;
474
475 case NOTIFY_OMNIBOX_OPENED_URL:
476 current_log_->RecordOmniboxOpenedURL(
477 *Details<AutocompleteLog>(details).ptr());
478 break;
479
480 case NOTIFY_BOOKMARK_MODEL_LOADED:
[email protected]d8e41ed2008-09-11 15:22:32481 LogBookmarks(Source<Profile>(source)->GetBookmarkModel());
initial.commit09911bf2008-07-26 23:55:29482 break;
483
484 default:
485 NOTREACHED();
486 break;
487 }
[email protected]d01b8732008-10-16 02:18:07488
489 HandleIdleSinceLastTransmission(false);
490
491 if (current_log_)
[email protected]281d2882009-01-20 20:32:42492 DLOG(INFO) << "METRICS: NUMBER OF EVENTS = " << current_log_->num_events();
[email protected]d01b8732008-10-16 02:18:07493}
494
495void MetricsService::HandleIdleSinceLastTransmission(bool in_idle) {
496 // If there wasn't a lot of action, maybe the computer was asleep, in which
497 // case, the log transmissions should have stopped. Here we start them up
498 // again.
[email protected]cac78842008-11-27 01:02:20499 if (!in_idle && idle_since_last_transmission_)
500 StartLogTransmissionTimer();
501 idle_since_last_transmission_ = in_idle;
initial.commit09911bf2008-07-26 23:55:29502}
503
504void MetricsService::RecordCleanShutdown() {
505 RecordBooleanPrefValue(prefs::kStabilityExitedCleanly, true);
506}
507
508void MetricsService::RecordStartOfSessionEnd() {
509 RecordBooleanPrefValue(prefs::kStabilitySessionEndCompleted, false);
510}
511
512void MetricsService::RecordCompletedSessionEnd() {
513 RecordBooleanPrefValue(prefs::kStabilitySessionEndCompleted, true);
514}
515
[email protected]e73c01972008-08-13 00:18:24516void MetricsService:: RecordBreakpadRegistration(bool success) {
[email protected]68475e602008-08-22 03:21:15517 if (!success)
[email protected]e73c01972008-08-13 00:18:24518 IncrementPrefValue(prefs::kStabilityBreakpadRegistrationFail);
519 else
520 IncrementPrefValue(prefs::kStabilityBreakpadRegistrationSuccess);
521}
522
523void MetricsService::RecordBreakpadHasDebugger(bool has_debugger) {
524 if (!has_debugger)
525 IncrementPrefValue(prefs::kStabilityDebuggerNotPresent);
526 else
[email protected]68475e602008-08-22 03:21:15527 IncrementPrefValue(prefs::kStabilityDebuggerPresent);
[email protected]e73c01972008-08-13 00:18:24528}
529
initial.commit09911bf2008-07-26 23:55:29530//------------------------------------------------------------------------------
531// private methods
532//------------------------------------------------------------------------------
533
534
535//------------------------------------------------------------------------------
536// Initialization methods
537
538void MetricsService::InitializeMetricsState() {
539 PrefService* pref = g_browser_process->local_state();
540 DCHECK(pref);
541
542 client_id_ = WideToUTF8(pref->GetString(prefs::kMetricsClientID));
543 if (client_id_.empty()) {
544 client_id_ = GenerateClientID();
545 pref->SetString(prefs::kMetricsClientID, UTF8ToWide(client_id_));
546
547 // Might as well make a note of how long this ID has existed
548 pref->SetString(prefs::kMetricsClientIDTimestamp,
549 Int64ToWString(Time::Now().ToTimeT()));
550 }
551
552 // Update session ID
553 session_id_ = pref->GetInteger(prefs::kMetricsSessionID);
554 ++session_id_;
555 pref->SetInteger(prefs::kMetricsSessionID, session_id_);
556
initial.commit09911bf2008-07-26 23:55:29557 // Stability bookkeeping
[email protected]e73c01972008-08-13 00:18:24558 IncrementPrefValue(prefs::kStabilityLaunchCount);
initial.commit09911bf2008-07-26 23:55:29559
[email protected]e73c01972008-08-13 00:18:24560 if (!pref->GetBoolean(prefs::kStabilityExitedCleanly)) {
561 IncrementPrefValue(prefs::kStabilityCrashCount);
initial.commit09911bf2008-07-26 23:55:29562 }
[email protected]e73c01972008-08-13 00:18:24563
564 // This will be set to 'true' if we exit cleanly.
initial.commit09911bf2008-07-26 23:55:29565 pref->SetBoolean(prefs::kStabilityExitedCleanly, false);
566
[email protected]e73c01972008-08-13 00:18:24567 if (!pref->GetBoolean(prefs::kStabilitySessionEndCompleted)) {
568 IncrementPrefValue(prefs::kStabilityIncompleteSessionEndCount);
initial.commit09911bf2008-07-26 23:55:29569 }
570 // This is marked false when we get a WM_ENDSESSION.
571 pref->SetBoolean(prefs::kStabilitySessionEndCompleted, true);
572
573 int64 last_start_time =
574 StringToInt64(pref->GetString(prefs::kStabilityLaunchTimeSec));
575 int64 last_end_time =
576 StringToInt64(pref->GetString(prefs::kStabilityLastTimestampSec));
577 int64 uptime =
578 StringToInt64(pref->GetString(prefs::kStabilityUptimeSec));
579
580 if (last_start_time && last_end_time) {
581 // TODO(JAR): Exclude sleep time. ... which must be gathered in UI loop.
582 uptime += last_end_time - last_start_time;
583 pref->SetString(prefs::kStabilityUptimeSec, Int64ToWString(uptime));
584 }
585 pref->SetString(prefs::kStabilityLaunchTimeSec,
586 Int64ToWString(Time::Now().ToTimeT()));
587
588 // Save profile metrics.
589 PrefService* prefs = g_browser_process->local_state();
590 if (prefs) {
591 // Remove the current dictionary and store it for use when sending data to
592 // server. By removing the value we prune potentially dead profiles
593 // (and keys). All valid values are added back once services startup.
594 const DictionaryValue* profile_dictionary =
595 prefs->GetDictionary(prefs::kProfileMetrics);
596 if (profile_dictionary) {
597 // Do a deep copy of profile_dictionary since ClearPref will delete it.
598 profile_dictionary_.reset(static_cast<DictionaryValue*>(
599 profile_dictionary->DeepCopy()));
600 prefs->ClearPref(prefs::kProfileMetrics);
601 }
602 }
603
604 // Kick off the process of saving the state (so the uptime numbers keep
605 // getting updated) every n minutes.
606 ScheduleNextStateSave();
607}
608
609void MetricsService::OnGetPluginListTaskComplete() {
610 DCHECK(state_ == PLUGIN_LIST_REQUESTED);
611 if (state_ == PLUGIN_LIST_REQUESTED)
612 state_ = PLUGIN_LIST_ARRIVED;
613}
614
615std::string MetricsService::GenerateClientID() {
616 const int kGUIDSize = 39;
617
618 GUID guid;
619 HRESULT guid_result = CoCreateGuid(&guid);
620 DCHECK(SUCCEEDED(guid_result));
621
622 std::wstring guid_string;
623 int result = StringFromGUID2(guid,
624 WriteInto(&guid_string, kGUIDSize), kGUIDSize);
625 DCHECK(result == kGUIDSize);
626
627 return WideToUTF8(guid_string.substr(1, guid_string.length() - 2));
628}
629
630
631//------------------------------------------------------------------------------
632// State save methods
633
634void MetricsService::ScheduleNextStateSave() {
635 state_saver_factory_.RevokeAll();
636
637 MessageLoop::current()->PostDelayedTask(FROM_HERE,
638 state_saver_factory_.NewRunnableMethod(&MetricsService::SaveLocalState),
639 kSaveStateInterval * 1000);
640}
641
642void MetricsService::SaveLocalState() {
643 PrefService* pref = g_browser_process->local_state();
644 if (!pref) {
645 NOTREACHED();
646 return;
647 }
648
649 RecordCurrentState(pref);
650 pref->ScheduleSavePersistentPrefs(g_browser_process->file_thread());
651
[email protected]281d2882009-01-20 20:32:42652 // TODO(jar): Does this run down the batteries????
initial.commit09911bf2008-07-26 23:55:29653 ScheduleNextStateSave();
654}
655
656
657//------------------------------------------------------------------------------
658// Recording control methods
659
660void MetricsService::StartRecording() {
661 if (current_log_)
662 return;
663
664 current_log_ = new MetricsLog(client_id_, session_id_);
665 if (state_ == INITIALIZED) {
666 // We only need to schedule that run once.
667 state_ = PLUGIN_LIST_REQUESTED;
668
669 // Make sure the plugin list is loaded before the inital log is sent, so
670 // that the main thread isn't blocked generating the list.
671 g_browser_process->file_thread()->message_loop()->PostDelayedTask(FROM_HERE,
672 new GetPluginListTask(MessageLoop::current()),
[email protected]252873ef2008-08-04 21:59:45673 kInitialInterlogDuration * 1000 / 2);
initial.commit09911bf2008-07-26 23:55:29674 }
675}
676
677void MetricsService::StopRecording(MetricsLog** log) {
678 if (!current_log_)
679 return;
680
[email protected]68475e602008-08-22 03:21:15681 // TODO(jar): Integrate bounds on log recording more consistently, so that we
682 // can stop recording logs that are too big much sooner.
[email protected]d01b8732008-10-16 02:18:07683 if (current_log_->num_events() > log_event_limit_) {
[email protected]68475e602008-08-22 03:21:15684 UMA_HISTOGRAM_COUNTS(L"UMA.Discarded Log Events",
685 current_log_->num_events());
686 current_log_->CloseLog();
687 delete current_log_;
[email protected]294638782008-09-24 00:22:41688 current_log_ = NULL;
[email protected]68475e602008-08-22 03:21:15689 StartRecording(); // Start trivial log to hold our histograms.
690 }
691
[email protected]0b33f80b2008-12-17 21:34:36692 // Put incremental data (histogram deltas, and realtime stats deltas) at the
[email protected]147bbc0b2009-01-06 19:37:40693 // end of all log transmissions (initial log handles this separately).
initial.commit09911bf2008-07-26 23:55:29694 // Don't bother if we're going to discard current_log_.
[email protected]0b33f80b2008-12-17 21:34:36695 if (log) {
696 current_log_->RecordIncrementalStabilityElements();
initial.commit09911bf2008-07-26 23:55:29697 RecordCurrentHistograms();
[email protected]0b33f80b2008-12-17 21:34:36698 }
initial.commit09911bf2008-07-26 23:55:29699
700 current_log_->CloseLog();
[email protected]cac78842008-11-27 01:02:20701 if (log)
initial.commit09911bf2008-07-26 23:55:29702 *log = current_log_;
[email protected]cac78842008-11-27 01:02:20703 else
initial.commit09911bf2008-07-26 23:55:29704 delete current_log_;
initial.commit09911bf2008-07-26 23:55:29705 current_log_ = NULL;
706}
707
708void MetricsService::ListenerRegistration(bool start_listening) {
709 AddOrRemoveObserver(this, NOTIFY_BROWSER_OPENED, start_listening);
710 AddOrRemoveObserver(this, NOTIFY_BROWSER_CLOSED, start_listening);
711 AddOrRemoveObserver(this, NOTIFY_USER_ACTION, start_listening);
[email protected]534e54b2008-08-13 15:40:09712 AddOrRemoveObserver(this, NOTIFY_TAB_PARENTED, start_listening);
initial.commit09911bf2008-07-26 23:55:29713 AddOrRemoveObserver(this, NOTIFY_TAB_CLOSING, start_listening);
714 AddOrRemoveObserver(this, NOTIFY_LOAD_START, start_listening);
715 AddOrRemoveObserver(this, NOTIFY_LOAD_STOP, start_listening);
716 AddOrRemoveObserver(this, NOTIFY_RENDERER_PROCESS_IN_SBOX, start_listening);
717 AddOrRemoveObserver(this, NOTIFY_RENDERER_PROCESS_TERMINATED,
718 start_listening);
719 AddOrRemoveObserver(this, NOTIFY_RENDERER_PROCESS_HANG, start_listening);
720 AddOrRemoveObserver(this, NOTIFY_PLUGIN_PROCESS_HOST_CONNECTED,
721 start_listening);
722 AddOrRemoveObserver(this, NOTIFY_PLUGIN_INSTANCE_CREATED, start_listening);
723 AddOrRemoveObserver(this, NOTIFY_PLUGIN_PROCESS_CRASHED, start_listening);
724 AddOrRemoveObserver(this, TEMPLATE_URL_MODEL_LOADED, start_listening);
725 AddOrRemoveObserver(this, NOTIFY_OMNIBOX_OPENED_URL, start_listening);
726 AddOrRemoveObserver(this, NOTIFY_BOOKMARK_MODEL_LOADED, start_listening);
727}
728
729// static
730void MetricsService::AddOrRemoveObserver(NotificationObserver* observer,
[email protected]cac78842008-11-27 01:02:20731 NotificationType type,
732 bool is_add) {
initial.commit09911bf2008-07-26 23:55:29733 NotificationService* service = NotificationService::current();
734
[email protected]cac78842008-11-27 01:02:20735 if (is_add)
initial.commit09911bf2008-07-26 23:55:29736 service->AddObserver(observer, type, NotificationService::AllSources());
[email protected]cac78842008-11-27 01:02:20737 else
initial.commit09911bf2008-07-26 23:55:29738 service->RemoveObserver(observer, type, NotificationService::AllSources());
initial.commit09911bf2008-07-26 23:55:29739}
740
741void MetricsService::PushPendingLogsToUnsentLists() {
742 if (state_ < INITIAL_LOG_READY)
[email protected]28ab7f92009-01-06 21:39:04743 return; // We didn't and still don't have time to get plugin list etc.
initial.commit09911bf2008-07-26 23:55:29744
745 if (pending_log()) {
746 PreparePendingLogText();
747 if (state_ == INITIAL_LOG_READY) {
748 // We may race here, and send second copy of initial log later.
749 unsent_initial_logs_.push_back(pending_log_text_);
[email protected]d01b8732008-10-16 02:18:07750 state_ = SEND_OLD_INITIAL_LOGS;
initial.commit09911bf2008-07-26 23:55:29751 } else {
[email protected]281d2882009-01-20 20:32:42752 // TODO(jar): Verify correctness in other states, including sending unsent
753 // iniitial logs.
[email protected]68475e602008-08-22 03:21:15754 PushPendingLogTextToUnsentOngoingLogs();
initial.commit09911bf2008-07-26 23:55:29755 }
756 DiscardPendingLog();
757 }
758 DCHECK(!pending_log());
759 StopRecording(&pending_log_);
760 PreparePendingLogText();
[email protected]68475e602008-08-22 03:21:15761 PushPendingLogTextToUnsentOngoingLogs();
initial.commit09911bf2008-07-26 23:55:29762 DiscardPendingLog();
763 StoreUnsentLogs();
764}
765
[email protected]68475e602008-08-22 03:21:15766void MetricsService::PushPendingLogTextToUnsentOngoingLogs() {
[email protected]d01b8732008-10-16 02:18:07767 // If UMA response told us not to upload, there's no need to save the pending
768 // log. It wasn't supposed to be uploaded anyway.
769 if (!server_permits_upload_)
770 return;
771
[email protected]68475e602008-08-22 03:21:15772 if (pending_log_text_.length() > kUploadLogAvoidRetransmitSize) {
773 UMA_HISTOGRAM_COUNTS(L"UMA.Large Accumulated Log Not Persisted",
774 static_cast<int>(pending_log_text_.length()));
775 return;
776 }
777 unsent_ongoing_logs_.push_back(pending_log_text_);
778}
779
initial.commit09911bf2008-07-26 23:55:29780//------------------------------------------------------------------------------
781// Transmission of logs methods
782
783void MetricsService::StartLogTransmissionTimer() {
[email protected]d01b8732008-10-16 02:18:07784 // If we're not reporting, there's no point in starting a log transmission
785 // timer.
786 if (!reporting_active())
787 return;
788
initial.commit09911bf2008-07-26 23:55:29789 if (!current_log_)
790 return; // Recorder is shutdown.
[email protected]d01b8732008-10-16 02:18:07791
792 // If there is already a timer running, we leave it running.
793 // If timer_pending is true because the fetch is waiting for a response,
794 // we return for now and let the response handler start the timer.
795 if (timer_pending_)
initial.commit09911bf2008-07-26 23:55:29796 return;
[email protected]d01b8732008-10-16 02:18:07797
[email protected]d01b8732008-10-16 02:18:07798 // Before starting the timer, set timer_pending_ to true.
initial.commit09911bf2008-07-26 23:55:29799 timer_pending_ = true;
[email protected]d01b8732008-10-16 02:18:07800
801 // Right before the UMA transmission gets started, there's one more thing we'd
802 // like to record: the histogram of memory usage, so we spawn a task to
803 // collect the memory details and when that task is finished, we arrange for
804 // TryToStartTransmission to take over.
initial.commit09911bf2008-07-26 23:55:29805 MessageLoop::current()->PostDelayedTask(FROM_HERE,
806 log_sender_factory_.
807 NewRunnableMethod(&MetricsService::CollectMemoryDetails),
808 static_cast<int>(interlog_duration_.InMilliseconds()));
809}
810
811void MetricsService::TryToStartTransmission() {
812 DCHECK(IsSingleThreaded());
813
[email protected]d01b8732008-10-16 02:18:07814 // This function should only be called via timer, so timer_pending_
815 // should be true.
816 DCHECK(timer_pending_);
817 timer_pending_ = false;
initial.commit09911bf2008-07-26 23:55:29818
819 DCHECK(!current_fetch_.get());
initial.commit09911bf2008-07-26 23:55:29820
[email protected]d01b8732008-10-16 02:18:07821 // If we're getting no notifications, then the log won't have much in it, and
822 // it's possible the computer is about to go to sleep, so don't upload and
823 // don't restart the transmission timer.
824 if (idle_since_last_transmission_)
825 return;
826
827 // If somehow there is a fetch in progress, we return setting timer_pending_
828 // to true and hope things work out.
829 if (current_fetch_.get()) {
830 timer_pending_ = true;
831 return;
832 }
833
834 // If uploads are forbidden by UMA response, there's no point in keeping
835 // the current_log_, and the more often we delete it, the less likely it is
836 // to expand forever.
837 if (!server_permits_upload_ && current_log_) {
838 StopRecording(NULL);
839 StartRecording();
840 }
initial.commit09911bf2008-07-26 23:55:29841
842 if (!current_log_)
843 return; // Logging was disabled.
[email protected]d01b8732008-10-16 02:18:07844 if (!reporting_active())
initial.commit09911bf2008-07-26 23:55:29845 return; // Don't do work if we're not going to send anything now.
846
[email protected]d01b8732008-10-16 02:18:07847 MakePendingLog();
initial.commit09911bf2008-07-26 23:55:29848
[email protected]d01b8732008-10-16 02:18:07849 // MakePendingLog should have put something in the pending log, if it didn't,
850 // we start the timer again, return and hope things work out.
851 if (!pending_log()) {
852 StartLogTransmissionTimer();
853 return;
854 }
initial.commit09911bf2008-07-26 23:55:29855
[email protected]d01b8732008-10-16 02:18:07856 // If we're not supposed to upload any UMA data because the response or the
857 // user said so, cancel the upload at this point, but start the timer.
858 if (!TransmissionPermitted()) {
859 DiscardPendingLog();
860 StartLogTransmissionTimer();
861 return;
862 }
initial.commit09911bf2008-07-26 23:55:29863
[email protected]d01b8732008-10-16 02:18:07864 PrepareFetchWithPendingLog();
865
866 if (!current_fetch_.get()) {
867 // Compression failed, and log discarded :-/.
868 DiscardPendingLog();
869 StartLogTransmissionTimer(); // Maybe we'll do better next time
870 // TODO(jar): If compression failed, we should have created a tiny log and
871 // compressed that, so that we can signal that we're losing logs.
872 return;
873 }
874
875 DCHECK(!timer_pending_);
876
877 // The URL fetch is a like timer in that after a while we get called back
878 // so we set timer_pending_ true just as we start the url fetch.
879 timer_pending_ = true;
880 current_fetch_->Start();
881
882 HandleIdleSinceLastTransmission(true);
883}
884
885
886void MetricsService::MakePendingLog() {
887 if (pending_log())
888 return;
889
890 switch (state_) {
891 case INITIALIZED:
892 case PLUGIN_LIST_REQUESTED: // We should be further along by now.
893 DCHECK(false);
894 return;
895
896 case PLUGIN_LIST_ARRIVED:
897 // We need to wait for the initial log to be ready before sending
898 // anything, because the server will tell us whether it wants to hear
899 // from us.
900 PrepareInitialLog();
901 DCHECK(state_ == PLUGIN_LIST_ARRIVED);
902 RecallUnsentLogs();
903 state_ = INITIAL_LOG_READY;
904 break;
905
906 case SEND_OLD_INITIAL_LOGS:
[email protected]cac78842008-11-27 01:02:20907 if (!unsent_initial_logs_.empty()) {
908 pending_log_text_ = unsent_initial_logs_.back();
909 break;
910 }
[email protected]d01b8732008-10-16 02:18:07911 state_ = SENDING_OLD_LOGS;
912 // Fall through.
initial.commit09911bf2008-07-26 23:55:29913
[email protected]d01b8732008-10-16 02:18:07914 case SENDING_OLD_LOGS:
915 if (!unsent_ongoing_logs_.empty()) {
916 pending_log_text_ = unsent_ongoing_logs_.back();
917 break;
918 }
919 state_ = SENDING_CURRENT_LOGS;
920 // Fall through.
921
922 case SENDING_CURRENT_LOGS:
923 StopRecording(&pending_log_);
924 StartRecording();
925 break;
926
927 default:
928 DCHECK(false);
929 return;
930 }
931
932 DCHECK(pending_log());
933}
934
935bool MetricsService::TransmissionPermitted() const {
936 // If the user forbids uploading that's they're business, and we don't upload
937 // anything. If the server forbids uploading, that's our business, so we take
938 // that to mean it forbids current logs, but we still send up the inital logs
939 // and any old logs.
[email protected]d01b8732008-10-16 02:18:07940 if (!user_permits_upload_)
941 return false;
[email protected]cac78842008-11-27 01:02:20942 if (server_permits_upload_)
[email protected]d01b8732008-10-16 02:18:07943 return true;
initial.commit09911bf2008-07-26 23:55:29944
[email protected]cac78842008-11-27 01:02:20945 switch (state_) {
946 case INITIAL_LOG_READY:
947 case SEND_OLD_INITIAL_LOGS:
948 case SENDING_OLD_LOGS:
949 return true;
950
951 case SENDING_CURRENT_LOGS:
952 default:
953 return false;
[email protected]8c8824b2008-09-20 01:55:50954 }
initial.commit09911bf2008-07-26 23:55:29955}
956
957void MetricsService::CollectMemoryDetails() {
958 Task* task = log_sender_factory_.
959 NewRunnableMethod(&MetricsService::TryToStartTransmission);
960 MetricsMemoryDetails* details = new MetricsMemoryDetails(task);
961 details->StartFetch();
962
963 // Collect WebCore cache information to put into a histogram.
964 for (RenderProcessHost::iterator it = RenderProcessHost::begin();
965 it != RenderProcessHost::end(); ++it) {
966 it->second->Send(new ViewMsg_GetCacheResourceStats());
967 }
968}
969
970void MetricsService::PrepareInitialLog() {
971 DCHECK(state_ == PLUGIN_LIST_ARRIVED);
972 std::vector<WebPluginInfo> plugins;
973 PluginService::GetInstance()->GetPlugins(false, &plugins);
974
975 MetricsLog* log = new MetricsLog(client_id_, session_id_);
976 log->RecordEnvironment(plugins, profile_dictionary_.get());
977
978 // Histograms only get written to current_log_, so setup for the write.
979 MetricsLog* save_log = current_log_;
980 current_log_ = log;
981 RecordCurrentHistograms(); // Into current_log_... which is really log.
982 current_log_ = save_log;
983
984 log->CloseLog();
985 DCHECK(!pending_log());
986 pending_log_ = log;
987}
988
989void MetricsService::RecallUnsentLogs() {
990 DCHECK(unsent_initial_logs_.empty());
991 DCHECK(unsent_ongoing_logs_.empty());
992
993 PrefService* local_state = g_browser_process->local_state();
994 DCHECK(local_state);
995
996 ListValue* unsent_initial_logs = local_state->GetMutableList(
997 prefs::kMetricsInitialLogs);
998 for (ListValue::iterator it = unsent_initial_logs->begin();
999 it != unsent_initial_logs->end(); ++it) {
[email protected]5e324b72008-12-18 00:07:591000 std::string log;
1001 (*it)->GetAsString(&log);
1002 unsent_initial_logs_.push_back(log);
initial.commit09911bf2008-07-26 23:55:291003 }
1004
1005 ListValue* unsent_ongoing_logs = local_state->GetMutableList(
1006 prefs::kMetricsOngoingLogs);
1007 for (ListValue::iterator it = unsent_ongoing_logs->begin();
1008 it != unsent_ongoing_logs->end(); ++it) {
[email protected]5e324b72008-12-18 00:07:591009 std::string log;
1010 (*it)->GetAsString(&log);
1011 unsent_ongoing_logs_.push_back(log);
initial.commit09911bf2008-07-26 23:55:291012 }
1013}
1014
1015void MetricsService::StoreUnsentLogs() {
1016 if (state_ < INITIAL_LOG_READY)
1017 return; // We never Recalled the prior unsent logs.
1018
1019 PrefService* local_state = g_browser_process->local_state();
1020 DCHECK(local_state);
1021
1022 ListValue* unsent_initial_logs = local_state->GetMutableList(
1023 prefs::kMetricsInitialLogs);
1024 unsent_initial_logs->Clear();
1025 size_t start = 0;
1026 if (unsent_initial_logs_.size() > kMaxInitialLogsPersisted)
1027 start = unsent_initial_logs_.size() - kMaxInitialLogsPersisted;
1028 for (size_t i = start; i < unsent_initial_logs_.size(); ++i)
1029 unsent_initial_logs->Append(
[email protected]5e324b72008-12-18 00:07:591030 Value::CreateStringValue(unsent_initial_logs_[i]));
initial.commit09911bf2008-07-26 23:55:291031
1032 ListValue* unsent_ongoing_logs = local_state->GetMutableList(
1033 prefs::kMetricsOngoingLogs);
1034 unsent_ongoing_logs->Clear();
1035 start = 0;
1036 if (unsent_ongoing_logs_.size() > kMaxOngoingLogsPersisted)
1037 start = unsent_ongoing_logs_.size() - kMaxOngoingLogsPersisted;
1038 for (size_t i = start; i < unsent_ongoing_logs_.size(); ++i)
1039 unsent_ongoing_logs->Append(
[email protected]5e324b72008-12-18 00:07:591040 Value::CreateStringValue(unsent_ongoing_logs_[i]));
initial.commit09911bf2008-07-26 23:55:291041}
1042
1043void MetricsService::PreparePendingLogText() {
1044 DCHECK(pending_log());
1045 if (!pending_log_text_.empty())
1046 return;
1047 int original_size = pending_log_->GetEncodedLogSize();
1048 pending_log_->GetEncodedLog(WriteInto(&pending_log_text_, original_size),
1049 original_size);
1050}
1051
[email protected]d01b8732008-10-16 02:18:071052void MetricsService::PrepareFetchWithPendingLog() {
initial.commit09911bf2008-07-26 23:55:291053 DCHECK(pending_log());
1054 DCHECK(!current_fetch_.get());
1055 PreparePendingLogText();
1056 DCHECK(!pending_log_text_.empty());
1057
1058 // Allow security conscious users to see all metrics logs that we send.
1059 LOG(INFO) << "METRICS LOG: " << pending_log_text_;
1060
1061 std::string compressed_log;
[email protected]cac78842008-11-27 01:02:201062 if (!Bzip2Compress(pending_log_text_, &compressed_log)) {
initial.commit09911bf2008-07-26 23:55:291063 NOTREACHED() << "Failed to compress log for transmission.";
1064 DiscardPendingLog();
1065 StartLogTransmissionTimer(); // Maybe we'll do better on next log :-/.
1066 return;
1067 }
[email protected]cac78842008-11-27 01:02:201068
initial.commit09911bf2008-07-26 23:55:291069 current_fetch_.reset(new URLFetcher(GURL(kMetricsURL), URLFetcher::POST,
1070 this));
1071 current_fetch_->set_request_context(Profile::GetDefaultRequestContext());
1072 current_fetch_->set_upload_data(kMetricsType, compressed_log);
initial.commit09911bf2008-07-26 23:55:291073}
1074
1075void MetricsService::DiscardPendingLog() {
1076 if (pending_log_) { // Shutdown might have deleted it!
1077 delete pending_log_;
1078 pending_log_ = NULL;
1079 }
1080 pending_log_text_.clear();
1081}
1082
1083// This implementation is based on the Firefox MetricsService implementation.
1084bool MetricsService::Bzip2Compress(const std::string& input,
1085 std::string* output) {
1086 bz_stream stream = {0};
1087 // As long as our input is smaller than the bzip2 block size, we should get
1088 // the best compression. For example, if your input was 250k, using a block
1089 // size of 300k or 500k should result in the same compression ratio. Since
1090 // our data should be under 100k, using the minimum block size of 100k should
1091 // allocate less temporary memory, but result in the same compression ratio.
1092 int result = BZ2_bzCompressInit(&stream,
1093 1, // 100k (min) block size
1094 0, // quiet
1095 0); // default "work factor"
1096 if (result != BZ_OK) { // out of memory?
1097 return false;
1098 }
1099
1100 output->clear();
1101
1102 stream.next_in = const_cast<char*>(input.data());
1103 stream.avail_in = static_cast<int>(input.size());
1104 // NOTE: we don't need a BZ_RUN phase since our input buffer contains
1105 // the entire input
1106 do {
1107 output->resize(output->size() + 1024);
1108 stream.next_out = &((*output)[stream.total_out_lo32]);
1109 stream.avail_out = static_cast<int>(output->size()) - stream.total_out_lo32;
1110 result = BZ2_bzCompress(&stream, BZ_FINISH);
1111 } while (result == BZ_FINISH_OK);
1112 if (result != BZ_STREAM_END) // unknown failure?
1113 return false;
1114 result = BZ2_bzCompressEnd(&stream);
1115 DCHECK(result == BZ_OK);
1116
1117 output->resize(stream.total_out_lo32);
1118
1119 return true;
1120}
1121
1122static const char* StatusToString(const URLRequestStatus& status) {
1123 switch (status.status()) {
1124 case URLRequestStatus::SUCCESS:
1125 return "SUCCESS";
1126
1127 case URLRequestStatus::IO_PENDING:
1128 return "IO_PENDING";
1129
1130 case URLRequestStatus::HANDLED_EXTERNALLY:
1131 return "HANDLED_EXTERNALLY";
1132
1133 case URLRequestStatus::CANCELED:
1134 return "CANCELED";
1135
1136 case URLRequestStatus::FAILED:
1137 return "FAILED";
1138
1139 default:
1140 NOTREACHED();
1141 return "Unknown";
1142 }
1143}
1144
1145void MetricsService::OnURLFetchComplete(const URLFetcher* source,
1146 const GURL& url,
1147 const URLRequestStatus& status,
1148 int response_code,
1149 const ResponseCookies& cookies,
1150 const std::string& data) {
1151 DCHECK(timer_pending_);
1152 timer_pending_ = false;
1153 DCHECK(current_fetch_.get());
1154 current_fetch_.reset(NULL); // We're not allowed to re-use it.
1155
1156 // Confirm send so that we can move on.
[email protected]281d2882009-01-20 20:32:421157 LOG(INFO) << "METRICS RESPONSE CODE: " << response_code << " status=" <<
[email protected]cac78842008-11-27 01:02:201158 StatusToString(status);
[email protected]252873ef2008-08-04 21:59:451159
[email protected]0eb34fee2009-01-21 08:04:381160 // Provide boolean for error recovery (allow us to ignore response_code).
1161 boolean discard_log = false;
1162
[email protected]68475e602008-08-22 03:21:151163 if (response_code != 200 &&
1164 pending_log_text_.length() > kUploadLogAvoidRetransmitSize) {
1165 UMA_HISTOGRAM_COUNTS(L"UMA.Large Rejected Log was Discarded",
1166 static_cast<int>(pending_log_text_.length()));
[email protected]0eb34fee2009-01-21 08:04:381167 discard_log = true;
1168 } else if (response_code == 400) {
1169 // Bad syntax. Retransmission won't work.
1170 UMA_HISTOGRAM_COUNTS(L"UMA.Unacceptable_Log_Discarded", state_);
1171 discard_log = true;
[email protected]68475e602008-08-22 03:21:151172 }
1173
[email protected]0eb34fee2009-01-21 08:04:381174 if (response_code != 200 && !discard_log) {
[email protected]281d2882009-01-20 20:32:421175 LOG(INFO) << "METRICS: transmission attempt returned a failure code: "
1176 << response_code << ". Verify network connectivity";
[email protected]252873ef2008-08-04 21:59:451177 HandleBadResponseCode();
[email protected]0eb34fee2009-01-21 08:04:381178 } else { // Successful receipt (or we are discarding log).
[email protected]281d2882009-01-20 20:32:421179 LOG(INFO) << "METRICS RESPONSE DATA: " << data;
initial.commit09911bf2008-07-26 23:55:291180 switch (state_) {
1181 case INITIAL_LOG_READY:
1182 state_ = SEND_OLD_INITIAL_LOGS;
1183 break;
1184
1185 case SEND_OLD_INITIAL_LOGS:
1186 DCHECK(!unsent_initial_logs_.empty());
1187 unsent_initial_logs_.pop_back();
1188 StoreUnsentLogs();
1189 break;
1190
1191 case SENDING_OLD_LOGS:
1192 DCHECK(!unsent_ongoing_logs_.empty());
1193 unsent_ongoing_logs_.pop_back();
1194 StoreUnsentLogs();
1195 break;
1196
1197 case SENDING_CURRENT_LOGS:
1198 break;
1199
1200 default:
1201 DCHECK(false);
1202 break;
1203 }
[email protected]d01b8732008-10-16 02:18:071204
initial.commit09911bf2008-07-26 23:55:291205 DiscardPendingLog();
[email protected]29be92552008-08-07 22:49:271206 // Since we sent a log, make sure our in-memory state is recorded to disk.
1207 PrefService* local_state = g_browser_process->local_state();
1208 DCHECK(local_state);
1209 if (local_state)
1210 local_state->ScheduleSavePersistentPrefs(
1211 g_browser_process->file_thread());
[email protected]252873ef2008-08-04 21:59:451212
[email protected]147bbc0b2009-01-06 19:37:401213 // Provide a default (free of exponetial backoff, other varances) in case
1214 // the server does not specify a value.
1215 interlog_duration_ = TimeDelta::FromSeconds(kMinSecondsPerLog);
1216
[email protected]252873ef2008-08-04 21:59:451217 GetSettingsFromResponseData(data);
[email protected]252873ef2008-08-04 21:59:451218 // Override server specified interlog delay if there are unsent logs to
[email protected]29be92552008-08-07 22:49:271219 // transmit.
initial.commit09911bf2008-07-26 23:55:291220 if (unsent_logs()) {
1221 DCHECK(state_ < SENDING_CURRENT_LOGS);
1222 interlog_duration_ = TimeDelta::FromSeconds(kUnsentLogDelay);
initial.commit09911bf2008-07-26 23:55:291223 }
1224 }
[email protected]252873ef2008-08-04 21:59:451225
initial.commit09911bf2008-07-26 23:55:291226 StartLogTransmissionTimer();
1227}
1228
[email protected]252873ef2008-08-04 21:59:451229void MetricsService::HandleBadResponseCode() {
[email protected]281d2882009-01-20 20:32:421230 LOG(INFO) << "Verify your metrics logs are formatted correctly. "
[email protected]cac78842008-11-27 01:02:201231 "Verify server is active at " << kMetricsURL;
[email protected]252873ef2008-08-04 21:59:451232 if (!pending_log()) {
[email protected]281d2882009-01-20 20:32:421233 LOG(INFO) << "METRICS: Recorder shutdown during log transmission.";
[email protected]252873ef2008-08-04 21:59:451234 } else {
1235 // Send progressively less frequently.
1236 DCHECK(kBackoff > 1.0);
1237 interlog_duration_ = TimeDelta::FromMicroseconds(
1238 static_cast<int64>(kBackoff * interlog_duration_.InMicroseconds()));
1239
1240 if (kMaxBackoff * TimeDelta::FromSeconds(kMinSecondsPerLog) <
[email protected]cac78842008-11-27 01:02:201241 interlog_duration_) {
[email protected]252873ef2008-08-04 21:59:451242 interlog_duration_ = kMaxBackoff *
1243 TimeDelta::FromSeconds(kMinSecondsPerLog);
[email protected]cac78842008-11-27 01:02:201244 }
[email protected]252873ef2008-08-04 21:59:451245
[email protected]281d2882009-01-20 20:32:421246 LOG(INFO) << "METRICS: transmission retry being scheduled in " <<
[email protected]252873ef2008-08-04 21:59:451247 interlog_duration_.InSeconds() << " seconds for " <<
1248 pending_log_text_;
initial.commit09911bf2008-07-26 23:55:291249 }
initial.commit09911bf2008-07-26 23:55:291250}
1251
[email protected]252873ef2008-08-04 21:59:451252void MetricsService::GetSettingsFromResponseData(const std::string& data) {
1253 // We assume that the file is structured as a block opened by <response>
[email protected]d01b8732008-10-16 02:18:071254 // and that inside response, there is a block opened by tag <chrome_config>
1255 // other tags are ignored for now except the content of <chrome_config>.
[email protected]281d2882009-01-20 20:32:421256 LOG(INFO) << "METRICS: getting settings from response data: " << data;
[email protected]d01b8732008-10-16 02:18:071257
[email protected]252873ef2008-08-04 21:59:451258 int data_size = static_cast<int>(data.size());
1259 if (data_size < 0) {
[email protected]281d2882009-01-20 20:32:421260 LOG(INFO) << "METRICS: server response data bad size: " << data_size <<
[email protected]cac78842008-11-27 01:02:201261 "; aborting extraction of settings";
[email protected]252873ef2008-08-04 21:59:451262 return;
1263 }
[email protected]cac78842008-11-27 01:02:201264 xmlDocPtr doc = xmlReadMemory(data.c_str(), data_size, "", NULL, 0);
[email protected]252873ef2008-08-04 21:59:451265 DCHECK(doc);
[email protected]d01b8732008-10-16 02:18:071266 // If the document is malformed, we just use the settings that were there.
1267 if (!doc) {
[email protected]281d2882009-01-20 20:32:421268 LOG(INFO) << "METRICS: reading xml from server response data failed";
[email protected]252873ef2008-08-04 21:59:451269 return;
[email protected]d01b8732008-10-16 02:18:071270 }
[email protected]252873ef2008-08-04 21:59:451271
[email protected]d01b8732008-10-16 02:18:071272 xmlNodePtr top_node = xmlDocGetRootElement(doc), chrome_config_node = NULL;
1273 // Here, we find the chrome_config node by name.
[email protected]252873ef2008-08-04 21:59:451274 for (xmlNodePtr p = top_node->children; p; p = p->next) {
[email protected]d01b8732008-10-16 02:18:071275 if (xmlStrEqual(p->name, BAD_CAST "chrome_config")) {
1276 chrome_config_node = p;
[email protected]252873ef2008-08-04 21:59:451277 break;
1278 }
1279 }
1280 // If the server data is formatted wrong and there is no
1281 // config node where we expect, we just drop out.
[email protected]d01b8732008-10-16 02:18:071282 if (chrome_config_node != NULL)
1283 GetSettingsFromChromeConfigNode(chrome_config_node);
[email protected]252873ef2008-08-04 21:59:451284 xmlFreeDoc(doc);
1285}
1286
[email protected]d01b8732008-10-16 02:18:071287void MetricsService::GetSettingsFromChromeConfigNode(
1288 xmlNodePtr chrome_config_node) {
1289 // Iterate through all children of the config node.
1290 for (xmlNodePtr current_node = chrome_config_node->children;
1291 current_node;
1292 current_node = current_node->next) {
1293 // If we find the upload tag, we appeal to another function
1294 // GetSettingsFromUploadNode to read all the data in it.
[email protected]252873ef2008-08-04 21:59:451295 if (xmlStrEqual(current_node->name, BAD_CAST "upload")) {
[email protected]d01b8732008-10-16 02:18:071296 GetSettingsFromUploadNode(current_node);
[email protected]252873ef2008-08-04 21:59:451297 continue;
1298 }
1299 }
1300}
initial.commit09911bf2008-07-26 23:55:291301
[email protected]d01b8732008-10-16 02:18:071302void MetricsService::InheritedProperties::OverwriteWhereNeeded(
1303 xmlNodePtr node) {
1304 xmlChar* salt_value = xmlGetProp(node, BAD_CAST "salt");
1305 if (salt_value) // If the property isn't there, xmlGetProp returns NULL.
1306 salt = atoi(reinterpret_cast<char*>(salt_value));
1307 // If the property isn't there, we keep the value the property had before
1308
1309 xmlChar* denominator_value = xmlGetProp(node, BAD_CAST "denominator");
1310 if (denominator_value)
1311 denominator = atoi(reinterpret_cast<char*>(denominator_value));
1312}
1313
1314void MetricsService::GetSettingsFromUploadNode(xmlNodePtr upload_node) {
1315 InheritedProperties props;
1316 GetSettingsFromUploadNodeRecursive(upload_node, props, "", true);
1317}
1318
[email protected]cac78842008-11-27 01:02:201319void MetricsService::GetSettingsFromUploadNodeRecursive(
1320 xmlNodePtr node,
1321 InheritedProperties props,
1322 std::string path_prefix,
1323 bool uploadOn) {
[email protected]d01b8732008-10-16 02:18:071324 props.OverwriteWhereNeeded(node);
1325
1326 // The bool uploadOn is set to true if the data represented by current
1327 // node should be uploaded. This gets inherited in the tree; the children
1328 // of a node that has already been rejected for upload get rejected for
1329 // upload.
1330 uploadOn = uploadOn && NodeProbabilityTest(node, props);
1331
1332 // The path is a / separated list of the node names ancestral to the current
1333 // one. So, if you want to check if the current node has a certain name,
1334 // compare to name. If you want to check if it is a certan tag at a certain
1335 // place in the tree, compare to the whole path.
1336 std::string name = std::string(reinterpret_cast<const char*>(node->name));
1337 std::string path = path_prefix + "/" + name;
1338
1339 if (path == "/upload") {
1340 xmlChar* upload_interval_val = xmlGetProp(node, BAD_CAST "interval");
1341 if (upload_interval_val) {
1342 interlog_duration_ = TimeDelta::FromSeconds(
1343 atoi(reinterpret_cast<char*>(upload_interval_val)));
1344 }
1345
1346 server_permits_upload_ = uploadOn;
1347 }
1348 if (path == "/upload/logs") {
1349 xmlChar* log_event_limit_val = xmlGetProp(node, BAD_CAST "event_limit");
1350 if (log_event_limit_val)
1351 log_event_limit_ = atoi(reinterpret_cast<char*>(log_event_limit_val));
1352 }
1353 if (name == "histogram") {
1354 xmlChar* type_value = xmlGetProp(node, BAD_CAST "type");
1355 if (type_value) {
1356 std::string type = (reinterpret_cast<char*>(type_value));
1357 if (uploadOn)
1358 histograms_to_upload_.insert(type);
1359 else
1360 histograms_to_omit_.insert(type);
1361 }
1362 }
1363 if (name == "log") {
1364 xmlChar* type_value = xmlGetProp(node, BAD_CAST "type");
1365 if (type_value) {
1366 std::string type = (reinterpret_cast<char*>(type_value));
1367 if (uploadOn)
1368 logs_to_upload_.insert(type);
1369 else
1370 logs_to_omit_.insert(type);
1371 }
1372 }
1373
1374 // Recursive call. If the node is a leaf i.e. if it ends in a "/>", then it
1375 // doesn't have children, so node->children is NULL, and this loop doesn't
1376 // call (that's how the recursion ends).
1377 for (xmlNodePtr child_node = node->children;
[email protected]cac78842008-11-27 01:02:201378 child_node;
1379 child_node = child_node->next) {
[email protected]d01b8732008-10-16 02:18:071380 GetSettingsFromUploadNodeRecursive(child_node, props, path, uploadOn);
1381 }
1382}
1383
1384bool MetricsService::NodeProbabilityTest(xmlNodePtr node,
[email protected]cac78842008-11-27 01:02:201385 InheritedProperties props) const {
[email protected]d01b8732008-10-16 02:18:071386 // Default value of probability on any node is 1, but recall that
1387 // its parents can already have been rejected for upload.
1388 double probability = 1;
1389
1390 // If a probability is specified in the node, we use it instead.
1391 xmlChar* probability_value = xmlGetProp(node, BAD_CAST "probability");
1392 if (probability_value)
[email protected]0b33f80b2008-12-17 21:34:361393 probability = atoi(reinterpret_cast<char*>(probability_value));
[email protected]d01b8732008-10-16 02:18:071394
1395 return ProbabilityTest(probability, props.salt, props.denominator);
1396}
1397
1398bool MetricsService::ProbabilityTest(double probability,
1399 int salt,
1400 int denominator) const {
1401 // Okay, first we figure out how many of the digits of the
1402 // client_id_ we need in order to make a nice pseudorandomish
1403 // number in the range [0,denominator). Too many digits is
1404 // fine.
[email protected]cac78842008-11-27 01:02:201405 int relevant_digits =
1406 static_cast<int>(log10(static_cast<double>(denominator)) + 1.0);
[email protected]d01b8732008-10-16 02:18:071407
1408 // n is the length of the client_id_ string
1409 size_t n = client_id_.size();
1410
1411 // idnumber is a positive integer generated from the client_id_.
1412 // It plus salt is going to give us our pseudorandom number.
1413 int idnumber = 0;
1414 const char* client_id_c_str = client_id_.c_str();
1415
1416 // Here we hash the relevant digits of the client_id_
1417 // string somehow to get a big integer idnumber (could be negative
1418 // from wraparound)
1419 int big = 1;
[email protected]cac78842008-11-27 01:02:201420 for (size_t j = n - 1; j >= 0; --j) {
1421 idnumber += static_cast<int>(client_id_c_str[j]) * big;
[email protected]d01b8732008-10-16 02:18:071422 big *= 10;
1423 }
1424
1425 // Mod id number by denominator making sure to get a non-negative
1426 // answer.
[email protected]cac78842008-11-27 01:02:201427 idnumber = ((idnumber % denominator) + denominator) % denominator;
[email protected]d01b8732008-10-16 02:18:071428
[email protected]cac78842008-11-27 01:02:201429 // ((idnumber + salt) % denominator) / denominator is in the range [0,1]
[email protected]d01b8732008-10-16 02:18:071430 // if it's less than probability we call that an affirmative coin
1431 // toss.
[email protected]cac78842008-11-27 01:02:201432 return static_cast<double>((idnumber + salt) % denominator) <
1433 probability * denominator;
[email protected]d01b8732008-10-16 02:18:071434}
1435
initial.commit09911bf2008-07-26 23:55:291436void MetricsService::LogWindowChange(NotificationType type,
1437 const NotificationSource& source,
1438 const NotificationDetails& details) {
[email protected]534e54b2008-08-13 15:40:091439 int controller_id = -1;
1440 uintptr_t window_or_tab = source.map_key();
initial.commit09911bf2008-07-26 23:55:291441 MetricsLog::WindowEventType window_type;
1442
1443 // Note: since we stop all logging when a single OTR session is active, it is
1444 // possible that we start getting notifications about a window that we don't
1445 // know about.
[email protected]534e54b2008-08-13 15:40:091446 if (window_map_.find(window_or_tab) == window_map_.end()) {
1447 controller_id = next_window_id_++;
1448 window_map_[window_or_tab] = controller_id;
initial.commit09911bf2008-07-26 23:55:291449 } else {
[email protected]534e54b2008-08-13 15:40:091450 controller_id = window_map_[window_or_tab];
initial.commit09911bf2008-07-26 23:55:291451 }
[email protected]534e54b2008-08-13 15:40:091452 DCHECK(controller_id != -1);
initial.commit09911bf2008-07-26 23:55:291453
1454 switch (type) {
[email protected]534e54b2008-08-13 15:40:091455 case NOTIFY_TAB_PARENTED:
initial.commit09911bf2008-07-26 23:55:291456 case NOTIFY_BROWSER_OPENED:
1457 window_type = MetricsLog::WINDOW_CREATE;
1458 break;
1459
1460 case NOTIFY_TAB_CLOSING:
1461 case NOTIFY_BROWSER_CLOSED:
[email protected]534e54b2008-08-13 15:40:091462 window_map_.erase(window_map_.find(window_or_tab));
initial.commit09911bf2008-07-26 23:55:291463 window_type = MetricsLog::WINDOW_DESTROY;
1464 break;
1465
1466 default:
1467 NOTREACHED();
1468 break;
1469 }
1470
[email protected]534e54b2008-08-13 15:40:091471 // TODO(brettw) we should have some kind of ID for the parent.
1472 current_log_->RecordWindowEvent(window_type, controller_id, 0);
initial.commit09911bf2008-07-26 23:55:291473}
1474
1475void MetricsService::LogLoadComplete(NotificationType type,
1476 const NotificationSource& source,
1477 const NotificationDetails& details) {
1478 if (details == NotificationService::NoDetails())
1479 return;
1480
[email protected]68475e602008-08-22 03:21:151481 // TODO(jar): There is a bug causing this to be called too many times, and
1482 // the log overflows. For now, we won't record these events.
1483 UMA_HISTOGRAM_COUNTS(L"UMA.LogLoadComplete called", 1);
1484 return;
1485
initial.commit09911bf2008-07-26 23:55:291486 const Details<LoadNotificationDetails> load_details(details);
[email protected]534e54b2008-08-13 15:40:091487 int controller_id = window_map_[details.map_key()];
1488 current_log_->RecordLoadEvent(controller_id,
initial.commit09911bf2008-07-26 23:55:291489 load_details->url(),
1490 load_details->origin(),
1491 load_details->session_index(),
1492 load_details->load_time());
1493}
1494
[email protected]e73c01972008-08-13 00:18:241495void MetricsService::IncrementPrefValue(const wchar_t* path) {
1496 PrefService* pref = g_browser_process->local_state();
1497 DCHECK(pref);
1498 int value = pref->GetInteger(path);
1499 pref->SetInteger(path, value + 1);
1500}
1501
initial.commit09911bf2008-07-26 23:55:291502void MetricsService::LogLoadStarted() {
[email protected]e73c01972008-08-13 00:18:241503 IncrementPrefValue(prefs::kStabilityPageLoadCount);
[email protected]0b33f80b2008-12-17 21:34:361504 // We need to save the prefs, as page load count is a critical stat, and it
1505 // might be lost due to a crash :-(.
initial.commit09911bf2008-07-26 23:55:291506}
1507
1508void MetricsService::LogRendererInSandbox(bool on_sandbox_desktop) {
1509 PrefService* prefs = g_browser_process->local_state();
1510 DCHECK(prefs);
[email protected]e73c01972008-08-13 00:18:241511 if (on_sandbox_desktop)
1512 IncrementPrefValue(prefs::kSecurityRendererOnSboxDesktop);
1513 else
1514 IncrementPrefValue(prefs::kSecurityRendererOnDefaultDesktop);
initial.commit09911bf2008-07-26 23:55:291515}
1516
1517void MetricsService::LogRendererCrash() {
[email protected]e73c01972008-08-13 00:18:241518 IncrementPrefValue(prefs::kStabilityRendererCrashCount);
initial.commit09911bf2008-07-26 23:55:291519}
1520
1521void MetricsService::LogRendererHang() {
[email protected]e73c01972008-08-13 00:18:241522 IncrementPrefValue(prefs::kStabilityRendererHangCount);
initial.commit09911bf2008-07-26 23:55:291523}
1524
1525void MetricsService::LogPluginChange(NotificationType type,
1526 const NotificationSource& source,
1527 const NotificationDetails& details) {
[email protected]690a99c2009-01-06 16:48:451528 FilePath plugin = Details<PluginProcessInfo>(details)->plugin_path();
initial.commit09911bf2008-07-26 23:55:291529
1530 if (plugin_stats_buffer_.find(plugin) == plugin_stats_buffer_.end()) {
1531 plugin_stats_buffer_[plugin] = PluginStats();
1532 }
1533
1534 PluginStats& stats = plugin_stats_buffer_[plugin];
1535 switch (type) {
1536 case NOTIFY_PLUGIN_PROCESS_HOST_CONNECTED:
1537 stats.process_launches++;
1538 break;
1539
1540 case NOTIFY_PLUGIN_INSTANCE_CREATED:
1541 stats.instances++;
1542 break;
1543
1544 case NOTIFY_PLUGIN_PROCESS_CRASHED:
1545 stats.process_crashes++;
1546 break;
1547
1548 default:
1549 NOTREACHED() << "Unexpected notification type " << type;
1550 return;
1551 }
1552}
1553
1554// Recursively counts the number of bookmarks and folders in node.
[email protected]d8e41ed2008-09-11 15:22:321555static void CountBookmarks(BookmarkNode* node, int* bookmarks, int* folders) {
initial.commit09911bf2008-07-26 23:55:291556 if (node->GetType() == history::StarredEntry::URL)
1557 (*bookmarks)++;
1558 else
1559 (*folders)++;
1560 for (int i = 0; i < node->GetChildCount(); ++i)
1561 CountBookmarks(node->GetChild(i), bookmarks, folders);
1562}
1563
[email protected]d8e41ed2008-09-11 15:22:321564void MetricsService::LogBookmarks(BookmarkNode* node,
initial.commit09911bf2008-07-26 23:55:291565 const wchar_t* num_bookmarks_key,
1566 const wchar_t* num_folders_key) {
1567 DCHECK(node);
1568 int num_bookmarks = 0;
1569 int num_folders = 0;
1570 CountBookmarks(node, &num_bookmarks, &num_folders);
1571 num_folders--; // Don't include the root folder in the count.
1572
1573 PrefService* pref = g_browser_process->local_state();
1574 DCHECK(pref);
1575 pref->SetInteger(num_bookmarks_key, num_bookmarks);
1576 pref->SetInteger(num_folders_key, num_folders);
1577}
1578
[email protected]d8e41ed2008-09-11 15:22:321579void MetricsService::LogBookmarks(BookmarkModel* model) {
initial.commit09911bf2008-07-26 23:55:291580 DCHECK(model);
1581 LogBookmarks(model->GetBookmarkBarNode(),
1582 prefs::kNumBookmarksOnBookmarkBar,
1583 prefs::kNumFoldersOnBookmarkBar);
1584 LogBookmarks(model->other_node(),
1585 prefs::kNumBookmarksInOtherBookmarkFolder,
1586 prefs::kNumFoldersInOtherBookmarkFolder);
1587 ScheduleNextStateSave();
1588}
1589
1590void MetricsService::LogKeywords(const TemplateURLModel* url_model) {
1591 DCHECK(url_model);
1592
1593 PrefService* pref = g_browser_process->local_state();
1594 DCHECK(pref);
1595 pref->SetInteger(prefs::kNumKeywords,
1596 static_cast<int>(url_model->GetTemplateURLs().size()));
1597 ScheduleNextStateSave();
1598}
1599
1600void MetricsService::RecordPluginChanges(PrefService* pref) {
1601 ListValue* plugins = pref->GetMutableList(prefs::kStabilityPluginStats);
1602 DCHECK(plugins);
1603
1604 for (ListValue::iterator value_iter = plugins->begin();
1605 value_iter != plugins->end(); ++value_iter) {
1606 if (!(*value_iter)->IsType(Value::TYPE_DICTIONARY)) {
1607 NOTREACHED();
1608 continue;
1609 }
1610
1611 DictionaryValue* plugin_dict = static_cast<DictionaryValue*>(*value_iter);
[email protected]690a99c2009-01-06 16:48:451612 FilePath::StringType plugin_path_str;
1613 plugin_dict->GetString(prefs::kStabilityPluginPath, &plugin_path_str);
1614 if (plugin_path_str.empty()) {
initial.commit09911bf2008-07-26 23:55:291615 NOTREACHED();
1616 continue;
1617 }
1618
[email protected]690a99c2009-01-06 16:48:451619 FilePath plugin_path(plugin_path_str);
initial.commit09911bf2008-07-26 23:55:291620 if (plugin_stats_buffer_.find(plugin_path) == plugin_stats_buffer_.end())
1621 continue;
1622
1623 PluginStats stats = plugin_stats_buffer_[plugin_path];
1624 if (stats.process_launches) {
1625 int launches = 0;
1626 plugin_dict->GetInteger(prefs::kStabilityPluginLaunches, &launches);
1627 launches += stats.process_launches;
1628 plugin_dict->SetInteger(prefs::kStabilityPluginLaunches, launches);
1629 }
1630 if (stats.process_crashes) {
1631 int crashes = 0;
1632 plugin_dict->GetInteger(prefs::kStabilityPluginCrashes, &crashes);
1633 crashes += stats.process_crashes;
1634 plugin_dict->SetInteger(prefs::kStabilityPluginCrashes, crashes);
1635 }
1636 if (stats.instances) {
1637 int instances = 0;
1638 plugin_dict->GetInteger(prefs::kStabilityPluginInstances, &instances);
1639 instances += stats.instances;
1640 plugin_dict->SetInteger(prefs::kStabilityPluginInstances, instances);
1641 }
1642
1643 plugin_stats_buffer_.erase(plugin_path);
1644 }
1645
1646 // Now go through and add dictionaries for plugins that didn't already have
1647 // reports in Local State.
[email protected]690a99c2009-01-06 16:48:451648 for (std::map<FilePath, PluginStats>::iterator cache_iter =
initial.commit09911bf2008-07-26 23:55:291649 plugin_stats_buffer_.begin();
1650 cache_iter != plugin_stats_buffer_.end(); ++cache_iter) {
[email protected]690a99c2009-01-06 16:48:451651 FilePath plugin_path = cache_iter->first;
initial.commit09911bf2008-07-26 23:55:291652 PluginStats stats = cache_iter->second;
1653 DictionaryValue* plugin_dict = new DictionaryValue;
1654
[email protected]690a99c2009-01-06 16:48:451655 plugin_dict->SetString(prefs::kStabilityPluginPath, plugin_path.value());
initial.commit09911bf2008-07-26 23:55:291656 plugin_dict->SetInteger(prefs::kStabilityPluginLaunches,
1657 stats.process_launches);
1658 plugin_dict->SetInteger(prefs::kStabilityPluginCrashes,
1659 stats.process_crashes);
1660 plugin_dict->SetInteger(prefs::kStabilityPluginInstances,
1661 stats.instances);
1662 plugins->Append(plugin_dict);
1663 }
1664 plugin_stats_buffer_.clear();
1665}
1666
1667bool MetricsService::CanLogNotification(NotificationType type,
1668 const NotificationSource& source,
1669 const NotificationDetails& details) {
1670 // We simply don't log anything to UMA if there is a single off the record
1671 // session visible. The problem is that we always notify using the orginal
1672 // profile in order to simplify notification processing.
1673 return !BrowserList::IsOffTheRecordSessionActive();
1674}
1675
1676void MetricsService::RecordBooleanPrefValue(const wchar_t* path, bool value) {
1677 DCHECK(IsSingleThreaded());
1678
1679 PrefService* pref = g_browser_process->local_state();
1680 DCHECK(pref);
1681
1682 pref->SetBoolean(path, value);
1683 RecordCurrentState(pref);
1684}
1685
1686void MetricsService::RecordCurrentState(PrefService* pref) {
1687 pref->SetString(prefs::kStabilityLastTimestampSec,
1688 Int64ToWString(Time::Now().ToTimeT()));
1689
1690 RecordPluginChanges(pref);
1691}
1692
1693void MetricsService::RecordCurrentHistograms() {
1694 DCHECK(current_log_);
1695
1696 StatisticsRecorder::Histograms histograms;
1697 StatisticsRecorder::GetHistograms(&histograms);
1698 for (StatisticsRecorder::Histograms::iterator it = histograms.begin();
1699 histograms.end() != it;
[email protected]cac78842008-11-27 01:02:201700 ++it) {
initial.commit09911bf2008-07-26 23:55:291701 if ((*it)->flags() & kUmaTargetedHistogramFlag)
[email protected]0b33f80b2008-12-17 21:34:361702 // TODO(petersont): Only record historgrams if they are not precluded by
1703 // the UMA response data.
[email protected]d01b8732008-10-16 02:18:071704 // Bug http://code.google.com/p/chromium/issues/detail?id=2739.
initial.commit09911bf2008-07-26 23:55:291705 RecordHistogram(**it);
1706 }
1707}
1708
1709void MetricsService::RecordHistogram(const Histogram& histogram) {
1710 // Get up-to-date snapshot of sample stats.
1711 Histogram::SampleSet snapshot;
1712 histogram.SnapshotSample(&snapshot);
1713
1714 const std::string& histogram_name = histogram.histogram_name();
1715
1716 // Find the already sent stats, or create an empty set.
1717 LoggedSampleMap::iterator it = logged_samples_.find(histogram_name);
1718 Histogram::SampleSet* already_logged;
1719 if (logged_samples_.end() == it) {
1720 // Add new entry
1721 already_logged = &logged_samples_[histogram.histogram_name()];
1722 already_logged->Resize(histogram); // Complete initialization.
1723 } else {
1724 already_logged = &(it->second);
1725 // Deduct any stats we've already logged from our snapshot.
1726 snapshot.Subtract(*already_logged);
1727 }
1728
1729 // snapshot now contains only a delta to what we've already_logged.
1730
1731 if (snapshot.TotalCount() > 0) {
1732 current_log_->RecordHistogramDelta(histogram, snapshot);
1733 // Add new data into our running total.
1734 already_logged->Add(snapshot);
1735 }
1736}
1737
1738void MetricsService::AddProfileMetric(Profile* profile,
1739 const std::wstring& key,
1740 int value) {
1741 // Restriction of types is needed for writing values. See
1742 // MetricsLog::WriteProfileMetrics.
1743 DCHECK(profile && !key.empty());
1744 PrefService* prefs = g_browser_process->local_state();
1745 DCHECK(prefs);
1746
1747 // Key is stored in prefs, which interpret '.'s as paths. As such, key
1748 // shouldn't have any '.'s in it.
1749 DCHECK(key.find(L'.') == std::wstring::npos);
1750 // The id is most likely an email address. We shouldn't send it to the server.
1751 const std::wstring id_hash =
1752 UTF8ToWide(MetricsLog::CreateBase64Hash(WideToUTF8(profile->GetID())));
1753 DCHECK(id_hash.find('.') == std::string::npos);
1754
1755 DictionaryValue* prof_prefs = prefs->GetMutableDictionary(
1756 prefs::kProfileMetrics);
1757 DCHECK(prof_prefs);
1758 const std::wstring pref_key = std::wstring(prefs::kProfilePrefix) + id_hash +
1759 L"." + key;
1760 prof_prefs->SetInteger(pref_key.c_str(), value);
1761}
1762
1763static bool IsSingleThreaded() {
1764 static int thread_id = 0;
1765 if (!thread_id)
1766 thread_id = GetCurrentThreadId();
1767 return GetCurrentThreadId() == thread_id;
1768}