blob: fa4d1dbc304b30182e6eeeb939a9278e1f037a32 [file] [log] [blame]
[email protected]79bf0b72009-04-27 21:30:551// Copyright (c) 2006-2009 The Chromium Authors. All rights reserved.
license.botbf09a502008-08-24 00:55:552// Use of this source code is governed by a BSD-style license that can be
3// found in the LICENSE file.
initial.commit09911bf2008-07-26 23:55:294
5
6
7//------------------------------------------------------------------------------
8// Description of the life cycle of a instance of MetricsService.
9//
10// OVERVIEW
11//
12// A MetricsService instance is typically created at application startup. It
13// is the central controller for the acquisition of log data, and the automatic
14// transmission of that log data to an external server. Its major job is to
15// manage logs, grouping them for transmission, and transmitting them. As part
16// of its grouping, MS finalizes logs by including some just-in-time gathered
17// memory statistics, snapshotting the current stats of numerous histograms,
18// closing the logs, translating to XML text, and compressing the results for
19// transmission. Transmission includes submitting a compressed log as data in a
[email protected]281d2882009-01-20 20:32:4220// URL-post, and retransmitting (or retaining at process termination) if the
initial.commit09911bf2008-07-26 23:55:2921// attempted transmission failed. Retention across process terminations is done
22// using the the PrefServices facilities. The format for the retained
23// logs (ones that never got transmitted) is always the uncompressed textual
24// representation.
25//
[email protected]281d2882009-01-20 20:32:4226// Logs fall into one of two categories: "initial logs," and "ongoing logs."
27// There is at most one initial log sent for each complete run of the chromium
initial.commit09911bf2008-07-26 23:55:2928// product (from startup, to browser shutdown). An initial log is generally
29// transmitted some short time (1 minute?) after startup, and includes stats
30// such as recent crash info, the number and types of plugins, etc. The
[email protected]281d2882009-01-20 20:32:4231// external server's response to the initial log conceptually tells this MS if
32// it should continue transmitting logs (during this session). The server
33// response can actually be much more detailed, and always includes (at a
34// minimum) how often additional ongoing logs should be sent.
initial.commit09911bf2008-07-26 23:55:2935//
36// After the above initial log, a series of ongoing logs will be transmitted.
37// The first ongoing log actually begins to accumulate information stating when
38// the MS was first constructed. Note that even though the initial log is
39// commonly sent a full minute after startup, the initial log does not include
40// much in the way of user stats. The most common interlog period (delay)
[email protected]0b33f80b2008-12-17 21:34:3641// is 20 minutes. That time period starts when the first user action causes a
initial.commit09911bf2008-07-26 23:55:2942// logging event. This means that if there is no user action, there may be long
[email protected]281d2882009-01-20 20:32:4243// periods without any (ongoing) log transmissions. Ongoing logs typically
initial.commit09911bf2008-07-26 23:55:2944// contain very detailed records of user activities (ex: opened tab, closed
45// tab, fetched URL, maximized window, etc.) In addition, just before an
46// ongoing log is closed out, a call is made to gather memory statistics. Those
47// memory statistics are deposited into a histogram, and the log finalization
48// code is then called. In the finalization, a call to a Histogram server
49// acquires a list of all local histograms that have been flagged for upload
[email protected]281d2882009-01-20 20:32:4250// to the UMA server. The finalization also acquires a the most recent number
51// of page loads, along with any counts of renderer or plugin crashes.
initial.commit09911bf2008-07-26 23:55:2952//
53// When the browser shuts down, there will typically be a fragment of an ongoing
54// log that has not yet been transmitted. At shutdown time, that fragment
55// is closed (including snapshotting histograms), and converted to text. Note
56// that memory stats are not gathered during shutdown, as gathering *might* be
57// too time consuming. The textual representation of the fragment of the
58// ongoing log is then stored persistently as a string in the PrefServices, for
59// potential transmission during a future run of the product.
60//
61// There are two slightly abnormal shutdown conditions. There is a
62// "disconnected scenario," and a "really fast startup and shutdown" scenario.
63// In the "never connected" situation, the user has (during the running of the
64// process) never established an internet connection. As a result, attempts to
65// transmit the initial log have failed, and a lot(?) of data has accumulated in
66// the ongoing log (which didn't yet get closed, because there was never even a
67// contemplation of sending it). There is also a kindred "lost connection"
68// situation, where a loss of connection prevented an ongoing log from being
69// transmitted, and a (still open) log was stuck accumulating a lot(?) of data,
70// while the earlier log retried its transmission. In both of these
71// disconnected situations, two logs need to be, and are, persistently stored
72// for future transmission.
73//
74// The other unusual shutdown condition, termed "really fast startup and
75// shutdown," involves the deliberate user termination of the process before
76// the initial log is even formed or transmitted. In that situation, no logging
77// is done, but the historical crash statistics remain (unlogged) for inclusion
78// in a future run's initial log. (i.e., we don't lose crash stats).
79//
80// With the above overview, we can now describe the state machine's various
81// stats, based on the State enum specified in the state_ member. Those states
82// are:
83//
84// INITIALIZED, // Constructor was called.
[email protected]28ab7f92009-01-06 21:39:0485// PLUGIN_LIST_REQUESTED, // Waiting for plugin list to be loaded.
initial.commit09911bf2008-07-26 23:55:2986// PLUGIN_LIST_ARRIVED, // Waiting for timer to send initial log.
87// INITIAL_LOG_READY, // Initial log generated, and waiting for reply.
88// SEND_OLD_INITIAL_LOGS, // Sending unsent logs from previous session.
89// SENDING_OLD_LOGS, // Sending unsent logs from previous session.
90// SENDING_CURRENT_LOGS, // Sending standard current logs as they accrue.
91//
92// In more detail, we have:
93//
94// INITIALIZED, // Constructor was called.
95// The MS has been constructed, but has taken no actions to compose the
96// initial log.
97//
[email protected]28ab7f92009-01-06 21:39:0498// PLUGIN_LIST_REQUESTED, // Waiting for plugin list to be loaded.
initial.commit09911bf2008-07-26 23:55:2999// Typically about 30 seconds after startup, a task is sent to a second thread
100// to get the list of plugins. That task will (when complete) make an async
101// callback (via a Task) to indicate the completion.
102//
103// PLUGIN_LIST_ARRIVED, // Waiting for timer to send initial log.
104// The callback has arrived, and it is now possible for an initial log to be
105// created. This callback typically arrives back less than one second after
106// the task is dispatched.
107//
108// INITIAL_LOG_READY, // Initial log generated, and waiting for reply.
109// This state is entered only after an initial log has been composed, and
110// prepared for transmission. It is also the case that any previously unsent
111// logs have been loaded into instance variables for possible transmission.
112//
113// SEND_OLD_INITIAL_LOGS, // Sending unsent logs from previous session.
114// This state indicates that the initial log for this session has been
115// successfully sent and it is now time to send any "initial logs" that were
116// saved from previous sessions. Most commonly, there are none, but all old
117// logs that were "initial logs" must be sent before this state is exited.
118//
119// SENDING_OLD_LOGS, // Sending unsent logs from previous session.
120// This state indicates that there are no more unsent initial logs, and now any
121// ongoing logs from previous sessions should be transmitted. All such logs
122// will be transmitted before exiting this state, and proceeding with ongoing
123// logs from the current session (see next state).
124//
125// SENDING_CURRENT_LOGS, // Sending standard current logs as they accrue.
[email protected]0b33f80b2008-12-17 21:34:36126// Current logs are being accumulated. Typically every 20 minutes a log is
initial.commit09911bf2008-07-26 23:55:29127// closed and finalized for transmission, at the same time as a new log is
128// started.
129//
130// The progression through the above states is simple, and sequential, in the
131// most common use cases. States proceed from INITIAL to SENDING_CURRENT_LOGS,
132// and remain in the latter until shutdown.
133//
134// The one unusual case is when the user asks that we stop logging. When that
135// happens, any pending (transmission in progress) log is pushed into the list
136// of old unsent logs (the appropriate list, depending on whether it is an
137// initial log, or an ongoing log). An addition, any log that is currently
138// accumulating is also finalized, and pushed into the unsent log list. With
[email protected]281d2882009-01-20 20:32:42139// those pushes performed, we regress back to the SEND_OLD_INITIAL_LOGS state in
initial.commit09911bf2008-07-26 23:55:29140// case the user enables log recording again during this session. This way
141// anything we have "pushed back" will be sent automatically if/when we progress
142// back to SENDING_CURRENT_LOG state.
143//
144// Also note that whenever the member variables containing unsent logs are
145// modified (i.e., when we send an old log), we mirror the list of logs into
146// the PrefServices. This ensures that IF we crash, we won't start up and
147// retransmit our old logs again.
148//
149// Due to race conditions, it is always possible that a log file could be sent
150// twice. For example, if a log file is sent, but not yet acknowledged by
151// the external server, and the user shuts down, then a copy of the log may be
152// saved for re-transmission. These duplicates could be filtered out server
[email protected]281d2882009-01-20 20:32:42153// side, but are not expected to be a significant problem.
initial.commit09911bf2008-07-26 23:55:29154//
155//
156//------------------------------------------------------------------------------
157
[email protected]40bcc302009-03-02 20:50:39158#include "chrome/browser/metrics/metrics_service.h"
159
[email protected]dc6f4962009-02-13 01:25:50160#if defined(OS_WIN)
initial.commit09911bf2008-07-26 23:55:29161#include <windows.h>
[email protected]40bcc302009-03-02 20:50:39162#include <objbase.h>
[email protected]dc6f4962009-02-13 01:25:50163#endif
initial.commit09911bf2008-07-26 23:55:29164
[email protected]690a99c2009-01-06 16:48:45165#include "base/file_path.h"
initial.commit09911bf2008-07-26 23:55:29166#include "base/histogram.h"
167#include "base/path_service.h"
[email protected]dc6f4962009-02-13 01:25:50168#include "base/platform_thread.h"
initial.commit09911bf2008-07-26 23:55:29169#include "base/string_util.h"
170#include "base/task.h"
[email protected]d8e41ed2008-09-11 15:22:32171#include "chrome/browser/bookmarks/bookmark_model.h"
initial.commit09911bf2008-07-26 23:55:29172#include "chrome/browser/browser.h"
173#include "chrome/browser/browser_list.h"
174#include "chrome/browser/browser_process.h"
175#include "chrome/browser/load_notification_details.h"
176#include "chrome/browser/memory_details.h"
[email protected]fd49e2d2009-02-20 17:21:30177#include "chrome/browser/plugin_service.h"
initial.commit09911bf2008-07-26 23:55:29178#include "chrome/browser/profile.h"
[email protected]8c8657d62009-01-16 18:31:26179#include "chrome/browser/renderer_host/render_process_host.h"
[email protected]d54e03a52009-01-16 00:31:04180#include "chrome/browser/search_engines/template_url.h"
181#include "chrome/browser/search_engines/template_url_model.h"
[email protected]a27a9382009-02-11 23:55:10182#include "chrome/common/child_process_info.h"
initial.commit09911bf2008-07-26 23:55:29183#include "chrome/common/chrome_paths.h"
[email protected]92745242009-06-12 16:52:21184#include "chrome/common/chrome_switches.h"
[email protected]c9a3ef82009-05-28 22:02:46185#include "chrome/common/histogram_synchronizer.h"
[email protected]252873ef2008-08-04 21:59:45186#include "chrome/common/libxml_utils.h"
[email protected]bfd04a62009-02-01 18:16:56187#include "chrome/common/notification_service.h"
initial.commit09911bf2008-07-26 23:55:29188#include "chrome/common/pref_names.h"
189#include "chrome/common/pref_service.h"
[email protected]e09ba552009-02-05 03:26:29190#include "chrome/common/render_messages.h"
initial.commit09911bf2008-07-26 23:55:29191#include "googleurl/src/gurl.h"
192#include "net/base/load_flags.h"
193#include "third_party/bzip2/bzlib.h"
194
[email protected]dc6f4962009-02-13 01:25:50195#if defined(OS_POSIX)
196// TODO(port): Move these headers above as they are ported.
197#include "chrome/common/temp_scaffolding_stubs.h"
198#else
[email protected]79bf0b72009-04-27 21:30:55199#include "chrome/installer/util/browser_distribution.h"
[email protected]dc6f4962009-02-13 01:25:50200#include "chrome/installer/util/google_update_settings.h"
201#endif
202
[email protected]e1acf6f2008-10-27 20:43:33203using base::Time;
204using base::TimeDelta;
205
initial.commit09911bf2008-07-26 23:55:29206// Check to see that we're being called on only one thread.
207static bool IsSingleThreaded();
208
initial.commit09911bf2008-07-26 23:55:29209static const char kMetricsType[] = "application/vnd.mozilla.metrics.bz2";
210
211// The delay, in seconds, after startup before sending the first log message.
[email protected]252873ef2008-08-04 21:59:45212static const int kInitialInterlogDuration = 60; // one minute
213
[email protected]c9a3ef82009-05-28 22:02:46214// This specifies the amount of time to wait for all renderers to send their
215// data.
216static const int kMaxHistogramGatheringWaitDuration = 60000; // 60 seconds.
217
[email protected]252873ef2008-08-04 21:59:45218// The default maximum number of events in a log uploaded to the UMA server.
[email protected]0b33f80b2008-12-17 21:34:36219static const int kInitialEventLimit = 2400;
[email protected]68475e602008-08-22 03:21:15220
221// If an upload fails, and the transmission was over this byte count, then we
222// will discard the log, and not try to retransmit it. We also don't persist
223// the log to the prefs for transmission during the next chrome session if this
224// limit is exceeded.
225static const int kUploadLogAvoidRetransmitSize = 50000;
initial.commit09911bf2008-07-26 23:55:29226
227// When we have logs from previous Chrome sessions to send, how long should we
228// delay (in seconds) between each log transmission.
229static const int kUnsentLogDelay = 15; // 15 seconds
230
231// Minimum time a log typically exists before sending, in seconds.
232// This number is supplied by the server, but until we parse it out of a server
233// response, we use this duration to specify how long we should wait before
234// sending the next log. If the channel is busy, such as when there is a
235// failure during an attempt to transmit a previous log, then a log may wait
236// (and continue to accrue now log entries) for a much greater period of time.
[email protected]0eb34fee2009-01-21 08:04:38237static const int kMinSecondsPerLog = 20 * 60; // Twenty minutes.
initial.commit09911bf2008-07-26 23:55:29238
initial.commit09911bf2008-07-26 23:55:29239// When we don't succeed at transmitting a log to a server, we progressively
240// wait longer and longer before sending the next log. This backoff process
241// help reduce load on the server, and makes the amount of backoff vary between
242// clients so that a collision (server overload?) on retransmit is less likely.
243// The following is the constant we use to expand that inter-log duration.
244static const double kBackoff = 1.1;
245// We limit the maximum backoff to be no greater than some multiple of the
246// default kMinSecondsPerLog. The following is that maximum ratio.
247static const int kMaxBackoff = 10;
248
249// Interval, in seconds, between state saves.
250static const int kSaveStateInterval = 5 * 60; // five minutes
251
252// The number of "initial" logs we're willing to save, and hope to send during
253// a future Chrome session. Initial logs contain crash stats, and are pretty
254// small.
255static const size_t kMaxInitialLogsPersisted = 20;
256
257// The number of ongoing logs we're willing to save persistently, and hope to
[email protected]281d2882009-01-20 20:32:42258// send during a this or future sessions. Note that each log may be pretty
initial.commit09911bf2008-07-26 23:55:29259// large, as presumably the related "initial" log wasn't sent (probably nothing
260// was, as the user was probably off-line). As a result, the log probably kept
261// accumulating while the "initial" log was stalled (pending_), and couldn't be
262// sent. As a result, we don't want to save too many of these mega-logs.
263// A "standard shutdown" will create a small log, including just the data that
264// was not yet been transmitted, and that is normal (to have exactly one
265// ongoing_log_ at startup).
[email protected]281d2882009-01-20 20:32:42266static const size_t kMaxOngoingLogsPersisted = 8;
initial.commit09911bf2008-07-26 23:55:29267
268
269// Handles asynchronous fetching of memory details.
270// Will run the provided task after finished.
271class MetricsMemoryDetails : public MemoryDetails {
272 public:
273 explicit MetricsMemoryDetails(Task* completion) : completion_(completion) {}
274
275 virtual void OnDetailsAvailable() {
276 MessageLoop::current()->PostTask(FROM_HERE, completion_);
277 }
278
279 private:
280 Task* completion_;
281 DISALLOW_EVIL_CONSTRUCTORS(MetricsMemoryDetails);
282};
283
284class MetricsService::GetPluginListTaskComplete : public Task {
285 virtual void Run() {
286 g_browser_process->metrics_service()->OnGetPluginListTaskComplete();
287 }
288};
289
290class MetricsService::GetPluginListTask : public Task {
291 public:
292 explicit GetPluginListTask(MessageLoop* callback_loop)
293 : callback_loop_(callback_loop) {}
294
295 virtual void Run() {
296 std::vector<WebPluginInfo> plugins;
297 PluginService::GetInstance()->GetPlugins(false, &plugins);
298
299 callback_loop_->PostTask(FROM_HERE, new GetPluginListTaskComplete());
300 }
301
302 private:
303 MessageLoop* callback_loop_;
304};
305
306// static
307void MetricsService::RegisterPrefs(PrefService* local_state) {
308 DCHECK(IsSingleThreaded());
309 local_state->RegisterStringPref(prefs::kMetricsClientID, L"");
[email protected]0bb1a622009-03-04 03:22:32310 local_state->RegisterInt64Pref(prefs::kMetricsClientIDTimestamp, 0);
311 local_state->RegisterInt64Pref(prefs::kStabilityLaunchTimeSec, 0);
312 local_state->RegisterInt64Pref(prefs::kStabilityLastTimestampSec, 0);
313 local_state->RegisterInt64Pref(prefs::kStabilityUptimeSec, 0);
[email protected]541f77922009-02-23 21:14:38314 local_state->RegisterStringPref(prefs::kStabilityStatsVersion, L"");
initial.commit09911bf2008-07-26 23:55:29315 local_state->RegisterBooleanPref(prefs::kStabilityExitedCleanly, true);
316 local_state->RegisterBooleanPref(prefs::kStabilitySessionEndCompleted, true);
317 local_state->RegisterIntegerPref(prefs::kMetricsSessionID, -1);
318 local_state->RegisterIntegerPref(prefs::kStabilityLaunchCount, 0);
319 local_state->RegisterIntegerPref(prefs::kStabilityCrashCount, 0);
320 local_state->RegisterIntegerPref(prefs::kStabilityIncompleteSessionEndCount,
321 0);
322 local_state->RegisterIntegerPref(prefs::kStabilityPageLoadCount, 0);
323 local_state->RegisterIntegerPref(prefs::kSecurityRendererOnSboxDesktop, 0);
324 local_state->RegisterIntegerPref(prefs::kSecurityRendererOnDefaultDesktop, 0);
325 local_state->RegisterIntegerPref(prefs::kStabilityRendererCrashCount, 0);
326 local_state->RegisterIntegerPref(prefs::kStabilityRendererHangCount, 0);
[email protected]e73c01972008-08-13 00:18:24327 local_state->RegisterIntegerPref(prefs::kStabilityBreakpadRegistrationFail,
328 0);
329 local_state->RegisterIntegerPref(prefs::kStabilityBreakpadRegistrationSuccess,
330 0);
331 local_state->RegisterIntegerPref(prefs::kStabilityDebuggerPresent, 0);
332 local_state->RegisterIntegerPref(prefs::kStabilityDebuggerNotPresent, 0);
333
initial.commit09911bf2008-07-26 23:55:29334 local_state->RegisterDictionaryPref(prefs::kProfileMetrics);
335 local_state->RegisterIntegerPref(prefs::kNumBookmarksOnBookmarkBar, 0);
336 local_state->RegisterIntegerPref(prefs::kNumFoldersOnBookmarkBar, 0);
337 local_state->RegisterIntegerPref(prefs::kNumBookmarksInOtherBookmarkFolder,
338 0);
339 local_state->RegisterIntegerPref(prefs::kNumFoldersInOtherBookmarkFolder, 0);
340 local_state->RegisterIntegerPref(prefs::kNumKeywords, 0);
341 local_state->RegisterListPref(prefs::kMetricsInitialLogs);
342 local_state->RegisterListPref(prefs::kMetricsOngoingLogs);
[email protected]0bb1a622009-03-04 03:22:32343
344 local_state->RegisterInt64Pref(prefs::kUninstallMetricsPageLoadCount, 0);
345 local_state->RegisterInt64Pref(prefs::kUninstallLaunchCount, 0);
[email protected]6b5f21d2009-04-13 17:01:35346 local_state->RegisterInt64Pref(prefs::kUninstallMetricsInstallDate, 0);
[email protected]0bb1a622009-03-04 03:22:32347 local_state->RegisterInt64Pref(prefs::kUninstallMetricsUptimeSec, 0);
348 local_state->RegisterInt64Pref(prefs::kUninstallLastLaunchTimeSec, 0);
349 local_state->RegisterInt64Pref(prefs::kUninstallLastObservedRunTimeSec, 0);
initial.commit09911bf2008-07-26 23:55:29350}
351
[email protected]541f77922009-02-23 21:14:38352// static
353void MetricsService::DiscardOldStabilityStats(PrefService* local_state) {
354 local_state->SetBoolean(prefs::kStabilityExitedCleanly, true);
355
356 local_state->SetInteger(prefs::kStabilityIncompleteSessionEndCount, 0);
357 local_state->SetInteger(prefs::kStabilityBreakpadRegistrationSuccess, 0);
358 local_state->SetInteger(prefs::kStabilityBreakpadRegistrationFail, 0);
359 local_state->SetInteger(prefs::kStabilityDebuggerPresent, 0);
360 local_state->SetInteger(prefs::kStabilityDebuggerNotPresent, 0);
361
362 local_state->SetInteger(prefs::kStabilityLaunchCount, 0);
363 local_state->SetInteger(prefs::kStabilityCrashCount, 0);
364
365 local_state->SetInteger(prefs::kStabilityPageLoadCount, 0);
366 local_state->SetInteger(prefs::kStabilityRendererCrashCount, 0);
367 local_state->SetInteger(prefs::kStabilityRendererHangCount, 0);
368
369 local_state->SetInteger(prefs::kSecurityRendererOnSboxDesktop, 0);
370 local_state->SetInteger(prefs::kSecurityRendererOnDefaultDesktop, 0);
371
372 local_state->SetString(prefs::kStabilityUptimeSec, L"0");
373
374 local_state->ClearPref(prefs::kStabilityPluginStats);
375}
376
initial.commit09911bf2008-07-26 23:55:29377MetricsService::MetricsService()
[email protected]d01b8732008-10-16 02:18:07378 : recording_active_(false),
379 reporting_active_(false),
380 user_permits_upload_(false),
381 server_permits_upload_(true),
382 state_(INITIALIZED),
initial.commit09911bf2008-07-26 23:55:29383 pending_log_(NULL),
384 pending_log_text_(""),
385 current_fetch_(NULL),
386 current_log_(NULL),
[email protected]d01b8732008-10-16 02:18:07387 idle_since_last_transmission_(false),
initial.commit09911bf2008-07-26 23:55:29388 next_window_id_(0),
[email protected]40bcc302009-03-02 20:50:39389 ALLOW_THIS_IN_INITIALIZER_LIST(log_sender_factory_(this)),
390 ALLOW_THIS_IN_INITIALIZER_LIST(state_saver_factory_(this)),
initial.commit09911bf2008-07-26 23:55:29391 logged_samples_(),
[email protected]252873ef2008-08-04 21:59:45392 interlog_duration_(TimeDelta::FromSeconds(kInitialInterlogDuration)),
[email protected]d01b8732008-10-16 02:18:07393 log_event_limit_(kInitialEventLimit),
initial.commit09911bf2008-07-26 23:55:29394 timer_pending_(false) {
395 DCHECK(IsSingleThreaded());
396 InitializeMetricsState();
397}
398
399MetricsService::~MetricsService() {
400 SetRecording(false);
[email protected]d8bc79bf2009-01-28 01:17:58401 if (pending_log_) {
402 delete pending_log_;
403 pending_log_ = NULL;
404 }
405 if (current_log_) {
406 delete current_log_;
407 current_log_ = NULL;
408 }
initial.commit09911bf2008-07-26 23:55:29409}
410
[email protected]d01b8732008-10-16 02:18:07411void MetricsService::SetUserPermitsUpload(bool enabled) {
412 HandleIdleSinceLastTransmission(false);
413 user_permits_upload_ = enabled;
414}
415
416void MetricsService::Start() {
417 SetRecording(true);
418 SetReporting(true);
419}
420
421void MetricsService::StartRecordingOnly() {
422 SetRecording(true);
423 SetReporting(false);
424}
425
426void MetricsService::Stop() {
427 SetReporting(false);
428 SetRecording(false);
429}
430
initial.commit09911bf2008-07-26 23:55:29431void MetricsService::SetRecording(bool enabled) {
432 DCHECK(IsSingleThreaded());
433
[email protected]d01b8732008-10-16 02:18:07434 if (enabled == recording_active_)
initial.commit09911bf2008-07-26 23:55:29435 return;
436
437 if (enabled) {
[email protected]b0c819f2009-03-08 04:52:15438 if (client_id_.empty()) {
439 PrefService* pref = g_browser_process->local_state();
440 DCHECK(pref);
441 client_id_ = WideToUTF8(pref->GetString(prefs::kMetricsClientID));
442 if (client_id_.empty()) {
443 client_id_ = GenerateClientID();
444 pref->SetString(prefs::kMetricsClientID, UTF8ToWide(client_id_));
445
446 // Might as well make a note of how long this ID has existed
447 pref->SetString(prefs::kMetricsClientIDTimestamp,
448 Int64ToWString(Time::Now().ToTimeT()));
449 }
450 }
initial.commit09911bf2008-07-26 23:55:29451 StartRecording();
[email protected]005ef3e2009-05-22 20:55:46452
453 registrar_.Add(this, NotificationType::BROWSER_OPENED,
454 NotificationService::AllSources());
455 registrar_.Add(this, NotificationType::BROWSER_CLOSED,
456 NotificationService::AllSources());
457 registrar_.Add(this, NotificationType::USER_ACTION,
458 NotificationService::AllSources());
459 registrar_.Add(this, NotificationType::TAB_PARENTED,
460 NotificationService::AllSources());
461 registrar_.Add(this, NotificationType::TAB_CLOSING,
462 NotificationService::AllSources());
463 registrar_.Add(this, NotificationType::LOAD_START,
464 NotificationService::AllSources());
465 registrar_.Add(this, NotificationType::LOAD_STOP,
466 NotificationService::AllSources());
467 registrar_.Add(this, NotificationType::RENDERER_PROCESS_IN_SBOX,
468 NotificationService::AllSources());
469 registrar_.Add(this, NotificationType::RENDERER_PROCESS_CLOSED,
470 NotificationService::AllSources());
471 registrar_.Add(this, NotificationType::RENDERER_PROCESS_HANG,
472 NotificationService::AllSources());
473 registrar_.Add(this, NotificationType::CHILD_PROCESS_HOST_CONNECTED,
474 NotificationService::AllSources());
475 registrar_.Add(this, NotificationType::CHILD_INSTANCE_CREATED,
476 NotificationService::AllSources());
477 registrar_.Add(this, NotificationType::CHILD_PROCESS_CRASHED,
478 NotificationService::AllSources());
479 registrar_.Add(this, NotificationType::TEMPLATE_URL_MODEL_LOADED,
480 NotificationService::AllSources());
481 registrar_.Add(this, NotificationType::OMNIBOX_OPENED_URL,
482 NotificationService::AllSources());
483 registrar_.Add(this, NotificationType::BOOKMARK_MODEL_LOADED,
484 NotificationService::AllSources());
initial.commit09911bf2008-07-26 23:55:29485 } else {
[email protected]005ef3e2009-05-22 20:55:46486 registrar_.RemoveAll();
initial.commit09911bf2008-07-26 23:55:29487 PushPendingLogsToUnsentLists();
488 DCHECK(!pending_log());
489 if (state_ > INITIAL_LOG_READY && unsent_logs())
490 state_ = SEND_OLD_INITIAL_LOGS;
491 }
[email protected]d01b8732008-10-16 02:18:07492 recording_active_ = enabled;
initial.commit09911bf2008-07-26 23:55:29493}
494
[email protected]d01b8732008-10-16 02:18:07495bool MetricsService::recording_active() const {
initial.commit09911bf2008-07-26 23:55:29496 DCHECK(IsSingleThreaded());
[email protected]d01b8732008-10-16 02:18:07497 return recording_active_;
initial.commit09911bf2008-07-26 23:55:29498}
499
[email protected]d01b8732008-10-16 02:18:07500void MetricsService::SetReporting(bool enable) {
501 if (reporting_active_ != enable) {
502 reporting_active_ = enable;
503 if (reporting_active_)
initial.commit09911bf2008-07-26 23:55:29504 StartLogTransmissionTimer();
505 }
[email protected]d01b8732008-10-16 02:18:07506}
507
508bool MetricsService::reporting_active() const {
509 DCHECK(IsSingleThreaded());
510 return reporting_active_;
initial.commit09911bf2008-07-26 23:55:29511}
512
513void MetricsService::Observe(NotificationType type,
514 const NotificationSource& source,
515 const NotificationDetails& details) {
516 DCHECK(current_log_);
517 DCHECK(IsSingleThreaded());
518
519 if (!CanLogNotification(type, source, details))
520 return;
521
[email protected]bfd04a62009-02-01 18:16:56522 switch (type.value) {
523 case NotificationType::USER_ACTION:
initial.commit09911bf2008-07-26 23:55:29524 current_log_->RecordUserAction(*Details<const wchar_t*>(details).ptr());
525 break;
526
[email protected]bfd04a62009-02-01 18:16:56527 case NotificationType::BROWSER_OPENED:
528 case NotificationType::BROWSER_CLOSED:
initial.commit09911bf2008-07-26 23:55:29529 LogWindowChange(type, source, details);
530 break;
531
[email protected]bfd04a62009-02-01 18:16:56532 case NotificationType::TAB_PARENTED:
533 case NotificationType::TAB_CLOSING:
initial.commit09911bf2008-07-26 23:55:29534 LogWindowChange(type, source, details);
535 break;
536
[email protected]bfd04a62009-02-01 18:16:56537 case NotificationType::LOAD_STOP:
initial.commit09911bf2008-07-26 23:55:29538 LogLoadComplete(type, source, details);
539 break;
540
[email protected]bfd04a62009-02-01 18:16:56541 case NotificationType::LOAD_START:
initial.commit09911bf2008-07-26 23:55:29542 LogLoadStarted();
543 break;
544
[email protected]6ba2ec22009-05-05 00:50:53545 case NotificationType::RENDERER_PROCESS_CLOSED:
546 if (*Details<bool>(details).ptr())
547 LogRendererCrash();
initial.commit09911bf2008-07-26 23:55:29548 break;
549
[email protected]bfd04a62009-02-01 18:16:56550 case NotificationType::RENDERER_PROCESS_HANG:
initial.commit09911bf2008-07-26 23:55:29551 LogRendererHang();
552 break;
553
[email protected]bfd04a62009-02-01 18:16:56554 case NotificationType::RENDERER_PROCESS_IN_SBOX:
initial.commit09911bf2008-07-26 23:55:29555 LogRendererInSandbox(*Details<bool>(details).ptr());
556 break;
557
[email protected]a27a9382009-02-11 23:55:10558 case NotificationType::CHILD_PROCESS_HOST_CONNECTED:
559 case NotificationType::CHILD_PROCESS_CRASHED:
560 case NotificationType::CHILD_INSTANCE_CREATED:
561 LogChildProcessChange(type, source, details);
initial.commit09911bf2008-07-26 23:55:29562 break;
563
[email protected]bfd04a62009-02-01 18:16:56564 case NotificationType::TEMPLATE_URL_MODEL_LOADED:
initial.commit09911bf2008-07-26 23:55:29565 LogKeywords(Source<TemplateURLModel>(source).ptr());
566 break;
567
[email protected]bfd04a62009-02-01 18:16:56568 case NotificationType::OMNIBOX_OPENED_URL:
initial.commit09911bf2008-07-26 23:55:29569 current_log_->RecordOmniboxOpenedURL(
570 *Details<AutocompleteLog>(details).ptr());
571 break;
572
[email protected]b61236c62009-04-09 22:43:55573 case NotificationType::BOOKMARK_MODEL_LOADED: {
574 Profile* p = Source<Profile>(source).ptr();
575 if (p)
576 LogBookmarks(p->GetBookmarkModel());
initial.commit09911bf2008-07-26 23:55:29577 break;
[email protected]b61236c62009-04-09 22:43:55578 }
initial.commit09911bf2008-07-26 23:55:29579 default:
580 NOTREACHED();
581 break;
582 }
[email protected]d01b8732008-10-16 02:18:07583
584 HandleIdleSinceLastTransmission(false);
585
586 if (current_log_)
[email protected]281d2882009-01-20 20:32:42587 DLOG(INFO) << "METRICS: NUMBER OF EVENTS = " << current_log_->num_events();
[email protected]d01b8732008-10-16 02:18:07588}
589
590void MetricsService::HandleIdleSinceLastTransmission(bool in_idle) {
591 // If there wasn't a lot of action, maybe the computer was asleep, in which
592 // case, the log transmissions should have stopped. Here we start them up
593 // again.
[email protected]cac78842008-11-27 01:02:20594 if (!in_idle && idle_since_last_transmission_)
595 StartLogTransmissionTimer();
596 idle_since_last_transmission_ = in_idle;
initial.commit09911bf2008-07-26 23:55:29597}
598
599void MetricsService::RecordCleanShutdown() {
600 RecordBooleanPrefValue(prefs::kStabilityExitedCleanly, true);
601}
602
603void MetricsService::RecordStartOfSessionEnd() {
604 RecordBooleanPrefValue(prefs::kStabilitySessionEndCompleted, false);
605}
606
607void MetricsService::RecordCompletedSessionEnd() {
608 RecordBooleanPrefValue(prefs::kStabilitySessionEndCompleted, true);
609}
610
[email protected]e73c01972008-08-13 00:18:24611void MetricsService:: RecordBreakpadRegistration(bool success) {
[email protected]68475e602008-08-22 03:21:15612 if (!success)
[email protected]e73c01972008-08-13 00:18:24613 IncrementPrefValue(prefs::kStabilityBreakpadRegistrationFail);
614 else
615 IncrementPrefValue(prefs::kStabilityBreakpadRegistrationSuccess);
616}
617
618void MetricsService::RecordBreakpadHasDebugger(bool has_debugger) {
619 if (!has_debugger)
620 IncrementPrefValue(prefs::kStabilityDebuggerNotPresent);
621 else
[email protected]68475e602008-08-22 03:21:15622 IncrementPrefValue(prefs::kStabilityDebuggerPresent);
[email protected]e73c01972008-08-13 00:18:24623}
624
initial.commit09911bf2008-07-26 23:55:29625//------------------------------------------------------------------------------
626// private methods
627//------------------------------------------------------------------------------
628
629
630//------------------------------------------------------------------------------
631// Initialization methods
632
633void MetricsService::InitializeMetricsState() {
[email protected]79bf0b72009-04-27 21:30:55634#if defined(OS_POSIX)
635 server_url_ = L"https://clients4.google.com/firefox/metrics/collect";
636#else
637 BrowserDistribution* dist = BrowserDistribution::GetDistribution();
638 server_url_ = dist->GetStatsServerURL();
639#endif
640
initial.commit09911bf2008-07-26 23:55:29641 PrefService* pref = g_browser_process->local_state();
642 DCHECK(pref);
643
[email protected]541f77922009-02-23 21:14:38644 if (WideToUTF8(pref->GetString(prefs::kStabilityStatsVersion)) !=
645 MetricsLog::GetVersionString()) {
646 // This is a new version, so we don't want to confuse the stats about the
647 // old version with info that we upload.
648 DiscardOldStabilityStats(pref);
649 pref->SetString(prefs::kStabilityStatsVersion,
650 UTF8ToWide(MetricsLog::GetVersionString()));
651 }
652
initial.commit09911bf2008-07-26 23:55:29653 // Update session ID
654 session_id_ = pref->GetInteger(prefs::kMetricsSessionID);
655 ++session_id_;
656 pref->SetInteger(prefs::kMetricsSessionID, session_id_);
657
initial.commit09911bf2008-07-26 23:55:29658 // Stability bookkeeping
[email protected]e73c01972008-08-13 00:18:24659 IncrementPrefValue(prefs::kStabilityLaunchCount);
initial.commit09911bf2008-07-26 23:55:29660
[email protected]e73c01972008-08-13 00:18:24661 if (!pref->GetBoolean(prefs::kStabilityExitedCleanly)) {
662 IncrementPrefValue(prefs::kStabilityCrashCount);
initial.commit09911bf2008-07-26 23:55:29663 }
[email protected]e73c01972008-08-13 00:18:24664
665 // This will be set to 'true' if we exit cleanly.
initial.commit09911bf2008-07-26 23:55:29666 pref->SetBoolean(prefs::kStabilityExitedCleanly, false);
667
[email protected]e73c01972008-08-13 00:18:24668 if (!pref->GetBoolean(prefs::kStabilitySessionEndCompleted)) {
669 IncrementPrefValue(prefs::kStabilityIncompleteSessionEndCount);
initial.commit09911bf2008-07-26 23:55:29670 }
671 // This is marked false when we get a WM_ENDSESSION.
672 pref->SetBoolean(prefs::kStabilitySessionEndCompleted, true);
673
[email protected]0bb1a622009-03-04 03:22:32674 int64 last_start_time = pref->GetInt64(prefs::kStabilityLaunchTimeSec);
675 int64 last_end_time = pref->GetInt64(prefs::kStabilityLastTimestampSec);
676 int64 uptime = pref->GetInt64(prefs::kStabilityUptimeSec);
677
678 // Same idea as uptime, except this one never gets reset and is used at
679 // uninstallation.
680 int64 uninstall_metrics_uptime =
681 pref->GetInt64(prefs::kUninstallMetricsUptimeSec);
initial.commit09911bf2008-07-26 23:55:29682
683 if (last_start_time && last_end_time) {
684 // TODO(JAR): Exclude sleep time. ... which must be gathered in UI loop.
[email protected]0bb1a622009-03-04 03:22:32685 int64 uptime_increment = last_end_time - last_start_time;
686 uptime += uptime_increment;
687 pref->SetInt64(prefs::kStabilityUptimeSec, uptime);
688
689 uninstall_metrics_uptime += uptime_increment;
690 pref->SetInt64(prefs::kUninstallMetricsUptimeSec,
691 uninstall_metrics_uptime);
initial.commit09911bf2008-07-26 23:55:29692 }
[email protected]0bb1a622009-03-04 03:22:32693 pref->SetInt64(prefs::kStabilityLaunchTimeSec, Time::Now().ToTimeT());
694
695 // Bookkeeping for the uninstall metrics.
696 IncrementLongPrefsValue(prefs::kUninstallLaunchCount);
initial.commit09911bf2008-07-26 23:55:29697
698 // Save profile metrics.
699 PrefService* prefs = g_browser_process->local_state();
700 if (prefs) {
701 // Remove the current dictionary and store it for use when sending data to
702 // server. By removing the value we prune potentially dead profiles
703 // (and keys). All valid values are added back once services startup.
704 const DictionaryValue* profile_dictionary =
705 prefs->GetDictionary(prefs::kProfileMetrics);
706 if (profile_dictionary) {
707 // Do a deep copy of profile_dictionary since ClearPref will delete it.
708 profile_dictionary_.reset(static_cast<DictionaryValue*>(
709 profile_dictionary->DeepCopy()));
710 prefs->ClearPref(prefs::kProfileMetrics);
711 }
712 }
713
[email protected]92745242009-06-12 16:52:21714 // Get stats on use of command line.
715 const CommandLine* command_line(CommandLine::ForCurrentProcess());
716 size_t common_commands = 0;
717 if (command_line->HasSwitch(switches::kUserDataDir)) {
718 ++common_commands;
719 UMA_HISTOGRAM_COUNTS_100("Chrome.CommandLineDatDirCount", 1);
720 }
721
722 if (command_line->HasSwitch(switches::kApp)) {
723 ++common_commands;
724 UMA_HISTOGRAM_COUNTS_100("Chrome.CommandLineAppModeCount", 1);
725 }
726
727 UMA_HISTOGRAM_COUNTS_100("Chrome.CommandLineFlagCount",
728 command_line->GetSwitchCount());
729 UMA_HISTOGRAM_COUNTS_100("Chrome.CommandLineUncommonFlagCount",
730 command_line->GetSwitchCount() - common_commands);
731
initial.commit09911bf2008-07-26 23:55:29732 // Kick off the process of saving the state (so the uptime numbers keep
733 // getting updated) every n minutes.
734 ScheduleNextStateSave();
735}
736
737void MetricsService::OnGetPluginListTaskComplete() {
738 DCHECK(state_ == PLUGIN_LIST_REQUESTED);
739 if (state_ == PLUGIN_LIST_REQUESTED)
740 state_ = PLUGIN_LIST_ARRIVED;
741}
742
743std::string MetricsService::GenerateClientID() {
[email protected]dc6f4962009-02-13 01:25:50744#if defined(OS_WIN)
initial.commit09911bf2008-07-26 23:55:29745 const int kGUIDSize = 39;
746
747 GUID guid;
748 HRESULT guid_result = CoCreateGuid(&guid);
749 DCHECK(SUCCEEDED(guid_result));
750
751 std::wstring guid_string;
752 int result = StringFromGUID2(guid,
753 WriteInto(&guid_string, kGUIDSize), kGUIDSize);
754 DCHECK(result == kGUIDSize);
755
756 return WideToUTF8(guid_string.substr(1, guid_string.length() - 2));
[email protected]dc6f4962009-02-13 01:25:50757#else
758 // TODO(port): Implement for Mac and linux.
[email protected]f5d0e152009-02-19 21:54:37759 // Rather than actually implementing a random source, might this be a good
760 // time to implement http://code.google.com/p/chromium/issues/detail?id=2278
761 // ? I think so!
[email protected]dc6f4962009-02-13 01:25:50762 NOTIMPLEMENTED();
763 return std::string();
764#endif
initial.commit09911bf2008-07-26 23:55:29765}
766
767
768//------------------------------------------------------------------------------
769// State save methods
770
771void MetricsService::ScheduleNextStateSave() {
772 state_saver_factory_.RevokeAll();
773
774 MessageLoop::current()->PostDelayedTask(FROM_HERE,
775 state_saver_factory_.NewRunnableMethod(&MetricsService::SaveLocalState),
776 kSaveStateInterval * 1000);
777}
778
779void MetricsService::SaveLocalState() {
780 PrefService* pref = g_browser_process->local_state();
781 if (!pref) {
782 NOTREACHED();
783 return;
784 }
785
786 RecordCurrentState(pref);
[email protected]6faa0e0d2009-04-28 06:50:36787 pref->ScheduleSavePersistentPrefs();
initial.commit09911bf2008-07-26 23:55:29788
[email protected]281d2882009-01-20 20:32:42789 // TODO(jar): Does this run down the batteries????
initial.commit09911bf2008-07-26 23:55:29790 ScheduleNextStateSave();
791}
792
793
794//------------------------------------------------------------------------------
795// Recording control methods
796
797void MetricsService::StartRecording() {
798 if (current_log_)
799 return;
800
801 current_log_ = new MetricsLog(client_id_, session_id_);
802 if (state_ == INITIALIZED) {
803 // We only need to schedule that run once.
804 state_ = PLUGIN_LIST_REQUESTED;
805
806 // Make sure the plugin list is loaded before the inital log is sent, so
807 // that the main thread isn't blocked generating the list.
808 g_browser_process->file_thread()->message_loop()->PostDelayedTask(FROM_HERE,
809 new GetPluginListTask(MessageLoop::current()),
[email protected]252873ef2008-08-04 21:59:45810 kInitialInterlogDuration * 1000 / 2);
initial.commit09911bf2008-07-26 23:55:29811 }
812}
813
814void MetricsService::StopRecording(MetricsLog** log) {
815 if (!current_log_)
816 return;
817
[email protected]68475e602008-08-22 03:21:15818 // TODO(jar): Integrate bounds on log recording more consistently, so that we
819 // can stop recording logs that are too big much sooner.
[email protected]d01b8732008-10-16 02:18:07820 if (current_log_->num_events() > log_event_limit_) {
[email protected]553dba62009-02-24 19:08:23821 UMA_HISTOGRAM_COUNTS("UMA.Discarded Log Events",
[email protected]68475e602008-08-22 03:21:15822 current_log_->num_events());
823 current_log_->CloseLog();
824 delete current_log_;
[email protected]294638782008-09-24 00:22:41825 current_log_ = NULL;
[email protected]68475e602008-08-22 03:21:15826 StartRecording(); // Start trivial log to hold our histograms.
827 }
828
[email protected]0b33f80b2008-12-17 21:34:36829 // Put incremental data (histogram deltas, and realtime stats deltas) at the
[email protected]147bbc0b2009-01-06 19:37:40830 // end of all log transmissions (initial log handles this separately).
initial.commit09911bf2008-07-26 23:55:29831 // Don't bother if we're going to discard current_log_.
[email protected]0b33f80b2008-12-17 21:34:36832 if (log) {
[email protected]c96d53092009-02-24 01:25:06833 current_log_->RecordIncrementalStabilityElements();
initial.commit09911bf2008-07-26 23:55:29834 RecordCurrentHistograms();
[email protected]0b33f80b2008-12-17 21:34:36835 }
initial.commit09911bf2008-07-26 23:55:29836
837 current_log_->CloseLog();
[email protected]cac78842008-11-27 01:02:20838 if (log)
initial.commit09911bf2008-07-26 23:55:29839 *log = current_log_;
[email protected]cac78842008-11-27 01:02:20840 else
initial.commit09911bf2008-07-26 23:55:29841 delete current_log_;
initial.commit09911bf2008-07-26 23:55:29842 current_log_ = NULL;
843}
844
initial.commit09911bf2008-07-26 23:55:29845void MetricsService::PushPendingLogsToUnsentLists() {
846 if (state_ < INITIAL_LOG_READY)
[email protected]28ab7f92009-01-06 21:39:04847 return; // We didn't and still don't have time to get plugin list etc.
initial.commit09911bf2008-07-26 23:55:29848
849 if (pending_log()) {
850 PreparePendingLogText();
851 if (state_ == INITIAL_LOG_READY) {
852 // We may race here, and send second copy of initial log later.
853 unsent_initial_logs_.push_back(pending_log_text_);
[email protected]d01b8732008-10-16 02:18:07854 state_ = SEND_OLD_INITIAL_LOGS;
initial.commit09911bf2008-07-26 23:55:29855 } else {
[email protected]281d2882009-01-20 20:32:42856 // TODO(jar): Verify correctness in other states, including sending unsent
[email protected]541f77922009-02-23 21:14:38857 // initial logs.
[email protected]68475e602008-08-22 03:21:15858 PushPendingLogTextToUnsentOngoingLogs();
initial.commit09911bf2008-07-26 23:55:29859 }
860 DiscardPendingLog();
861 }
862 DCHECK(!pending_log());
863 StopRecording(&pending_log_);
864 PreparePendingLogText();
[email protected]68475e602008-08-22 03:21:15865 PushPendingLogTextToUnsentOngoingLogs();
initial.commit09911bf2008-07-26 23:55:29866 DiscardPendingLog();
867 StoreUnsentLogs();
868}
869
[email protected]68475e602008-08-22 03:21:15870void MetricsService::PushPendingLogTextToUnsentOngoingLogs() {
[email protected]d01b8732008-10-16 02:18:07871 // If UMA response told us not to upload, there's no need to save the pending
872 // log. It wasn't supposed to be uploaded anyway.
873 if (!server_permits_upload_)
874 return;
875
[email protected]dc6f4962009-02-13 01:25:50876 if (pending_log_text_.length() >
877 static_cast<size_t>(kUploadLogAvoidRetransmitSize)) {
[email protected]553dba62009-02-24 19:08:23878 UMA_HISTOGRAM_COUNTS("UMA.Large Accumulated Log Not Persisted",
[email protected]68475e602008-08-22 03:21:15879 static_cast<int>(pending_log_text_.length()));
880 return;
881 }
882 unsent_ongoing_logs_.push_back(pending_log_text_);
883}
884
initial.commit09911bf2008-07-26 23:55:29885//------------------------------------------------------------------------------
886// Transmission of logs methods
887
888void MetricsService::StartLogTransmissionTimer() {
[email protected]d01b8732008-10-16 02:18:07889 // If we're not reporting, there's no point in starting a log transmission
890 // timer.
891 if (!reporting_active())
892 return;
893
initial.commit09911bf2008-07-26 23:55:29894 if (!current_log_)
895 return; // Recorder is shutdown.
[email protected]d01b8732008-10-16 02:18:07896
897 // If there is already a timer running, we leave it running.
898 // If timer_pending is true because the fetch is waiting for a response,
899 // we return for now and let the response handler start the timer.
900 if (timer_pending_)
initial.commit09911bf2008-07-26 23:55:29901 return;
[email protected]d01b8732008-10-16 02:18:07902
[email protected]d01b8732008-10-16 02:18:07903 // Before starting the timer, set timer_pending_ to true.
initial.commit09911bf2008-07-26 23:55:29904 timer_pending_ = true;
[email protected]d01b8732008-10-16 02:18:07905
906 // Right before the UMA transmission gets started, there's one more thing we'd
907 // like to record: the histogram of memory usage, so we spawn a task to
[email protected]c9a3ef82009-05-28 22:02:46908 // collect the memory details and when that task is finished, it will call
909 // OnMemoryDetailCollectionDone, which will call HistogramSynchronization to
910 // collect histograms from all renderers and then we will call
911 // OnHistogramSynchronizationDone to continue processing.
initial.commit09911bf2008-07-26 23:55:29912 MessageLoop::current()->PostDelayedTask(FROM_HERE,
913 log_sender_factory_.
[email protected]c9a3ef82009-05-28 22:02:46914 NewRunnableMethod(&MetricsService::LogTransmissionTimerDone),
initial.commit09911bf2008-07-26 23:55:29915 static_cast<int>(interlog_duration_.InMilliseconds()));
916}
917
[email protected]c9a3ef82009-05-28 22:02:46918void MetricsService::LogTransmissionTimerDone() {
919 Task* task = log_sender_factory_.
920 NewRunnableMethod(&MetricsService::OnMemoryDetailCollectionDone);
921
922 MetricsMemoryDetails* details = new MetricsMemoryDetails(task);
923 details->StartFetch();
924
925 // Collect WebCore cache information to put into a histogram.
926 for (RenderProcessHost::iterator it = RenderProcessHost::begin();
927 it != RenderProcessHost::end(); ++it) {
928 it->second->Send(new ViewMsg_GetCacheResourceStats());
929 }
930}
931
932void MetricsService::OnMemoryDetailCollectionDone() {
933 DCHECK(IsSingleThreaded());
934
935 // HistogramSynchronizer will Collect histograms from all renderers and it
936 // will call OnHistogramSynchronizationDone (if wait time elapses before it
937 // heard from all renderers, then also it will call
938 // OnHistogramSynchronizationDone).
939
940 // Create a callback_task for OnHistogramSynchronizationDone.
941 Task* callback_task = log_sender_factory_.NewRunnableMethod(
942 &MetricsService::OnHistogramSynchronizationDone);
943
944 // Set up the callback to task to call after we receive histograms from all
945 // renderer processes. Wait time specifies how long to wait before absolutely
946 // calling us back on the task.
947 HistogramSynchronizer::FetchRendererHistogramsAsynchronously(
948 MessageLoop::current(), callback_task,
949 kMaxHistogramGatheringWaitDuration);
950}
951
952void MetricsService::OnHistogramSynchronizationDone() {
initial.commit09911bf2008-07-26 23:55:29953 DCHECK(IsSingleThreaded());
954
[email protected]d01b8732008-10-16 02:18:07955 // This function should only be called via timer, so timer_pending_
956 // should be true.
957 DCHECK(timer_pending_);
958 timer_pending_ = false;
initial.commit09911bf2008-07-26 23:55:29959
960 DCHECK(!current_fetch_.get());
initial.commit09911bf2008-07-26 23:55:29961
[email protected]d01b8732008-10-16 02:18:07962 // If we're getting no notifications, then the log won't have much in it, and
963 // it's possible the computer is about to go to sleep, so don't upload and
964 // don't restart the transmission timer.
965 if (idle_since_last_transmission_)
966 return;
967
968 // If somehow there is a fetch in progress, we return setting timer_pending_
969 // to true and hope things work out.
970 if (current_fetch_.get()) {
971 timer_pending_ = true;
972 return;
973 }
974
975 // If uploads are forbidden by UMA response, there's no point in keeping
976 // the current_log_, and the more often we delete it, the less likely it is
977 // to expand forever.
978 if (!server_permits_upload_ && current_log_) {
979 StopRecording(NULL);
980 StartRecording();
981 }
initial.commit09911bf2008-07-26 23:55:29982
983 if (!current_log_)
984 return; // Logging was disabled.
[email protected]d01b8732008-10-16 02:18:07985 if (!reporting_active())
initial.commit09911bf2008-07-26 23:55:29986 return; // Don't do work if we're not going to send anything now.
987
[email protected]d01b8732008-10-16 02:18:07988 MakePendingLog();
initial.commit09911bf2008-07-26 23:55:29989
[email protected]d01b8732008-10-16 02:18:07990 // MakePendingLog should have put something in the pending log, if it didn't,
991 // we start the timer again, return and hope things work out.
992 if (!pending_log()) {
993 StartLogTransmissionTimer();
994 return;
995 }
initial.commit09911bf2008-07-26 23:55:29996
[email protected]d01b8732008-10-16 02:18:07997 // If we're not supposed to upload any UMA data because the response or the
998 // user said so, cancel the upload at this point, but start the timer.
999 if (!TransmissionPermitted()) {
1000 DiscardPendingLog();
1001 StartLogTransmissionTimer();
1002 return;
1003 }
initial.commit09911bf2008-07-26 23:55:291004
[email protected]d01b8732008-10-16 02:18:071005 PrepareFetchWithPendingLog();
1006
1007 if (!current_fetch_.get()) {
1008 // Compression failed, and log discarded :-/.
1009 DiscardPendingLog();
1010 StartLogTransmissionTimer(); // Maybe we'll do better next time
1011 // TODO(jar): If compression failed, we should have created a tiny log and
1012 // compressed that, so that we can signal that we're losing logs.
1013 return;
1014 }
1015
1016 DCHECK(!timer_pending_);
1017
1018 // The URL fetch is a like timer in that after a while we get called back
1019 // so we set timer_pending_ true just as we start the url fetch.
1020 timer_pending_ = true;
1021 current_fetch_->Start();
1022
1023 HandleIdleSinceLastTransmission(true);
1024}
1025
1026
1027void MetricsService::MakePendingLog() {
1028 if (pending_log())
1029 return;
1030
1031 switch (state_) {
1032 case INITIALIZED:
1033 case PLUGIN_LIST_REQUESTED: // We should be further along by now.
1034 DCHECK(false);
1035 return;
1036
1037 case PLUGIN_LIST_ARRIVED:
1038 // We need to wait for the initial log to be ready before sending
1039 // anything, because the server will tell us whether it wants to hear
1040 // from us.
1041 PrepareInitialLog();
1042 DCHECK(state_ == PLUGIN_LIST_ARRIVED);
1043 RecallUnsentLogs();
1044 state_ = INITIAL_LOG_READY;
1045 break;
1046
1047 case SEND_OLD_INITIAL_LOGS:
[email protected]cac78842008-11-27 01:02:201048 if (!unsent_initial_logs_.empty()) {
1049 pending_log_text_ = unsent_initial_logs_.back();
1050 break;
1051 }
[email protected]d01b8732008-10-16 02:18:071052 state_ = SENDING_OLD_LOGS;
1053 // Fall through.
initial.commit09911bf2008-07-26 23:55:291054
[email protected]d01b8732008-10-16 02:18:071055 case SENDING_OLD_LOGS:
1056 if (!unsent_ongoing_logs_.empty()) {
1057 pending_log_text_ = unsent_ongoing_logs_.back();
1058 break;
1059 }
1060 state_ = SENDING_CURRENT_LOGS;
1061 // Fall through.
1062
1063 case SENDING_CURRENT_LOGS:
1064 StopRecording(&pending_log_);
1065 StartRecording();
1066 break;
1067
1068 default:
1069 DCHECK(false);
1070 return;
1071 }
1072
1073 DCHECK(pending_log());
1074}
1075
1076bool MetricsService::TransmissionPermitted() const {
1077 // If the user forbids uploading that's they're business, and we don't upload
1078 // anything. If the server forbids uploading, that's our business, so we take
1079 // that to mean it forbids current logs, but we still send up the inital logs
1080 // and any old logs.
[email protected]d01b8732008-10-16 02:18:071081 if (!user_permits_upload_)
1082 return false;
[email protected]cac78842008-11-27 01:02:201083 if (server_permits_upload_)
[email protected]d01b8732008-10-16 02:18:071084 return true;
initial.commit09911bf2008-07-26 23:55:291085
[email protected]cac78842008-11-27 01:02:201086 switch (state_) {
1087 case INITIAL_LOG_READY:
1088 case SEND_OLD_INITIAL_LOGS:
1089 case SENDING_OLD_LOGS:
1090 return true;
1091
1092 case SENDING_CURRENT_LOGS:
1093 default:
1094 return false;
[email protected]8c8824b2008-09-20 01:55:501095 }
initial.commit09911bf2008-07-26 23:55:291096}
1097
initial.commit09911bf2008-07-26 23:55:291098void MetricsService::PrepareInitialLog() {
1099 DCHECK(state_ == PLUGIN_LIST_ARRIVED);
1100 std::vector<WebPluginInfo> plugins;
1101 PluginService::GetInstance()->GetPlugins(false, &plugins);
1102
1103 MetricsLog* log = new MetricsLog(client_id_, session_id_);
1104 log->RecordEnvironment(plugins, profile_dictionary_.get());
1105
1106 // Histograms only get written to current_log_, so setup for the write.
1107 MetricsLog* save_log = current_log_;
1108 current_log_ = log;
1109 RecordCurrentHistograms(); // Into current_log_... which is really log.
1110 current_log_ = save_log;
1111
1112 log->CloseLog();
1113 DCHECK(!pending_log());
1114 pending_log_ = log;
1115}
1116
1117void MetricsService::RecallUnsentLogs() {
1118 DCHECK(unsent_initial_logs_.empty());
1119 DCHECK(unsent_ongoing_logs_.empty());
1120
1121 PrefService* local_state = g_browser_process->local_state();
1122 DCHECK(local_state);
1123
1124 ListValue* unsent_initial_logs = local_state->GetMutableList(
1125 prefs::kMetricsInitialLogs);
1126 for (ListValue::iterator it = unsent_initial_logs->begin();
1127 it != unsent_initial_logs->end(); ++it) {
[email protected]5e324b72008-12-18 00:07:591128 std::string log;
1129 (*it)->GetAsString(&log);
1130 unsent_initial_logs_.push_back(log);
initial.commit09911bf2008-07-26 23:55:291131 }
1132
1133 ListValue* unsent_ongoing_logs = local_state->GetMutableList(
1134 prefs::kMetricsOngoingLogs);
1135 for (ListValue::iterator it = unsent_ongoing_logs->begin();
1136 it != unsent_ongoing_logs->end(); ++it) {
[email protected]5e324b72008-12-18 00:07:591137 std::string log;
1138 (*it)->GetAsString(&log);
1139 unsent_ongoing_logs_.push_back(log);
initial.commit09911bf2008-07-26 23:55:291140 }
1141}
1142
1143void MetricsService::StoreUnsentLogs() {
1144 if (state_ < INITIAL_LOG_READY)
1145 return; // We never Recalled the prior unsent logs.
1146
1147 PrefService* local_state = g_browser_process->local_state();
1148 DCHECK(local_state);
1149
1150 ListValue* unsent_initial_logs = local_state->GetMutableList(
1151 prefs::kMetricsInitialLogs);
1152 unsent_initial_logs->Clear();
1153 size_t start = 0;
1154 if (unsent_initial_logs_.size() > kMaxInitialLogsPersisted)
1155 start = unsent_initial_logs_.size() - kMaxInitialLogsPersisted;
1156 for (size_t i = start; i < unsent_initial_logs_.size(); ++i)
1157 unsent_initial_logs->Append(
[email protected]5e324b72008-12-18 00:07:591158 Value::CreateStringValue(unsent_initial_logs_[i]));
initial.commit09911bf2008-07-26 23:55:291159
1160 ListValue* unsent_ongoing_logs = local_state->GetMutableList(
1161 prefs::kMetricsOngoingLogs);
1162 unsent_ongoing_logs->Clear();
1163 start = 0;
1164 if (unsent_ongoing_logs_.size() > kMaxOngoingLogsPersisted)
1165 start = unsent_ongoing_logs_.size() - kMaxOngoingLogsPersisted;
1166 for (size_t i = start; i < unsent_ongoing_logs_.size(); ++i)
1167 unsent_ongoing_logs->Append(
[email protected]5e324b72008-12-18 00:07:591168 Value::CreateStringValue(unsent_ongoing_logs_[i]));
initial.commit09911bf2008-07-26 23:55:291169}
1170
1171void MetricsService::PreparePendingLogText() {
1172 DCHECK(pending_log());
1173 if (!pending_log_text_.empty())
1174 return;
1175 int original_size = pending_log_->GetEncodedLogSize();
1176 pending_log_->GetEncodedLog(WriteInto(&pending_log_text_, original_size),
1177 original_size);
1178}
1179
[email protected]d01b8732008-10-16 02:18:071180void MetricsService::PrepareFetchWithPendingLog() {
initial.commit09911bf2008-07-26 23:55:291181 DCHECK(pending_log());
1182 DCHECK(!current_fetch_.get());
1183 PreparePendingLogText();
1184 DCHECK(!pending_log_text_.empty());
1185
1186 // Allow security conscious users to see all metrics logs that we send.
1187 LOG(INFO) << "METRICS LOG: " << pending_log_text_;
1188
1189 std::string compressed_log;
[email protected]cac78842008-11-27 01:02:201190 if (!Bzip2Compress(pending_log_text_, &compressed_log)) {
initial.commit09911bf2008-07-26 23:55:291191 NOTREACHED() << "Failed to compress log for transmission.";
1192 DiscardPendingLog();
1193 StartLogTransmissionTimer(); // Maybe we'll do better on next log :-/.
1194 return;
1195 }
[email protected]cac78842008-11-27 01:02:201196
[email protected]79bf0b72009-04-27 21:30:551197 current_fetch_.reset(new URLFetcher(GURL(WideToUTF16(server_url_)),
1198 URLFetcher::POST,
initial.commit09911bf2008-07-26 23:55:291199 this));
1200 current_fetch_->set_request_context(Profile::GetDefaultRequestContext());
1201 current_fetch_->set_upload_data(kMetricsType, compressed_log);
initial.commit09911bf2008-07-26 23:55:291202}
1203
1204void MetricsService::DiscardPendingLog() {
1205 if (pending_log_) { // Shutdown might have deleted it!
1206 delete pending_log_;
1207 pending_log_ = NULL;
1208 }
1209 pending_log_text_.clear();
1210}
1211
1212// This implementation is based on the Firefox MetricsService implementation.
1213bool MetricsService::Bzip2Compress(const std::string& input,
1214 std::string* output) {
1215 bz_stream stream = {0};
1216 // As long as our input is smaller than the bzip2 block size, we should get
1217 // the best compression. For example, if your input was 250k, using a block
1218 // size of 300k or 500k should result in the same compression ratio. Since
1219 // our data should be under 100k, using the minimum block size of 100k should
1220 // allocate less temporary memory, but result in the same compression ratio.
1221 int result = BZ2_bzCompressInit(&stream,
1222 1, // 100k (min) block size
1223 0, // quiet
1224 0); // default "work factor"
1225 if (result != BZ_OK) { // out of memory?
1226 return false;
1227 }
1228
1229 output->clear();
1230
1231 stream.next_in = const_cast<char*>(input.data());
1232 stream.avail_in = static_cast<int>(input.size());
1233 // NOTE: we don't need a BZ_RUN phase since our input buffer contains
1234 // the entire input
1235 do {
1236 output->resize(output->size() + 1024);
1237 stream.next_out = &((*output)[stream.total_out_lo32]);
1238 stream.avail_out = static_cast<int>(output->size()) - stream.total_out_lo32;
1239 result = BZ2_bzCompress(&stream, BZ_FINISH);
1240 } while (result == BZ_FINISH_OK);
1241 if (result != BZ_STREAM_END) // unknown failure?
1242 return false;
1243 result = BZ2_bzCompressEnd(&stream);
1244 DCHECK(result == BZ_OK);
1245
1246 output->resize(stream.total_out_lo32);
1247
1248 return true;
1249}
1250
1251static const char* StatusToString(const URLRequestStatus& status) {
1252 switch (status.status()) {
1253 case URLRequestStatus::SUCCESS:
1254 return "SUCCESS";
1255
1256 case URLRequestStatus::IO_PENDING:
1257 return "IO_PENDING";
1258
1259 case URLRequestStatus::HANDLED_EXTERNALLY:
1260 return "HANDLED_EXTERNALLY";
1261
1262 case URLRequestStatus::CANCELED:
1263 return "CANCELED";
1264
1265 case URLRequestStatus::FAILED:
1266 return "FAILED";
1267
1268 default:
1269 NOTREACHED();
1270 return "Unknown";
1271 }
1272}
1273
1274void MetricsService::OnURLFetchComplete(const URLFetcher* source,
1275 const GURL& url,
1276 const URLRequestStatus& status,
1277 int response_code,
1278 const ResponseCookies& cookies,
1279 const std::string& data) {
1280 DCHECK(timer_pending_);
1281 timer_pending_ = false;
1282 DCHECK(current_fetch_.get());
1283 current_fetch_.reset(NULL); // We're not allowed to re-use it.
1284
1285 // Confirm send so that we can move on.
[email protected]281d2882009-01-20 20:32:421286 LOG(INFO) << "METRICS RESPONSE CODE: " << response_code << " status=" <<
[email protected]cac78842008-11-27 01:02:201287 StatusToString(status);
[email protected]252873ef2008-08-04 21:59:451288
[email protected]0eb34fee2009-01-21 08:04:381289 // Provide boolean for error recovery (allow us to ignore response_code).
[email protected]dc6f4962009-02-13 01:25:501290 bool discard_log = false;
[email protected]0eb34fee2009-01-21 08:04:381291
[email protected]68475e602008-08-22 03:21:151292 if (response_code != 200 &&
[email protected]dc6f4962009-02-13 01:25:501293 pending_log_text_.length() >
1294 static_cast<size_t>(kUploadLogAvoidRetransmitSize)) {
[email protected]553dba62009-02-24 19:08:231295 UMA_HISTOGRAM_COUNTS("UMA.Large Rejected Log was Discarded",
[email protected]68475e602008-08-22 03:21:151296 static_cast<int>(pending_log_text_.length()));
[email protected]0eb34fee2009-01-21 08:04:381297 discard_log = true;
1298 } else if (response_code == 400) {
1299 // Bad syntax. Retransmission won't work.
[email protected]553dba62009-02-24 19:08:231300 UMA_HISTOGRAM_COUNTS("UMA.Unacceptable_Log_Discarded", state_);
[email protected]0eb34fee2009-01-21 08:04:381301 discard_log = true;
[email protected]68475e602008-08-22 03:21:151302 }
1303
[email protected]0eb34fee2009-01-21 08:04:381304 if (response_code != 200 && !discard_log) {
[email protected]281d2882009-01-20 20:32:421305 LOG(INFO) << "METRICS: transmission attempt returned a failure code: "
1306 << response_code << ". Verify network connectivity";
[email protected]252873ef2008-08-04 21:59:451307 HandleBadResponseCode();
[email protected]0eb34fee2009-01-21 08:04:381308 } else { // Successful receipt (or we are discarding log).
[email protected]281d2882009-01-20 20:32:421309 LOG(INFO) << "METRICS RESPONSE DATA: " << data;
initial.commit09911bf2008-07-26 23:55:291310 switch (state_) {
1311 case INITIAL_LOG_READY:
1312 state_ = SEND_OLD_INITIAL_LOGS;
1313 break;
1314
1315 case SEND_OLD_INITIAL_LOGS:
1316 DCHECK(!unsent_initial_logs_.empty());
1317 unsent_initial_logs_.pop_back();
1318 StoreUnsentLogs();
1319 break;
1320
1321 case SENDING_OLD_LOGS:
1322 DCHECK(!unsent_ongoing_logs_.empty());
1323 unsent_ongoing_logs_.pop_back();
1324 StoreUnsentLogs();
1325 break;
1326
1327 case SENDING_CURRENT_LOGS:
1328 break;
1329
1330 default:
1331 DCHECK(false);
1332 break;
1333 }
[email protected]d01b8732008-10-16 02:18:071334
initial.commit09911bf2008-07-26 23:55:291335 DiscardPendingLog();
[email protected]29be92552008-08-07 22:49:271336 // Since we sent a log, make sure our in-memory state is recorded to disk.
1337 PrefService* local_state = g_browser_process->local_state();
1338 DCHECK(local_state);
1339 if (local_state)
[email protected]6faa0e0d2009-04-28 06:50:361340 local_state->ScheduleSavePersistentPrefs();
[email protected]252873ef2008-08-04 21:59:451341
[email protected]147bbc0b2009-01-06 19:37:401342 // Provide a default (free of exponetial backoff, other varances) in case
1343 // the server does not specify a value.
1344 interlog_duration_ = TimeDelta::FromSeconds(kMinSecondsPerLog);
1345
[email protected]252873ef2008-08-04 21:59:451346 GetSettingsFromResponseData(data);
[email protected]252873ef2008-08-04 21:59:451347 // Override server specified interlog delay if there are unsent logs to
[email protected]29be92552008-08-07 22:49:271348 // transmit.
initial.commit09911bf2008-07-26 23:55:291349 if (unsent_logs()) {
1350 DCHECK(state_ < SENDING_CURRENT_LOGS);
1351 interlog_duration_ = TimeDelta::FromSeconds(kUnsentLogDelay);
initial.commit09911bf2008-07-26 23:55:291352 }
1353 }
[email protected]252873ef2008-08-04 21:59:451354
initial.commit09911bf2008-07-26 23:55:291355 StartLogTransmissionTimer();
1356}
1357
[email protected]252873ef2008-08-04 21:59:451358void MetricsService::HandleBadResponseCode() {
[email protected]281d2882009-01-20 20:32:421359 LOG(INFO) << "Verify your metrics logs are formatted correctly. "
[email protected]79bf0b72009-04-27 21:30:551360 "Verify server is active at " << server_url_;
[email protected]252873ef2008-08-04 21:59:451361 if (!pending_log()) {
[email protected]281d2882009-01-20 20:32:421362 LOG(INFO) << "METRICS: Recorder shutdown during log transmission.";
[email protected]252873ef2008-08-04 21:59:451363 } else {
1364 // Send progressively less frequently.
1365 DCHECK(kBackoff > 1.0);
1366 interlog_duration_ = TimeDelta::FromMicroseconds(
1367 static_cast<int64>(kBackoff * interlog_duration_.InMicroseconds()));
1368
1369 if (kMaxBackoff * TimeDelta::FromSeconds(kMinSecondsPerLog) <
[email protected]cac78842008-11-27 01:02:201370 interlog_duration_) {
[email protected]252873ef2008-08-04 21:59:451371 interlog_duration_ = kMaxBackoff *
1372 TimeDelta::FromSeconds(kMinSecondsPerLog);
[email protected]cac78842008-11-27 01:02:201373 }
[email protected]252873ef2008-08-04 21:59:451374
[email protected]281d2882009-01-20 20:32:421375 LOG(INFO) << "METRICS: transmission retry being scheduled in " <<
[email protected]252873ef2008-08-04 21:59:451376 interlog_duration_.InSeconds() << " seconds for " <<
1377 pending_log_text_;
initial.commit09911bf2008-07-26 23:55:291378 }
initial.commit09911bf2008-07-26 23:55:291379}
1380
[email protected]252873ef2008-08-04 21:59:451381void MetricsService::GetSettingsFromResponseData(const std::string& data) {
1382 // We assume that the file is structured as a block opened by <response>
[email protected]d01b8732008-10-16 02:18:071383 // and that inside response, there is a block opened by tag <chrome_config>
1384 // other tags are ignored for now except the content of <chrome_config>.
[email protected]281d2882009-01-20 20:32:421385 LOG(INFO) << "METRICS: getting settings from response data: " << data;
[email protected]d01b8732008-10-16 02:18:071386
[email protected]252873ef2008-08-04 21:59:451387 int data_size = static_cast<int>(data.size());
1388 if (data_size < 0) {
[email protected]281d2882009-01-20 20:32:421389 LOG(INFO) << "METRICS: server response data bad size: " << data_size <<
[email protected]cac78842008-11-27 01:02:201390 "; aborting extraction of settings";
[email protected]252873ef2008-08-04 21:59:451391 return;
1392 }
[email protected]cac78842008-11-27 01:02:201393 xmlDocPtr doc = xmlReadMemory(data.c_str(), data_size, "", NULL, 0);
[email protected]252873ef2008-08-04 21:59:451394 DCHECK(doc);
[email protected]d01b8732008-10-16 02:18:071395 // If the document is malformed, we just use the settings that were there.
1396 if (!doc) {
[email protected]281d2882009-01-20 20:32:421397 LOG(INFO) << "METRICS: reading xml from server response data failed";
[email protected]252873ef2008-08-04 21:59:451398 return;
[email protected]d01b8732008-10-16 02:18:071399 }
[email protected]252873ef2008-08-04 21:59:451400
[email protected]d01b8732008-10-16 02:18:071401 xmlNodePtr top_node = xmlDocGetRootElement(doc), chrome_config_node = NULL;
1402 // Here, we find the chrome_config node by name.
[email protected]252873ef2008-08-04 21:59:451403 for (xmlNodePtr p = top_node->children; p; p = p->next) {
[email protected]d01b8732008-10-16 02:18:071404 if (xmlStrEqual(p->name, BAD_CAST "chrome_config")) {
1405 chrome_config_node = p;
[email protected]252873ef2008-08-04 21:59:451406 break;
1407 }
1408 }
1409 // If the server data is formatted wrong and there is no
1410 // config node where we expect, we just drop out.
[email protected]d01b8732008-10-16 02:18:071411 if (chrome_config_node != NULL)
1412 GetSettingsFromChromeConfigNode(chrome_config_node);
[email protected]252873ef2008-08-04 21:59:451413 xmlFreeDoc(doc);
1414}
1415
[email protected]d01b8732008-10-16 02:18:071416void MetricsService::GetSettingsFromChromeConfigNode(
1417 xmlNodePtr chrome_config_node) {
1418 // Iterate through all children of the config node.
1419 for (xmlNodePtr current_node = chrome_config_node->children;
1420 current_node;
1421 current_node = current_node->next) {
1422 // If we find the upload tag, we appeal to another function
1423 // GetSettingsFromUploadNode to read all the data in it.
[email protected]252873ef2008-08-04 21:59:451424 if (xmlStrEqual(current_node->name, BAD_CAST "upload")) {
[email protected]d01b8732008-10-16 02:18:071425 GetSettingsFromUploadNode(current_node);
[email protected]252873ef2008-08-04 21:59:451426 continue;
1427 }
1428 }
1429}
initial.commit09911bf2008-07-26 23:55:291430
[email protected]d01b8732008-10-16 02:18:071431void MetricsService::InheritedProperties::OverwriteWhereNeeded(
1432 xmlNodePtr node) {
1433 xmlChar* salt_value = xmlGetProp(node, BAD_CAST "salt");
1434 if (salt_value) // If the property isn't there, xmlGetProp returns NULL.
1435 salt = atoi(reinterpret_cast<char*>(salt_value));
1436 // If the property isn't there, we keep the value the property had before
1437
1438 xmlChar* denominator_value = xmlGetProp(node, BAD_CAST "denominator");
1439 if (denominator_value)
1440 denominator = atoi(reinterpret_cast<char*>(denominator_value));
1441}
1442
1443void MetricsService::GetSettingsFromUploadNode(xmlNodePtr upload_node) {
1444 InheritedProperties props;
1445 GetSettingsFromUploadNodeRecursive(upload_node, props, "", true);
1446}
1447
[email protected]cac78842008-11-27 01:02:201448void MetricsService::GetSettingsFromUploadNodeRecursive(
1449 xmlNodePtr node,
1450 InheritedProperties props,
1451 std::string path_prefix,
1452 bool uploadOn) {
[email protected]d01b8732008-10-16 02:18:071453 props.OverwriteWhereNeeded(node);
1454
1455 // The bool uploadOn is set to true if the data represented by current
1456 // node should be uploaded. This gets inherited in the tree; the children
1457 // of a node that has already been rejected for upload get rejected for
1458 // upload.
1459 uploadOn = uploadOn && NodeProbabilityTest(node, props);
1460
1461 // The path is a / separated list of the node names ancestral to the current
1462 // one. So, if you want to check if the current node has a certain name,
1463 // compare to name. If you want to check if it is a certan tag at a certain
1464 // place in the tree, compare to the whole path.
1465 std::string name = std::string(reinterpret_cast<const char*>(node->name));
1466 std::string path = path_prefix + "/" + name;
1467
1468 if (path == "/upload") {
1469 xmlChar* upload_interval_val = xmlGetProp(node, BAD_CAST "interval");
1470 if (upload_interval_val) {
1471 interlog_duration_ = TimeDelta::FromSeconds(
1472 atoi(reinterpret_cast<char*>(upload_interval_val)));
1473 }
1474
1475 server_permits_upload_ = uploadOn;
1476 }
1477 if (path == "/upload/logs") {
1478 xmlChar* log_event_limit_val = xmlGetProp(node, BAD_CAST "event_limit");
1479 if (log_event_limit_val)
1480 log_event_limit_ = atoi(reinterpret_cast<char*>(log_event_limit_val));
1481 }
1482 if (name == "histogram") {
1483 xmlChar* type_value = xmlGetProp(node, BAD_CAST "type");
1484 if (type_value) {
1485 std::string type = (reinterpret_cast<char*>(type_value));
1486 if (uploadOn)
1487 histograms_to_upload_.insert(type);
1488 else
1489 histograms_to_omit_.insert(type);
1490 }
1491 }
1492 if (name == "log") {
1493 xmlChar* type_value = xmlGetProp(node, BAD_CAST "type");
1494 if (type_value) {
1495 std::string type = (reinterpret_cast<char*>(type_value));
1496 if (uploadOn)
1497 logs_to_upload_.insert(type);
1498 else
1499 logs_to_omit_.insert(type);
1500 }
1501 }
1502
1503 // Recursive call. If the node is a leaf i.e. if it ends in a "/>", then it
1504 // doesn't have children, so node->children is NULL, and this loop doesn't
1505 // call (that's how the recursion ends).
1506 for (xmlNodePtr child_node = node->children;
[email protected]cac78842008-11-27 01:02:201507 child_node;
1508 child_node = child_node->next) {
[email protected]d01b8732008-10-16 02:18:071509 GetSettingsFromUploadNodeRecursive(child_node, props, path, uploadOn);
1510 }
1511}
1512
1513bool MetricsService::NodeProbabilityTest(xmlNodePtr node,
[email protected]cac78842008-11-27 01:02:201514 InheritedProperties props) const {
[email protected]d01b8732008-10-16 02:18:071515 // Default value of probability on any node is 1, but recall that
1516 // its parents can already have been rejected for upload.
1517 double probability = 1;
1518
1519 // If a probability is specified in the node, we use it instead.
1520 xmlChar* probability_value = xmlGetProp(node, BAD_CAST "probability");
1521 if (probability_value)
[email protected]0b33f80b2008-12-17 21:34:361522 probability = atoi(reinterpret_cast<char*>(probability_value));
[email protected]d01b8732008-10-16 02:18:071523
1524 return ProbabilityTest(probability, props.salt, props.denominator);
1525}
1526
1527bool MetricsService::ProbabilityTest(double probability,
1528 int salt,
1529 int denominator) const {
1530 // Okay, first we figure out how many of the digits of the
1531 // client_id_ we need in order to make a nice pseudorandomish
1532 // number in the range [0,denominator). Too many digits is
1533 // fine.
[email protected]d01b8732008-10-16 02:18:071534
1535 // n is the length of the client_id_ string
1536 size_t n = client_id_.size();
1537
1538 // idnumber is a positive integer generated from the client_id_.
1539 // It plus salt is going to give us our pseudorandom number.
1540 int idnumber = 0;
1541 const char* client_id_c_str = client_id_.c_str();
1542
1543 // Here we hash the relevant digits of the client_id_
1544 // string somehow to get a big integer idnumber (could be negative
1545 // from wraparound)
1546 int big = 1;
[email protected]5ed73342009-03-18 17:39:431547 int last_pos = n - 1;
1548 for (size_t j = 0; j < n; ++j) {
1549 idnumber += static_cast<int>(client_id_c_str[last_pos - j]) * big;
[email protected]d01b8732008-10-16 02:18:071550 big *= 10;
1551 }
1552
1553 // Mod id number by denominator making sure to get a non-negative
1554 // answer.
[email protected]cac78842008-11-27 01:02:201555 idnumber = ((idnumber % denominator) + denominator) % denominator;
[email protected]d01b8732008-10-16 02:18:071556
[email protected]cac78842008-11-27 01:02:201557 // ((idnumber + salt) % denominator) / denominator is in the range [0,1]
[email protected]d01b8732008-10-16 02:18:071558 // if it's less than probability we call that an affirmative coin
1559 // toss.
[email protected]cac78842008-11-27 01:02:201560 return static_cast<double>((idnumber + salt) % denominator) <
1561 probability * denominator;
[email protected]d01b8732008-10-16 02:18:071562}
1563
initial.commit09911bf2008-07-26 23:55:291564void MetricsService::LogWindowChange(NotificationType type,
1565 const NotificationSource& source,
1566 const NotificationDetails& details) {
[email protected]534e54b2008-08-13 15:40:091567 int controller_id = -1;
1568 uintptr_t window_or_tab = source.map_key();
initial.commit09911bf2008-07-26 23:55:291569 MetricsLog::WindowEventType window_type;
1570
1571 // Note: since we stop all logging when a single OTR session is active, it is
1572 // possible that we start getting notifications about a window that we don't
1573 // know about.
[email protected]534e54b2008-08-13 15:40:091574 if (window_map_.find(window_or_tab) == window_map_.end()) {
1575 controller_id = next_window_id_++;
1576 window_map_[window_or_tab] = controller_id;
initial.commit09911bf2008-07-26 23:55:291577 } else {
[email protected]534e54b2008-08-13 15:40:091578 controller_id = window_map_[window_or_tab];
initial.commit09911bf2008-07-26 23:55:291579 }
[email protected]92745242009-06-12 16:52:211580 DCHECK_NE(controller_id, -1);
initial.commit09911bf2008-07-26 23:55:291581
[email protected]bfd04a62009-02-01 18:16:561582 switch (type.value) {
1583 case NotificationType::TAB_PARENTED:
1584 case NotificationType::BROWSER_OPENED:
initial.commit09911bf2008-07-26 23:55:291585 window_type = MetricsLog::WINDOW_CREATE;
1586 break;
1587
[email protected]bfd04a62009-02-01 18:16:561588 case NotificationType::TAB_CLOSING:
1589 case NotificationType::BROWSER_CLOSED:
[email protected]534e54b2008-08-13 15:40:091590 window_map_.erase(window_map_.find(window_or_tab));
initial.commit09911bf2008-07-26 23:55:291591 window_type = MetricsLog::WINDOW_DESTROY;
1592 break;
1593
1594 default:
1595 NOTREACHED();
[email protected]68d74f02009-02-13 01:36:501596 return;
initial.commit09911bf2008-07-26 23:55:291597 }
1598
[email protected]534e54b2008-08-13 15:40:091599 // TODO(brettw) we should have some kind of ID for the parent.
1600 current_log_->RecordWindowEvent(window_type, controller_id, 0);
initial.commit09911bf2008-07-26 23:55:291601}
1602
1603void MetricsService::LogLoadComplete(NotificationType type,
1604 const NotificationSource& source,
1605 const NotificationDetails& details) {
1606 if (details == NotificationService::NoDetails())
1607 return;
1608
[email protected]68475e602008-08-22 03:21:151609 // TODO(jar): There is a bug causing this to be called too many times, and
1610 // the log overflows. For now, we won't record these events.
[email protected]553dba62009-02-24 19:08:231611 UMA_HISTOGRAM_COUNTS("UMA.LogLoadComplete called", 1);
[email protected]68475e602008-08-22 03:21:151612 return;
1613
initial.commit09911bf2008-07-26 23:55:291614 const Details<LoadNotificationDetails> load_details(details);
[email protected]534e54b2008-08-13 15:40:091615 int controller_id = window_map_[details.map_key()];
1616 current_log_->RecordLoadEvent(controller_id,
initial.commit09911bf2008-07-26 23:55:291617 load_details->url(),
1618 load_details->origin(),
1619 load_details->session_index(),
1620 load_details->load_time());
1621}
1622
[email protected]e73c01972008-08-13 00:18:241623void MetricsService::IncrementPrefValue(const wchar_t* path) {
1624 PrefService* pref = g_browser_process->local_state();
1625 DCHECK(pref);
1626 int value = pref->GetInteger(path);
1627 pref->SetInteger(path, value + 1);
1628}
1629
[email protected]0bb1a622009-03-04 03:22:321630void MetricsService::IncrementLongPrefsValue(const wchar_t* path) {
1631 PrefService* pref = g_browser_process->local_state();
1632 DCHECK(pref);
1633 int64 value = pref->GetInt64(path);
1634 pref->SetInt64(path, value+1);
1635}
1636
initial.commit09911bf2008-07-26 23:55:291637void MetricsService::LogLoadStarted() {
[email protected]e73c01972008-08-13 00:18:241638 IncrementPrefValue(prefs::kStabilityPageLoadCount);
[email protected]0bb1a622009-03-04 03:22:321639 IncrementLongPrefsValue(prefs::kUninstallMetricsPageLoadCount);
[email protected]0b33f80b2008-12-17 21:34:361640 // We need to save the prefs, as page load count is a critical stat, and it
1641 // might be lost due to a crash :-(.
initial.commit09911bf2008-07-26 23:55:291642}
1643
1644void MetricsService::LogRendererInSandbox(bool on_sandbox_desktop) {
1645 PrefService* prefs = g_browser_process->local_state();
1646 DCHECK(prefs);
[email protected]e73c01972008-08-13 00:18:241647 if (on_sandbox_desktop)
1648 IncrementPrefValue(prefs::kSecurityRendererOnSboxDesktop);
1649 else
1650 IncrementPrefValue(prefs::kSecurityRendererOnDefaultDesktop);
initial.commit09911bf2008-07-26 23:55:291651}
1652
1653void MetricsService::LogRendererCrash() {
[email protected]e73c01972008-08-13 00:18:241654 IncrementPrefValue(prefs::kStabilityRendererCrashCount);
initial.commit09911bf2008-07-26 23:55:291655}
1656
1657void MetricsService::LogRendererHang() {
[email protected]e73c01972008-08-13 00:18:241658 IncrementPrefValue(prefs::kStabilityRendererHangCount);
initial.commit09911bf2008-07-26 23:55:291659}
1660
[email protected]a27a9382009-02-11 23:55:101661void MetricsService::LogChildProcessChange(
1662 NotificationType type,
1663 const NotificationSource& source,
1664 const NotificationDetails& details) {
1665 const std::wstring& child_name =
1666 Details<ChildProcessInfo>(details)->name();
initial.commit09911bf2008-07-26 23:55:291667
[email protected]a27a9382009-02-11 23:55:101668 if (child_process_stats_buffer_.find(child_name) ==
1669 child_process_stats_buffer_.end()) {
1670 child_process_stats_buffer_[child_name] = ChildProcessStats();
initial.commit09911bf2008-07-26 23:55:291671 }
1672
[email protected]a27a9382009-02-11 23:55:101673 ChildProcessStats& stats = child_process_stats_buffer_[child_name];
[email protected]bfd04a62009-02-01 18:16:561674 switch (type.value) {
[email protected]a27a9382009-02-11 23:55:101675 case NotificationType::CHILD_PROCESS_HOST_CONNECTED:
initial.commit09911bf2008-07-26 23:55:291676 stats.process_launches++;
1677 break;
1678
[email protected]a27a9382009-02-11 23:55:101679 case NotificationType::CHILD_INSTANCE_CREATED:
initial.commit09911bf2008-07-26 23:55:291680 stats.instances++;
1681 break;
1682
[email protected]a27a9382009-02-11 23:55:101683 case NotificationType::CHILD_PROCESS_CRASHED:
initial.commit09911bf2008-07-26 23:55:291684 stats.process_crashes++;
1685 break;
1686
1687 default:
[email protected]bfd04a62009-02-01 18:16:561688 NOTREACHED() << "Unexpected notification type " << type.value;
initial.commit09911bf2008-07-26 23:55:291689 return;
1690 }
1691}
1692
1693// Recursively counts the number of bookmarks and folders in node.
[email protected]d8e41ed2008-09-11 15:22:321694static void CountBookmarks(BookmarkNode* node, int* bookmarks, int* folders) {
initial.commit09911bf2008-07-26 23:55:291695 if (node->GetType() == history::StarredEntry::URL)
1696 (*bookmarks)++;
1697 else
1698 (*folders)++;
1699 for (int i = 0; i < node->GetChildCount(); ++i)
1700 CountBookmarks(node->GetChild(i), bookmarks, folders);
1701}
1702
[email protected]d8e41ed2008-09-11 15:22:321703void MetricsService::LogBookmarks(BookmarkNode* node,
initial.commit09911bf2008-07-26 23:55:291704 const wchar_t* num_bookmarks_key,
1705 const wchar_t* num_folders_key) {
1706 DCHECK(node);
1707 int num_bookmarks = 0;
1708 int num_folders = 0;
1709 CountBookmarks(node, &num_bookmarks, &num_folders);
1710 num_folders--; // Don't include the root folder in the count.
1711
1712 PrefService* pref = g_browser_process->local_state();
1713 DCHECK(pref);
1714 pref->SetInteger(num_bookmarks_key, num_bookmarks);
1715 pref->SetInteger(num_folders_key, num_folders);
1716}
1717
[email protected]d8e41ed2008-09-11 15:22:321718void MetricsService::LogBookmarks(BookmarkModel* model) {
initial.commit09911bf2008-07-26 23:55:291719 DCHECK(model);
1720 LogBookmarks(model->GetBookmarkBarNode(),
1721 prefs::kNumBookmarksOnBookmarkBar,
1722 prefs::kNumFoldersOnBookmarkBar);
1723 LogBookmarks(model->other_node(),
1724 prefs::kNumBookmarksInOtherBookmarkFolder,
1725 prefs::kNumFoldersInOtherBookmarkFolder);
1726 ScheduleNextStateSave();
1727}
1728
1729void MetricsService::LogKeywords(const TemplateURLModel* url_model) {
1730 DCHECK(url_model);
1731
1732 PrefService* pref = g_browser_process->local_state();
1733 DCHECK(pref);
1734 pref->SetInteger(prefs::kNumKeywords,
1735 static_cast<int>(url_model->GetTemplateURLs().size()));
1736 ScheduleNextStateSave();
1737}
1738
1739void MetricsService::RecordPluginChanges(PrefService* pref) {
1740 ListValue* plugins = pref->GetMutableList(prefs::kStabilityPluginStats);
1741 DCHECK(plugins);
1742
1743 for (ListValue::iterator value_iter = plugins->begin();
1744 value_iter != plugins->end(); ++value_iter) {
1745 if (!(*value_iter)->IsType(Value::TYPE_DICTIONARY)) {
1746 NOTREACHED();
1747 continue;
1748 }
1749
1750 DictionaryValue* plugin_dict = static_cast<DictionaryValue*>(*value_iter);
[email protected]8e50b602009-03-03 22:59:431751 std::wstring plugin_name;
1752 plugin_dict->GetString(prefs::kStabilityPluginName, &plugin_name);
[email protected]6470ee8f2009-03-03 20:46:401753 if (plugin_name.empty()) {
initial.commit09911bf2008-07-26 23:55:291754 NOTREACHED();
1755 continue;
1756 }
1757
[email protected]8e50b602009-03-03 22:59:431758 if (child_process_stats_buffer_.find(plugin_name) ==
[email protected]a27a9382009-02-11 23:55:101759 child_process_stats_buffer_.end())
initial.commit09911bf2008-07-26 23:55:291760 continue;
1761
[email protected]8e50b602009-03-03 22:59:431762 ChildProcessStats stats = child_process_stats_buffer_[plugin_name];
initial.commit09911bf2008-07-26 23:55:291763 if (stats.process_launches) {
1764 int launches = 0;
[email protected]8e50b602009-03-03 22:59:431765 plugin_dict->GetInteger(prefs::kStabilityPluginLaunches, &launches);
initial.commit09911bf2008-07-26 23:55:291766 launches += stats.process_launches;
[email protected]8e50b602009-03-03 22:59:431767 plugin_dict->SetInteger(prefs::kStabilityPluginLaunches, launches);
initial.commit09911bf2008-07-26 23:55:291768 }
1769 if (stats.process_crashes) {
1770 int crashes = 0;
[email protected]8e50b602009-03-03 22:59:431771 plugin_dict->GetInteger(prefs::kStabilityPluginCrashes, &crashes);
initial.commit09911bf2008-07-26 23:55:291772 crashes += stats.process_crashes;
[email protected]8e50b602009-03-03 22:59:431773 plugin_dict->SetInteger(prefs::kStabilityPluginCrashes, crashes);
initial.commit09911bf2008-07-26 23:55:291774 }
1775 if (stats.instances) {
1776 int instances = 0;
[email protected]8e50b602009-03-03 22:59:431777 plugin_dict->GetInteger(prefs::kStabilityPluginInstances, &instances);
initial.commit09911bf2008-07-26 23:55:291778 instances += stats.instances;
[email protected]8e50b602009-03-03 22:59:431779 plugin_dict->SetInteger(prefs::kStabilityPluginInstances, instances);
initial.commit09911bf2008-07-26 23:55:291780 }
1781
[email protected]8e50b602009-03-03 22:59:431782 child_process_stats_buffer_.erase(plugin_name);
initial.commit09911bf2008-07-26 23:55:291783 }
1784
1785 // Now go through and add dictionaries for plugins that didn't already have
1786 // reports in Local State.
[email protected]a27a9382009-02-11 23:55:101787 for (std::map<std::wstring, ChildProcessStats>::iterator cache_iter =
1788 child_process_stats_buffer_.begin();
1789 cache_iter != child_process_stats_buffer_.end(); ++cache_iter) {
1790 std::wstring plugin_name = cache_iter->first;
1791 ChildProcessStats stats = cache_iter->second;
initial.commit09911bf2008-07-26 23:55:291792 DictionaryValue* plugin_dict = new DictionaryValue;
1793
[email protected]8e50b602009-03-03 22:59:431794 plugin_dict->SetString(prefs::kStabilityPluginName, plugin_name);
1795 plugin_dict->SetInteger(prefs::kStabilityPluginLaunches,
initial.commit09911bf2008-07-26 23:55:291796 stats.process_launches);
[email protected]8e50b602009-03-03 22:59:431797 plugin_dict->SetInteger(prefs::kStabilityPluginCrashes,
initial.commit09911bf2008-07-26 23:55:291798 stats.process_crashes);
[email protected]8e50b602009-03-03 22:59:431799 plugin_dict->SetInteger(prefs::kStabilityPluginInstances,
initial.commit09911bf2008-07-26 23:55:291800 stats.instances);
1801 plugins->Append(plugin_dict);
1802 }
[email protected]a27a9382009-02-11 23:55:101803 child_process_stats_buffer_.clear();
initial.commit09911bf2008-07-26 23:55:291804}
1805
1806bool MetricsService::CanLogNotification(NotificationType type,
1807 const NotificationSource& source,
1808 const NotificationDetails& details) {
1809 // We simply don't log anything to UMA if there is a single off the record
1810 // session visible. The problem is that we always notify using the orginal
1811 // profile in order to simplify notification processing.
1812 return !BrowserList::IsOffTheRecordSessionActive();
1813}
1814
1815void MetricsService::RecordBooleanPrefValue(const wchar_t* path, bool value) {
1816 DCHECK(IsSingleThreaded());
1817
1818 PrefService* pref = g_browser_process->local_state();
1819 DCHECK(pref);
1820
1821 pref->SetBoolean(path, value);
1822 RecordCurrentState(pref);
1823}
1824
1825void MetricsService::RecordCurrentState(PrefService* pref) {
[email protected]0bb1a622009-03-04 03:22:321826 pref->SetInt64(prefs::kStabilityLastTimestampSec, Time::Now().ToTimeT());
initial.commit09911bf2008-07-26 23:55:291827
1828 RecordPluginChanges(pref);
1829}
1830
initial.commit09911bf2008-07-26 23:55:291831void MetricsService::RecordCurrentHistograms() {
1832 DCHECK(current_log_);
1833
initial.commit09911bf2008-07-26 23:55:291834 StatisticsRecorder::Histograms histograms;
1835 StatisticsRecorder::GetHistograms(&histograms);
1836 for (StatisticsRecorder::Histograms::iterator it = histograms.begin();
1837 histograms.end() != it;
[email protected]cac78842008-11-27 01:02:201838 ++it) {
initial.commit09911bf2008-07-26 23:55:291839 if ((*it)->flags() & kUmaTargetedHistogramFlag)
[email protected]0b33f80b2008-12-17 21:34:361840 // TODO(petersont): Only record historgrams if they are not precluded by
1841 // the UMA response data.
[email protected]d01b8732008-10-16 02:18:071842 // Bug http://code.google.com/p/chromium/issues/detail?id=2739.
initial.commit09911bf2008-07-26 23:55:291843 RecordHistogram(**it);
1844 }
1845}
1846
1847void MetricsService::RecordHistogram(const Histogram& histogram) {
1848 // Get up-to-date snapshot of sample stats.
1849 Histogram::SampleSet snapshot;
1850 histogram.SnapshotSample(&snapshot);
1851
1852 const std::string& histogram_name = histogram.histogram_name();
1853
1854 // Find the already sent stats, or create an empty set.
1855 LoggedSampleMap::iterator it = logged_samples_.find(histogram_name);
1856 Histogram::SampleSet* already_logged;
1857 if (logged_samples_.end() == it) {
1858 // Add new entry
1859 already_logged = &logged_samples_[histogram.histogram_name()];
1860 already_logged->Resize(histogram); // Complete initialization.
1861 } else {
1862 already_logged = &(it->second);
1863 // Deduct any stats we've already logged from our snapshot.
1864 snapshot.Subtract(*already_logged);
1865 }
1866
1867 // snapshot now contains only a delta to what we've already_logged.
1868
1869 if (snapshot.TotalCount() > 0) {
1870 current_log_->RecordHistogramDelta(histogram, snapshot);
1871 // Add new data into our running total.
1872 already_logged->Add(snapshot);
1873 }
1874}
1875
1876void MetricsService::AddProfileMetric(Profile* profile,
1877 const std::wstring& key,
1878 int value) {
1879 // Restriction of types is needed for writing values. See
1880 // MetricsLog::WriteProfileMetrics.
1881 DCHECK(profile && !key.empty());
1882 PrefService* prefs = g_browser_process->local_state();
1883 DCHECK(prefs);
1884
1885 // Key is stored in prefs, which interpret '.'s as paths. As such, key
1886 // shouldn't have any '.'s in it.
1887 DCHECK(key.find(L'.') == std::wstring::npos);
1888 // The id is most likely an email address. We shouldn't send it to the server.
1889 const std::wstring id_hash =
1890 UTF8ToWide(MetricsLog::CreateBase64Hash(WideToUTF8(profile->GetID())));
1891 DCHECK(id_hash.find('.') == std::string::npos);
1892
1893 DictionaryValue* prof_prefs = prefs->GetMutableDictionary(
1894 prefs::kProfileMetrics);
1895 DCHECK(prof_prefs);
1896 const std::wstring pref_key = std::wstring(prefs::kProfilePrefix) + id_hash +
1897 L"." + key;
[email protected]8e50b602009-03-03 22:59:431898 prof_prefs->SetInteger(pref_key.c_str(), value);
initial.commit09911bf2008-07-26 23:55:291899}
1900
1901static bool IsSingleThreaded() {
[email protected]dc6f4962009-02-13 01:25:501902 static PlatformThreadId thread_id = 0;
initial.commit09911bf2008-07-26 23:55:291903 if (!thread_id)
[email protected]dc6f4962009-02-13 01:25:501904 thread_id = PlatformThread::CurrentId();
1905 return PlatformThread::CurrentId() == thread_id;
initial.commit09911bf2008-07-26 23:55:291906}