blob: c822500fbfb351c3b36468b868439f1fa5cb7095 [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]c9a3ef82009-05-28 22:02:46184#include "chrome/common/histogram_synchronizer.h"
[email protected]252873ef2008-08-04 21:59:45185#include "chrome/common/libxml_utils.h"
[email protected]bfd04a62009-02-01 18:16:56186#include "chrome/common/notification_service.h"
initial.commit09911bf2008-07-26 23:55:29187#include "chrome/common/pref_names.h"
188#include "chrome/common/pref_service.h"
[email protected]e09ba552009-02-05 03:26:29189#include "chrome/common/render_messages.h"
initial.commit09911bf2008-07-26 23:55:29190#include "googleurl/src/gurl.h"
191#include "net/base/load_flags.h"
192#include "third_party/bzip2/bzlib.h"
193
[email protected]dc6f4962009-02-13 01:25:50194#if defined(OS_POSIX)
195// TODO(port): Move these headers above as they are ported.
196#include "chrome/common/temp_scaffolding_stubs.h"
197#else
[email protected]79bf0b72009-04-27 21:30:55198#include "chrome/installer/util/browser_distribution.h"
[email protected]dc6f4962009-02-13 01:25:50199#include "chrome/installer/util/google_update_settings.h"
200#endif
201
[email protected]e1acf6f2008-10-27 20:43:33202using base::Time;
203using base::TimeDelta;
204
initial.commit09911bf2008-07-26 23:55:29205// Check to see that we're being called on only one thread.
206static bool IsSingleThreaded();
207
initial.commit09911bf2008-07-26 23:55:29208static const char kMetricsType[] = "application/vnd.mozilla.metrics.bz2";
209
210// The delay, in seconds, after startup before sending the first log message.
[email protected]252873ef2008-08-04 21:59:45211static const int kInitialInterlogDuration = 60; // one minute
212
[email protected]c9a3ef82009-05-28 22:02:46213// This specifies the amount of time to wait for all renderers to send their
214// data.
215static const int kMaxHistogramGatheringWaitDuration = 60000; // 60 seconds.
216
[email protected]252873ef2008-08-04 21:59:45217// The default maximum number of events in a log uploaded to the UMA server.
[email protected]0b33f80b2008-12-17 21:34:36218static const int kInitialEventLimit = 2400;
[email protected]68475e602008-08-22 03:21:15219
220// If an upload fails, and the transmission was over this byte count, then we
221// will discard the log, and not try to retransmit it. We also don't persist
222// the log to the prefs for transmission during the next chrome session if this
223// limit is exceeded.
224static const int kUploadLogAvoidRetransmitSize = 50000;
initial.commit09911bf2008-07-26 23:55:29225
226// When we have logs from previous Chrome sessions to send, how long should we
227// delay (in seconds) between each log transmission.
228static const int kUnsentLogDelay = 15; // 15 seconds
229
230// Minimum time a log typically exists before sending, in seconds.
231// This number is supplied by the server, but until we parse it out of a server
232// response, we use this duration to specify how long we should wait before
233// sending the next log. If the channel is busy, such as when there is a
234// failure during an attempt to transmit a previous log, then a log may wait
235// (and continue to accrue now log entries) for a much greater period of time.
[email protected]0eb34fee2009-01-21 08:04:38236static const int kMinSecondsPerLog = 20 * 60; // Twenty minutes.
initial.commit09911bf2008-07-26 23:55:29237
initial.commit09911bf2008-07-26 23:55:29238// When we don't succeed at transmitting a log to a server, we progressively
239// wait longer and longer before sending the next log. This backoff process
240// help reduce load on the server, and makes the amount of backoff vary between
241// clients so that a collision (server overload?) on retransmit is less likely.
242// The following is the constant we use to expand that inter-log duration.
243static const double kBackoff = 1.1;
244// We limit the maximum backoff to be no greater than some multiple of the
245// default kMinSecondsPerLog. The following is that maximum ratio.
246static const int kMaxBackoff = 10;
247
248// Interval, in seconds, between state saves.
249static const int kSaveStateInterval = 5 * 60; // five minutes
250
251// The number of "initial" logs we're willing to save, and hope to send during
252// a future Chrome session. Initial logs contain crash stats, and are pretty
253// small.
254static const size_t kMaxInitialLogsPersisted = 20;
255
256// The number of ongoing logs we're willing to save persistently, and hope to
[email protected]281d2882009-01-20 20:32:42257// send during a this or future sessions. Note that each log may be pretty
initial.commit09911bf2008-07-26 23:55:29258// large, as presumably the related "initial" log wasn't sent (probably nothing
259// was, as the user was probably off-line). As a result, the log probably kept
260// accumulating while the "initial" log was stalled (pending_), and couldn't be
261// sent. As a result, we don't want to save too many of these mega-logs.
262// A "standard shutdown" will create a small log, including just the data that
263// was not yet been transmitted, and that is normal (to have exactly one
264// ongoing_log_ at startup).
[email protected]281d2882009-01-20 20:32:42265static const size_t kMaxOngoingLogsPersisted = 8;
initial.commit09911bf2008-07-26 23:55:29266
267
268// Handles asynchronous fetching of memory details.
269// Will run the provided task after finished.
270class MetricsMemoryDetails : public MemoryDetails {
271 public:
272 explicit MetricsMemoryDetails(Task* completion) : completion_(completion) {}
273
274 virtual void OnDetailsAvailable() {
275 MessageLoop::current()->PostTask(FROM_HERE, completion_);
276 }
277
278 private:
279 Task* completion_;
280 DISALLOW_EVIL_CONSTRUCTORS(MetricsMemoryDetails);
281};
282
283class MetricsService::GetPluginListTaskComplete : public Task {
284 virtual void Run() {
285 g_browser_process->metrics_service()->OnGetPluginListTaskComplete();
286 }
287};
288
289class MetricsService::GetPluginListTask : public Task {
290 public:
291 explicit GetPluginListTask(MessageLoop* callback_loop)
292 : callback_loop_(callback_loop) {}
293
294 virtual void Run() {
295 std::vector<WebPluginInfo> plugins;
296 PluginService::GetInstance()->GetPlugins(false, &plugins);
297
298 callback_loop_->PostTask(FROM_HERE, new GetPluginListTaskComplete());
299 }
300
301 private:
302 MessageLoop* callback_loop_;
303};
304
305// static
306void MetricsService::RegisterPrefs(PrefService* local_state) {
307 DCHECK(IsSingleThreaded());
308 local_state->RegisterStringPref(prefs::kMetricsClientID, L"");
[email protected]0bb1a622009-03-04 03:22:32309 local_state->RegisterInt64Pref(prefs::kMetricsClientIDTimestamp, 0);
310 local_state->RegisterInt64Pref(prefs::kStabilityLaunchTimeSec, 0);
311 local_state->RegisterInt64Pref(prefs::kStabilityLastTimestampSec, 0);
312 local_state->RegisterInt64Pref(prefs::kStabilityUptimeSec, 0);
[email protected]541f77922009-02-23 21:14:38313 local_state->RegisterStringPref(prefs::kStabilityStatsVersion, L"");
initial.commit09911bf2008-07-26 23:55:29314 local_state->RegisterBooleanPref(prefs::kStabilityExitedCleanly, true);
315 local_state->RegisterBooleanPref(prefs::kStabilitySessionEndCompleted, true);
316 local_state->RegisterIntegerPref(prefs::kMetricsSessionID, -1);
317 local_state->RegisterIntegerPref(prefs::kStabilityLaunchCount, 0);
318 local_state->RegisterIntegerPref(prefs::kStabilityCrashCount, 0);
319 local_state->RegisterIntegerPref(prefs::kStabilityIncompleteSessionEndCount,
320 0);
321 local_state->RegisterIntegerPref(prefs::kStabilityPageLoadCount, 0);
322 local_state->RegisterIntegerPref(prefs::kSecurityRendererOnSboxDesktop, 0);
323 local_state->RegisterIntegerPref(prefs::kSecurityRendererOnDefaultDesktop, 0);
324 local_state->RegisterIntegerPref(prefs::kStabilityRendererCrashCount, 0);
325 local_state->RegisterIntegerPref(prefs::kStabilityRendererHangCount, 0);
[email protected]e73c01972008-08-13 00:18:24326 local_state->RegisterIntegerPref(prefs::kStabilityBreakpadRegistrationFail,
327 0);
328 local_state->RegisterIntegerPref(prefs::kStabilityBreakpadRegistrationSuccess,
329 0);
330 local_state->RegisterIntegerPref(prefs::kStabilityDebuggerPresent, 0);
331 local_state->RegisterIntegerPref(prefs::kStabilityDebuggerNotPresent, 0);
332
initial.commit09911bf2008-07-26 23:55:29333 local_state->RegisterDictionaryPref(prefs::kProfileMetrics);
334 local_state->RegisterIntegerPref(prefs::kNumBookmarksOnBookmarkBar, 0);
335 local_state->RegisterIntegerPref(prefs::kNumFoldersOnBookmarkBar, 0);
336 local_state->RegisterIntegerPref(prefs::kNumBookmarksInOtherBookmarkFolder,
337 0);
338 local_state->RegisterIntegerPref(prefs::kNumFoldersInOtherBookmarkFolder, 0);
339 local_state->RegisterIntegerPref(prefs::kNumKeywords, 0);
340 local_state->RegisterListPref(prefs::kMetricsInitialLogs);
341 local_state->RegisterListPref(prefs::kMetricsOngoingLogs);
[email protected]0bb1a622009-03-04 03:22:32342
343 local_state->RegisterInt64Pref(prefs::kUninstallMetricsPageLoadCount, 0);
344 local_state->RegisterInt64Pref(prefs::kUninstallLaunchCount, 0);
[email protected]6b5f21d2009-04-13 17:01:35345 local_state->RegisterInt64Pref(prefs::kUninstallMetricsInstallDate, 0);
[email protected]0bb1a622009-03-04 03:22:32346 local_state->RegisterInt64Pref(prefs::kUninstallMetricsUptimeSec, 0);
347 local_state->RegisterInt64Pref(prefs::kUninstallLastLaunchTimeSec, 0);
348 local_state->RegisterInt64Pref(prefs::kUninstallLastObservedRunTimeSec, 0);
initial.commit09911bf2008-07-26 23:55:29349}
350
[email protected]541f77922009-02-23 21:14:38351// static
352void MetricsService::DiscardOldStabilityStats(PrefService* local_state) {
353 local_state->SetBoolean(prefs::kStabilityExitedCleanly, true);
354
355 local_state->SetInteger(prefs::kStabilityIncompleteSessionEndCount, 0);
356 local_state->SetInteger(prefs::kStabilityBreakpadRegistrationSuccess, 0);
357 local_state->SetInteger(prefs::kStabilityBreakpadRegistrationFail, 0);
358 local_state->SetInteger(prefs::kStabilityDebuggerPresent, 0);
359 local_state->SetInteger(prefs::kStabilityDebuggerNotPresent, 0);
360
361 local_state->SetInteger(prefs::kStabilityLaunchCount, 0);
362 local_state->SetInteger(prefs::kStabilityCrashCount, 0);
363
364 local_state->SetInteger(prefs::kStabilityPageLoadCount, 0);
365 local_state->SetInteger(prefs::kStabilityRendererCrashCount, 0);
366 local_state->SetInteger(prefs::kStabilityRendererHangCount, 0);
367
368 local_state->SetInteger(prefs::kSecurityRendererOnSboxDesktop, 0);
369 local_state->SetInteger(prefs::kSecurityRendererOnDefaultDesktop, 0);
370
371 local_state->SetString(prefs::kStabilityUptimeSec, L"0");
372
373 local_state->ClearPref(prefs::kStabilityPluginStats);
374}
375
initial.commit09911bf2008-07-26 23:55:29376MetricsService::MetricsService()
[email protected]d01b8732008-10-16 02:18:07377 : recording_active_(false),
378 reporting_active_(false),
379 user_permits_upload_(false),
380 server_permits_upload_(true),
381 state_(INITIALIZED),
initial.commit09911bf2008-07-26 23:55:29382 pending_log_(NULL),
383 pending_log_text_(""),
384 current_fetch_(NULL),
385 current_log_(NULL),
[email protected]d01b8732008-10-16 02:18:07386 idle_since_last_transmission_(false),
initial.commit09911bf2008-07-26 23:55:29387 next_window_id_(0),
[email protected]40bcc302009-03-02 20:50:39388 ALLOW_THIS_IN_INITIALIZER_LIST(log_sender_factory_(this)),
389 ALLOW_THIS_IN_INITIALIZER_LIST(state_saver_factory_(this)),
initial.commit09911bf2008-07-26 23:55:29390 logged_samples_(),
[email protected]252873ef2008-08-04 21:59:45391 interlog_duration_(TimeDelta::FromSeconds(kInitialInterlogDuration)),
[email protected]d01b8732008-10-16 02:18:07392 log_event_limit_(kInitialEventLimit),
initial.commit09911bf2008-07-26 23:55:29393 timer_pending_(false) {
394 DCHECK(IsSingleThreaded());
395 InitializeMetricsState();
396}
397
398MetricsService::~MetricsService() {
399 SetRecording(false);
[email protected]d8bc79bf2009-01-28 01:17:58400 if (pending_log_) {
401 delete pending_log_;
402 pending_log_ = NULL;
403 }
404 if (current_log_) {
405 delete current_log_;
406 current_log_ = NULL;
407 }
initial.commit09911bf2008-07-26 23:55:29408}
409
[email protected]d01b8732008-10-16 02:18:07410void MetricsService::SetUserPermitsUpload(bool enabled) {
411 HandleIdleSinceLastTransmission(false);
412 user_permits_upload_ = enabled;
413}
414
415void MetricsService::Start() {
416 SetRecording(true);
417 SetReporting(true);
418}
419
420void MetricsService::StartRecordingOnly() {
421 SetRecording(true);
422 SetReporting(false);
423}
424
425void MetricsService::Stop() {
426 SetReporting(false);
427 SetRecording(false);
428}
429
initial.commit09911bf2008-07-26 23:55:29430void MetricsService::SetRecording(bool enabled) {
431 DCHECK(IsSingleThreaded());
432
[email protected]d01b8732008-10-16 02:18:07433 if (enabled == recording_active_)
initial.commit09911bf2008-07-26 23:55:29434 return;
435
436 if (enabled) {
[email protected]b0c819f2009-03-08 04:52:15437 if (client_id_.empty()) {
438 PrefService* pref = g_browser_process->local_state();
439 DCHECK(pref);
440 client_id_ = WideToUTF8(pref->GetString(prefs::kMetricsClientID));
441 if (client_id_.empty()) {
442 client_id_ = GenerateClientID();
443 pref->SetString(prefs::kMetricsClientID, UTF8ToWide(client_id_));
444
445 // Might as well make a note of how long this ID has existed
446 pref->SetString(prefs::kMetricsClientIDTimestamp,
447 Int64ToWString(Time::Now().ToTimeT()));
448 }
449 }
initial.commit09911bf2008-07-26 23:55:29450 StartRecording();
[email protected]005ef3e2009-05-22 20:55:46451
452 registrar_.Add(this, NotificationType::BROWSER_OPENED,
453 NotificationService::AllSources());
454 registrar_.Add(this, NotificationType::BROWSER_CLOSED,
455 NotificationService::AllSources());
456 registrar_.Add(this, NotificationType::USER_ACTION,
457 NotificationService::AllSources());
458 registrar_.Add(this, NotificationType::TAB_PARENTED,
459 NotificationService::AllSources());
460 registrar_.Add(this, NotificationType::TAB_CLOSING,
461 NotificationService::AllSources());
462 registrar_.Add(this, NotificationType::LOAD_START,
463 NotificationService::AllSources());
464 registrar_.Add(this, NotificationType::LOAD_STOP,
465 NotificationService::AllSources());
466 registrar_.Add(this, NotificationType::RENDERER_PROCESS_IN_SBOX,
467 NotificationService::AllSources());
468 registrar_.Add(this, NotificationType::RENDERER_PROCESS_CLOSED,
469 NotificationService::AllSources());
470 registrar_.Add(this, NotificationType::RENDERER_PROCESS_HANG,
471 NotificationService::AllSources());
472 registrar_.Add(this, NotificationType::CHILD_PROCESS_HOST_CONNECTED,
473 NotificationService::AllSources());
474 registrar_.Add(this, NotificationType::CHILD_INSTANCE_CREATED,
475 NotificationService::AllSources());
476 registrar_.Add(this, NotificationType::CHILD_PROCESS_CRASHED,
477 NotificationService::AllSources());
478 registrar_.Add(this, NotificationType::TEMPLATE_URL_MODEL_LOADED,
479 NotificationService::AllSources());
480 registrar_.Add(this, NotificationType::OMNIBOX_OPENED_URL,
481 NotificationService::AllSources());
482 registrar_.Add(this, NotificationType::BOOKMARK_MODEL_LOADED,
483 NotificationService::AllSources());
initial.commit09911bf2008-07-26 23:55:29484 } else {
[email protected]005ef3e2009-05-22 20:55:46485 registrar_.RemoveAll();
initial.commit09911bf2008-07-26 23:55:29486 PushPendingLogsToUnsentLists();
487 DCHECK(!pending_log());
488 if (state_ > INITIAL_LOG_READY && unsent_logs())
489 state_ = SEND_OLD_INITIAL_LOGS;
490 }
[email protected]d01b8732008-10-16 02:18:07491 recording_active_ = enabled;
initial.commit09911bf2008-07-26 23:55:29492}
493
[email protected]d01b8732008-10-16 02:18:07494bool MetricsService::recording_active() const {
initial.commit09911bf2008-07-26 23:55:29495 DCHECK(IsSingleThreaded());
[email protected]d01b8732008-10-16 02:18:07496 return recording_active_;
initial.commit09911bf2008-07-26 23:55:29497}
498
[email protected]d01b8732008-10-16 02:18:07499void MetricsService::SetReporting(bool enable) {
500 if (reporting_active_ != enable) {
501 reporting_active_ = enable;
502 if (reporting_active_)
initial.commit09911bf2008-07-26 23:55:29503 StartLogTransmissionTimer();
504 }
[email protected]d01b8732008-10-16 02:18:07505}
506
507bool MetricsService::reporting_active() const {
508 DCHECK(IsSingleThreaded());
509 return reporting_active_;
initial.commit09911bf2008-07-26 23:55:29510}
511
512void MetricsService::Observe(NotificationType type,
513 const NotificationSource& source,
514 const NotificationDetails& details) {
515 DCHECK(current_log_);
516 DCHECK(IsSingleThreaded());
517
518 if (!CanLogNotification(type, source, details))
519 return;
520
[email protected]bfd04a62009-02-01 18:16:56521 switch (type.value) {
522 case NotificationType::USER_ACTION:
initial.commit09911bf2008-07-26 23:55:29523 current_log_->RecordUserAction(*Details<const wchar_t*>(details).ptr());
524 break;
525
[email protected]bfd04a62009-02-01 18:16:56526 case NotificationType::BROWSER_OPENED:
527 case NotificationType::BROWSER_CLOSED:
initial.commit09911bf2008-07-26 23:55:29528 LogWindowChange(type, source, details);
529 break;
530
[email protected]bfd04a62009-02-01 18:16:56531 case NotificationType::TAB_PARENTED:
532 case NotificationType::TAB_CLOSING:
initial.commit09911bf2008-07-26 23:55:29533 LogWindowChange(type, source, details);
534 break;
535
[email protected]bfd04a62009-02-01 18:16:56536 case NotificationType::LOAD_STOP:
initial.commit09911bf2008-07-26 23:55:29537 LogLoadComplete(type, source, details);
538 break;
539
[email protected]bfd04a62009-02-01 18:16:56540 case NotificationType::LOAD_START:
initial.commit09911bf2008-07-26 23:55:29541 LogLoadStarted();
542 break;
543
[email protected]6ba2ec22009-05-05 00:50:53544 case NotificationType::RENDERER_PROCESS_CLOSED:
545 if (*Details<bool>(details).ptr())
546 LogRendererCrash();
initial.commit09911bf2008-07-26 23:55:29547 break;
548
[email protected]bfd04a62009-02-01 18:16:56549 case NotificationType::RENDERER_PROCESS_HANG:
initial.commit09911bf2008-07-26 23:55:29550 LogRendererHang();
551 break;
552
[email protected]bfd04a62009-02-01 18:16:56553 case NotificationType::RENDERER_PROCESS_IN_SBOX:
initial.commit09911bf2008-07-26 23:55:29554 LogRendererInSandbox(*Details<bool>(details).ptr());
555 break;
556
[email protected]a27a9382009-02-11 23:55:10557 case NotificationType::CHILD_PROCESS_HOST_CONNECTED:
558 case NotificationType::CHILD_PROCESS_CRASHED:
559 case NotificationType::CHILD_INSTANCE_CREATED:
560 LogChildProcessChange(type, source, details);
initial.commit09911bf2008-07-26 23:55:29561 break;
562
[email protected]bfd04a62009-02-01 18:16:56563 case NotificationType::TEMPLATE_URL_MODEL_LOADED:
initial.commit09911bf2008-07-26 23:55:29564 LogKeywords(Source<TemplateURLModel>(source).ptr());
565 break;
566
[email protected]bfd04a62009-02-01 18:16:56567 case NotificationType::OMNIBOX_OPENED_URL:
initial.commit09911bf2008-07-26 23:55:29568 current_log_->RecordOmniboxOpenedURL(
569 *Details<AutocompleteLog>(details).ptr());
570 break;
571
[email protected]b61236c62009-04-09 22:43:55572 case NotificationType::BOOKMARK_MODEL_LOADED: {
573 Profile* p = Source<Profile>(source).ptr();
574 if (p)
575 LogBookmarks(p->GetBookmarkModel());
initial.commit09911bf2008-07-26 23:55:29576 break;
[email protected]b61236c62009-04-09 22:43:55577 }
initial.commit09911bf2008-07-26 23:55:29578 default:
579 NOTREACHED();
580 break;
581 }
[email protected]d01b8732008-10-16 02:18:07582
583 HandleIdleSinceLastTransmission(false);
584
585 if (current_log_)
[email protected]281d2882009-01-20 20:32:42586 DLOG(INFO) << "METRICS: NUMBER OF EVENTS = " << current_log_->num_events();
[email protected]d01b8732008-10-16 02:18:07587}
588
589void MetricsService::HandleIdleSinceLastTransmission(bool in_idle) {
590 // If there wasn't a lot of action, maybe the computer was asleep, in which
591 // case, the log transmissions should have stopped. Here we start them up
592 // again.
[email protected]cac78842008-11-27 01:02:20593 if (!in_idle && idle_since_last_transmission_)
594 StartLogTransmissionTimer();
595 idle_since_last_transmission_ = in_idle;
initial.commit09911bf2008-07-26 23:55:29596}
597
598void MetricsService::RecordCleanShutdown() {
599 RecordBooleanPrefValue(prefs::kStabilityExitedCleanly, true);
600}
601
602void MetricsService::RecordStartOfSessionEnd() {
603 RecordBooleanPrefValue(prefs::kStabilitySessionEndCompleted, false);
604}
605
606void MetricsService::RecordCompletedSessionEnd() {
607 RecordBooleanPrefValue(prefs::kStabilitySessionEndCompleted, true);
608}
609
[email protected]e73c01972008-08-13 00:18:24610void MetricsService:: RecordBreakpadRegistration(bool success) {
[email protected]68475e602008-08-22 03:21:15611 if (!success)
[email protected]e73c01972008-08-13 00:18:24612 IncrementPrefValue(prefs::kStabilityBreakpadRegistrationFail);
613 else
614 IncrementPrefValue(prefs::kStabilityBreakpadRegistrationSuccess);
615}
616
617void MetricsService::RecordBreakpadHasDebugger(bool has_debugger) {
618 if (!has_debugger)
619 IncrementPrefValue(prefs::kStabilityDebuggerNotPresent);
620 else
[email protected]68475e602008-08-22 03:21:15621 IncrementPrefValue(prefs::kStabilityDebuggerPresent);
[email protected]e73c01972008-08-13 00:18:24622}
623
initial.commit09911bf2008-07-26 23:55:29624//------------------------------------------------------------------------------
625// private methods
626//------------------------------------------------------------------------------
627
628
629//------------------------------------------------------------------------------
630// Initialization methods
631
632void MetricsService::InitializeMetricsState() {
[email protected]79bf0b72009-04-27 21:30:55633#if defined(OS_POSIX)
634 server_url_ = L"https://clients4.google.com/firefox/metrics/collect";
635#else
636 BrowserDistribution* dist = BrowserDistribution::GetDistribution();
637 server_url_ = dist->GetStatsServerURL();
638#endif
639
initial.commit09911bf2008-07-26 23:55:29640 PrefService* pref = g_browser_process->local_state();
641 DCHECK(pref);
642
[email protected]541f77922009-02-23 21:14:38643 if (WideToUTF8(pref->GetString(prefs::kStabilityStatsVersion)) !=
644 MetricsLog::GetVersionString()) {
645 // This is a new version, so we don't want to confuse the stats about the
646 // old version with info that we upload.
647 DiscardOldStabilityStats(pref);
648 pref->SetString(prefs::kStabilityStatsVersion,
649 UTF8ToWide(MetricsLog::GetVersionString()));
650 }
651
initial.commit09911bf2008-07-26 23:55:29652 // Update session ID
653 session_id_ = pref->GetInteger(prefs::kMetricsSessionID);
654 ++session_id_;
655 pref->SetInteger(prefs::kMetricsSessionID, session_id_);
656
initial.commit09911bf2008-07-26 23:55:29657 // Stability bookkeeping
[email protected]e73c01972008-08-13 00:18:24658 IncrementPrefValue(prefs::kStabilityLaunchCount);
initial.commit09911bf2008-07-26 23:55:29659
[email protected]e73c01972008-08-13 00:18:24660 if (!pref->GetBoolean(prefs::kStabilityExitedCleanly)) {
661 IncrementPrefValue(prefs::kStabilityCrashCount);
initial.commit09911bf2008-07-26 23:55:29662 }
[email protected]e73c01972008-08-13 00:18:24663
664 // This will be set to 'true' if we exit cleanly.
initial.commit09911bf2008-07-26 23:55:29665 pref->SetBoolean(prefs::kStabilityExitedCleanly, false);
666
[email protected]e73c01972008-08-13 00:18:24667 if (!pref->GetBoolean(prefs::kStabilitySessionEndCompleted)) {
668 IncrementPrefValue(prefs::kStabilityIncompleteSessionEndCount);
initial.commit09911bf2008-07-26 23:55:29669 }
670 // This is marked false when we get a WM_ENDSESSION.
671 pref->SetBoolean(prefs::kStabilitySessionEndCompleted, true);
672
[email protected]0bb1a622009-03-04 03:22:32673 int64 last_start_time = pref->GetInt64(prefs::kStabilityLaunchTimeSec);
674 int64 last_end_time = pref->GetInt64(prefs::kStabilityLastTimestampSec);
675 int64 uptime = pref->GetInt64(prefs::kStabilityUptimeSec);
676
677 // Same idea as uptime, except this one never gets reset and is used at
678 // uninstallation.
679 int64 uninstall_metrics_uptime =
680 pref->GetInt64(prefs::kUninstallMetricsUptimeSec);
initial.commit09911bf2008-07-26 23:55:29681
682 if (last_start_time && last_end_time) {
683 // TODO(JAR): Exclude sleep time. ... which must be gathered in UI loop.
[email protected]0bb1a622009-03-04 03:22:32684 int64 uptime_increment = last_end_time - last_start_time;
685 uptime += uptime_increment;
686 pref->SetInt64(prefs::kStabilityUptimeSec, uptime);
687
688 uninstall_metrics_uptime += uptime_increment;
689 pref->SetInt64(prefs::kUninstallMetricsUptimeSec,
690 uninstall_metrics_uptime);
initial.commit09911bf2008-07-26 23:55:29691 }
[email protected]0bb1a622009-03-04 03:22:32692 pref->SetInt64(prefs::kStabilityLaunchTimeSec, Time::Now().ToTimeT());
693
694 // Bookkeeping for the uninstall metrics.
695 IncrementLongPrefsValue(prefs::kUninstallLaunchCount);
initial.commit09911bf2008-07-26 23:55:29696
697 // Save profile metrics.
698 PrefService* prefs = g_browser_process->local_state();
699 if (prefs) {
700 // Remove the current dictionary and store it for use when sending data to
701 // server. By removing the value we prune potentially dead profiles
702 // (and keys). All valid values are added back once services startup.
703 const DictionaryValue* profile_dictionary =
704 prefs->GetDictionary(prefs::kProfileMetrics);
705 if (profile_dictionary) {
706 // Do a deep copy of profile_dictionary since ClearPref will delete it.
707 profile_dictionary_.reset(static_cast<DictionaryValue*>(
708 profile_dictionary->DeepCopy()));
709 prefs->ClearPref(prefs::kProfileMetrics);
710 }
711 }
712
713 // Kick off the process of saving the state (so the uptime numbers keep
714 // getting updated) every n minutes.
715 ScheduleNextStateSave();
716}
717
718void MetricsService::OnGetPluginListTaskComplete() {
719 DCHECK(state_ == PLUGIN_LIST_REQUESTED);
720 if (state_ == PLUGIN_LIST_REQUESTED)
721 state_ = PLUGIN_LIST_ARRIVED;
722}
723
724std::string MetricsService::GenerateClientID() {
[email protected]dc6f4962009-02-13 01:25:50725#if defined(OS_WIN)
initial.commit09911bf2008-07-26 23:55:29726 const int kGUIDSize = 39;
727
728 GUID guid;
729 HRESULT guid_result = CoCreateGuid(&guid);
730 DCHECK(SUCCEEDED(guid_result));
731
732 std::wstring guid_string;
733 int result = StringFromGUID2(guid,
734 WriteInto(&guid_string, kGUIDSize), kGUIDSize);
735 DCHECK(result == kGUIDSize);
736
737 return WideToUTF8(guid_string.substr(1, guid_string.length() - 2));
[email protected]dc6f4962009-02-13 01:25:50738#else
739 // TODO(port): Implement for Mac and linux.
[email protected]f5d0e152009-02-19 21:54:37740 // Rather than actually implementing a random source, might this be a good
741 // time to implement http://code.google.com/p/chromium/issues/detail?id=2278
742 // ? I think so!
[email protected]dc6f4962009-02-13 01:25:50743 NOTIMPLEMENTED();
744 return std::string();
745#endif
initial.commit09911bf2008-07-26 23:55:29746}
747
748
749//------------------------------------------------------------------------------
750// State save methods
751
752void MetricsService::ScheduleNextStateSave() {
753 state_saver_factory_.RevokeAll();
754
755 MessageLoop::current()->PostDelayedTask(FROM_HERE,
756 state_saver_factory_.NewRunnableMethod(&MetricsService::SaveLocalState),
757 kSaveStateInterval * 1000);
758}
759
760void MetricsService::SaveLocalState() {
761 PrefService* pref = g_browser_process->local_state();
762 if (!pref) {
763 NOTREACHED();
764 return;
765 }
766
767 RecordCurrentState(pref);
[email protected]6faa0e0d2009-04-28 06:50:36768 pref->ScheduleSavePersistentPrefs();
initial.commit09911bf2008-07-26 23:55:29769
[email protected]281d2882009-01-20 20:32:42770 // TODO(jar): Does this run down the batteries????
initial.commit09911bf2008-07-26 23:55:29771 ScheduleNextStateSave();
772}
773
774
775//------------------------------------------------------------------------------
776// Recording control methods
777
778void MetricsService::StartRecording() {
779 if (current_log_)
780 return;
781
782 current_log_ = new MetricsLog(client_id_, session_id_);
783 if (state_ == INITIALIZED) {
784 // We only need to schedule that run once.
785 state_ = PLUGIN_LIST_REQUESTED;
786
787 // Make sure the plugin list is loaded before the inital log is sent, so
788 // that the main thread isn't blocked generating the list.
789 g_browser_process->file_thread()->message_loop()->PostDelayedTask(FROM_HERE,
790 new GetPluginListTask(MessageLoop::current()),
[email protected]252873ef2008-08-04 21:59:45791 kInitialInterlogDuration * 1000 / 2);
initial.commit09911bf2008-07-26 23:55:29792 }
793}
794
795void MetricsService::StopRecording(MetricsLog** log) {
796 if (!current_log_)
797 return;
798
[email protected]68475e602008-08-22 03:21:15799 // TODO(jar): Integrate bounds on log recording more consistently, so that we
800 // can stop recording logs that are too big much sooner.
[email protected]d01b8732008-10-16 02:18:07801 if (current_log_->num_events() > log_event_limit_) {
[email protected]553dba62009-02-24 19:08:23802 UMA_HISTOGRAM_COUNTS("UMA.Discarded Log Events",
[email protected]68475e602008-08-22 03:21:15803 current_log_->num_events());
804 current_log_->CloseLog();
805 delete current_log_;
[email protected]294638782008-09-24 00:22:41806 current_log_ = NULL;
[email protected]68475e602008-08-22 03:21:15807 StartRecording(); // Start trivial log to hold our histograms.
808 }
809
[email protected]0b33f80b2008-12-17 21:34:36810 // Put incremental data (histogram deltas, and realtime stats deltas) at the
[email protected]147bbc0b2009-01-06 19:37:40811 // end of all log transmissions (initial log handles this separately).
initial.commit09911bf2008-07-26 23:55:29812 // Don't bother if we're going to discard current_log_.
[email protected]0b33f80b2008-12-17 21:34:36813 if (log) {
[email protected]c96d53092009-02-24 01:25:06814 current_log_->RecordIncrementalStabilityElements();
initial.commit09911bf2008-07-26 23:55:29815 RecordCurrentHistograms();
[email protected]0b33f80b2008-12-17 21:34:36816 }
initial.commit09911bf2008-07-26 23:55:29817
818 current_log_->CloseLog();
[email protected]cac78842008-11-27 01:02:20819 if (log)
initial.commit09911bf2008-07-26 23:55:29820 *log = current_log_;
[email protected]cac78842008-11-27 01:02:20821 else
initial.commit09911bf2008-07-26 23:55:29822 delete current_log_;
initial.commit09911bf2008-07-26 23:55:29823 current_log_ = NULL;
824}
825
initial.commit09911bf2008-07-26 23:55:29826void MetricsService::PushPendingLogsToUnsentLists() {
827 if (state_ < INITIAL_LOG_READY)
[email protected]28ab7f92009-01-06 21:39:04828 return; // We didn't and still don't have time to get plugin list etc.
initial.commit09911bf2008-07-26 23:55:29829
830 if (pending_log()) {
831 PreparePendingLogText();
832 if (state_ == INITIAL_LOG_READY) {
833 // We may race here, and send second copy of initial log later.
834 unsent_initial_logs_.push_back(pending_log_text_);
[email protected]d01b8732008-10-16 02:18:07835 state_ = SEND_OLD_INITIAL_LOGS;
initial.commit09911bf2008-07-26 23:55:29836 } else {
[email protected]281d2882009-01-20 20:32:42837 // TODO(jar): Verify correctness in other states, including sending unsent
[email protected]541f77922009-02-23 21:14:38838 // initial logs.
[email protected]68475e602008-08-22 03:21:15839 PushPendingLogTextToUnsentOngoingLogs();
initial.commit09911bf2008-07-26 23:55:29840 }
841 DiscardPendingLog();
842 }
843 DCHECK(!pending_log());
844 StopRecording(&pending_log_);
845 PreparePendingLogText();
[email protected]68475e602008-08-22 03:21:15846 PushPendingLogTextToUnsentOngoingLogs();
initial.commit09911bf2008-07-26 23:55:29847 DiscardPendingLog();
848 StoreUnsentLogs();
849}
850
[email protected]68475e602008-08-22 03:21:15851void MetricsService::PushPendingLogTextToUnsentOngoingLogs() {
[email protected]d01b8732008-10-16 02:18:07852 // If UMA response told us not to upload, there's no need to save the pending
853 // log. It wasn't supposed to be uploaded anyway.
854 if (!server_permits_upload_)
855 return;
856
[email protected]dc6f4962009-02-13 01:25:50857 if (pending_log_text_.length() >
858 static_cast<size_t>(kUploadLogAvoidRetransmitSize)) {
[email protected]553dba62009-02-24 19:08:23859 UMA_HISTOGRAM_COUNTS("UMA.Large Accumulated Log Not Persisted",
[email protected]68475e602008-08-22 03:21:15860 static_cast<int>(pending_log_text_.length()));
861 return;
862 }
863 unsent_ongoing_logs_.push_back(pending_log_text_);
864}
865
initial.commit09911bf2008-07-26 23:55:29866//------------------------------------------------------------------------------
867// Transmission of logs methods
868
869void MetricsService::StartLogTransmissionTimer() {
[email protected]d01b8732008-10-16 02:18:07870 // If we're not reporting, there's no point in starting a log transmission
871 // timer.
872 if (!reporting_active())
873 return;
874
initial.commit09911bf2008-07-26 23:55:29875 if (!current_log_)
876 return; // Recorder is shutdown.
[email protected]d01b8732008-10-16 02:18:07877
878 // If there is already a timer running, we leave it running.
879 // If timer_pending is true because the fetch is waiting for a response,
880 // we return for now and let the response handler start the timer.
881 if (timer_pending_)
initial.commit09911bf2008-07-26 23:55:29882 return;
[email protected]d01b8732008-10-16 02:18:07883
[email protected]d01b8732008-10-16 02:18:07884 // Before starting the timer, set timer_pending_ to true.
initial.commit09911bf2008-07-26 23:55:29885 timer_pending_ = true;
[email protected]d01b8732008-10-16 02:18:07886
887 // Right before the UMA transmission gets started, there's one more thing we'd
888 // like to record: the histogram of memory usage, so we spawn a task to
[email protected]c9a3ef82009-05-28 22:02:46889 // collect the memory details and when that task is finished, it will call
890 // OnMemoryDetailCollectionDone, which will call HistogramSynchronization to
891 // collect histograms from all renderers and then we will call
892 // OnHistogramSynchronizationDone to continue processing.
initial.commit09911bf2008-07-26 23:55:29893 MessageLoop::current()->PostDelayedTask(FROM_HERE,
894 log_sender_factory_.
[email protected]c9a3ef82009-05-28 22:02:46895 NewRunnableMethod(&MetricsService::LogTransmissionTimerDone),
initial.commit09911bf2008-07-26 23:55:29896 static_cast<int>(interlog_duration_.InMilliseconds()));
897}
898
[email protected]c9a3ef82009-05-28 22:02:46899void MetricsService::LogTransmissionTimerDone() {
900 Task* task = log_sender_factory_.
901 NewRunnableMethod(&MetricsService::OnMemoryDetailCollectionDone);
902
903 MetricsMemoryDetails* details = new MetricsMemoryDetails(task);
904 details->StartFetch();
905
906 // Collect WebCore cache information to put into a histogram.
907 for (RenderProcessHost::iterator it = RenderProcessHost::begin();
908 it != RenderProcessHost::end(); ++it) {
909 it->second->Send(new ViewMsg_GetCacheResourceStats());
910 }
911}
912
913void MetricsService::OnMemoryDetailCollectionDone() {
914 DCHECK(IsSingleThreaded());
915
916 // HistogramSynchronizer will Collect histograms from all renderers and it
917 // will call OnHistogramSynchronizationDone (if wait time elapses before it
918 // heard from all renderers, then also it will call
919 // OnHistogramSynchronizationDone).
920
921 // Create a callback_task for OnHistogramSynchronizationDone.
922 Task* callback_task = log_sender_factory_.NewRunnableMethod(
923 &MetricsService::OnHistogramSynchronizationDone);
924
925 // Set up the callback to task to call after we receive histograms from all
926 // renderer processes. Wait time specifies how long to wait before absolutely
927 // calling us back on the task.
928 HistogramSynchronizer::FetchRendererHistogramsAsynchronously(
929 MessageLoop::current(), callback_task,
930 kMaxHistogramGatheringWaitDuration);
931}
932
933void MetricsService::OnHistogramSynchronizationDone() {
initial.commit09911bf2008-07-26 23:55:29934 DCHECK(IsSingleThreaded());
935
[email protected]d01b8732008-10-16 02:18:07936 // This function should only be called via timer, so timer_pending_
937 // should be true.
938 DCHECK(timer_pending_);
939 timer_pending_ = false;
initial.commit09911bf2008-07-26 23:55:29940
941 DCHECK(!current_fetch_.get());
initial.commit09911bf2008-07-26 23:55:29942
[email protected]d01b8732008-10-16 02:18:07943 // If we're getting no notifications, then the log won't have much in it, and
944 // it's possible the computer is about to go to sleep, so don't upload and
945 // don't restart the transmission timer.
946 if (idle_since_last_transmission_)
947 return;
948
949 // If somehow there is a fetch in progress, we return setting timer_pending_
950 // to true and hope things work out.
951 if (current_fetch_.get()) {
952 timer_pending_ = true;
953 return;
954 }
955
956 // If uploads are forbidden by UMA response, there's no point in keeping
957 // the current_log_, and the more often we delete it, the less likely it is
958 // to expand forever.
959 if (!server_permits_upload_ && current_log_) {
960 StopRecording(NULL);
961 StartRecording();
962 }
initial.commit09911bf2008-07-26 23:55:29963
964 if (!current_log_)
965 return; // Logging was disabled.
[email protected]d01b8732008-10-16 02:18:07966 if (!reporting_active())
initial.commit09911bf2008-07-26 23:55:29967 return; // Don't do work if we're not going to send anything now.
968
[email protected]d01b8732008-10-16 02:18:07969 MakePendingLog();
initial.commit09911bf2008-07-26 23:55:29970
[email protected]d01b8732008-10-16 02:18:07971 // MakePendingLog should have put something in the pending log, if it didn't,
972 // we start the timer again, return and hope things work out.
973 if (!pending_log()) {
974 StartLogTransmissionTimer();
975 return;
976 }
initial.commit09911bf2008-07-26 23:55:29977
[email protected]d01b8732008-10-16 02:18:07978 // If we're not supposed to upload any UMA data because the response or the
979 // user said so, cancel the upload at this point, but start the timer.
980 if (!TransmissionPermitted()) {
981 DiscardPendingLog();
982 StartLogTransmissionTimer();
983 return;
984 }
initial.commit09911bf2008-07-26 23:55:29985
[email protected]d01b8732008-10-16 02:18:07986 PrepareFetchWithPendingLog();
987
988 if (!current_fetch_.get()) {
989 // Compression failed, and log discarded :-/.
990 DiscardPendingLog();
991 StartLogTransmissionTimer(); // Maybe we'll do better next time
992 // TODO(jar): If compression failed, we should have created a tiny log and
993 // compressed that, so that we can signal that we're losing logs.
994 return;
995 }
996
997 DCHECK(!timer_pending_);
998
999 // The URL fetch is a like timer in that after a while we get called back
1000 // so we set timer_pending_ true just as we start the url fetch.
1001 timer_pending_ = true;
1002 current_fetch_->Start();
1003
1004 HandleIdleSinceLastTransmission(true);
1005}
1006
1007
1008void MetricsService::MakePendingLog() {
1009 if (pending_log())
1010 return;
1011
1012 switch (state_) {
1013 case INITIALIZED:
1014 case PLUGIN_LIST_REQUESTED: // We should be further along by now.
1015 DCHECK(false);
1016 return;
1017
1018 case PLUGIN_LIST_ARRIVED:
1019 // We need to wait for the initial log to be ready before sending
1020 // anything, because the server will tell us whether it wants to hear
1021 // from us.
1022 PrepareInitialLog();
1023 DCHECK(state_ == PLUGIN_LIST_ARRIVED);
1024 RecallUnsentLogs();
1025 state_ = INITIAL_LOG_READY;
1026 break;
1027
1028 case SEND_OLD_INITIAL_LOGS:
[email protected]cac78842008-11-27 01:02:201029 if (!unsent_initial_logs_.empty()) {
1030 pending_log_text_ = unsent_initial_logs_.back();
1031 break;
1032 }
[email protected]d01b8732008-10-16 02:18:071033 state_ = SENDING_OLD_LOGS;
1034 // Fall through.
initial.commit09911bf2008-07-26 23:55:291035
[email protected]d01b8732008-10-16 02:18:071036 case SENDING_OLD_LOGS:
1037 if (!unsent_ongoing_logs_.empty()) {
1038 pending_log_text_ = unsent_ongoing_logs_.back();
1039 break;
1040 }
1041 state_ = SENDING_CURRENT_LOGS;
1042 // Fall through.
1043
1044 case SENDING_CURRENT_LOGS:
1045 StopRecording(&pending_log_);
1046 StartRecording();
1047 break;
1048
1049 default:
1050 DCHECK(false);
1051 return;
1052 }
1053
1054 DCHECK(pending_log());
1055}
1056
1057bool MetricsService::TransmissionPermitted() const {
1058 // If the user forbids uploading that's they're business, and we don't upload
1059 // anything. If the server forbids uploading, that's our business, so we take
1060 // that to mean it forbids current logs, but we still send up the inital logs
1061 // and any old logs.
[email protected]d01b8732008-10-16 02:18:071062 if (!user_permits_upload_)
1063 return false;
[email protected]cac78842008-11-27 01:02:201064 if (server_permits_upload_)
[email protected]d01b8732008-10-16 02:18:071065 return true;
initial.commit09911bf2008-07-26 23:55:291066
[email protected]cac78842008-11-27 01:02:201067 switch (state_) {
1068 case INITIAL_LOG_READY:
1069 case SEND_OLD_INITIAL_LOGS:
1070 case SENDING_OLD_LOGS:
1071 return true;
1072
1073 case SENDING_CURRENT_LOGS:
1074 default:
1075 return false;
[email protected]8c8824b2008-09-20 01:55:501076 }
initial.commit09911bf2008-07-26 23:55:291077}
1078
initial.commit09911bf2008-07-26 23:55:291079void MetricsService::PrepareInitialLog() {
1080 DCHECK(state_ == PLUGIN_LIST_ARRIVED);
1081 std::vector<WebPluginInfo> plugins;
1082 PluginService::GetInstance()->GetPlugins(false, &plugins);
1083
1084 MetricsLog* log = new MetricsLog(client_id_, session_id_);
1085 log->RecordEnvironment(plugins, profile_dictionary_.get());
1086
1087 // Histograms only get written to current_log_, so setup for the write.
1088 MetricsLog* save_log = current_log_;
1089 current_log_ = log;
1090 RecordCurrentHistograms(); // Into current_log_... which is really log.
1091 current_log_ = save_log;
1092
1093 log->CloseLog();
1094 DCHECK(!pending_log());
1095 pending_log_ = log;
1096}
1097
1098void MetricsService::RecallUnsentLogs() {
1099 DCHECK(unsent_initial_logs_.empty());
1100 DCHECK(unsent_ongoing_logs_.empty());
1101
1102 PrefService* local_state = g_browser_process->local_state();
1103 DCHECK(local_state);
1104
1105 ListValue* unsent_initial_logs = local_state->GetMutableList(
1106 prefs::kMetricsInitialLogs);
1107 for (ListValue::iterator it = unsent_initial_logs->begin();
1108 it != unsent_initial_logs->end(); ++it) {
[email protected]5e324b72008-12-18 00:07:591109 std::string log;
1110 (*it)->GetAsString(&log);
1111 unsent_initial_logs_.push_back(log);
initial.commit09911bf2008-07-26 23:55:291112 }
1113
1114 ListValue* unsent_ongoing_logs = local_state->GetMutableList(
1115 prefs::kMetricsOngoingLogs);
1116 for (ListValue::iterator it = unsent_ongoing_logs->begin();
1117 it != unsent_ongoing_logs->end(); ++it) {
[email protected]5e324b72008-12-18 00:07:591118 std::string log;
1119 (*it)->GetAsString(&log);
1120 unsent_ongoing_logs_.push_back(log);
initial.commit09911bf2008-07-26 23:55:291121 }
1122}
1123
1124void MetricsService::StoreUnsentLogs() {
1125 if (state_ < INITIAL_LOG_READY)
1126 return; // We never Recalled the prior unsent logs.
1127
1128 PrefService* local_state = g_browser_process->local_state();
1129 DCHECK(local_state);
1130
1131 ListValue* unsent_initial_logs = local_state->GetMutableList(
1132 prefs::kMetricsInitialLogs);
1133 unsent_initial_logs->Clear();
1134 size_t start = 0;
1135 if (unsent_initial_logs_.size() > kMaxInitialLogsPersisted)
1136 start = unsent_initial_logs_.size() - kMaxInitialLogsPersisted;
1137 for (size_t i = start; i < unsent_initial_logs_.size(); ++i)
1138 unsent_initial_logs->Append(
[email protected]5e324b72008-12-18 00:07:591139 Value::CreateStringValue(unsent_initial_logs_[i]));
initial.commit09911bf2008-07-26 23:55:291140
1141 ListValue* unsent_ongoing_logs = local_state->GetMutableList(
1142 prefs::kMetricsOngoingLogs);
1143 unsent_ongoing_logs->Clear();
1144 start = 0;
1145 if (unsent_ongoing_logs_.size() > kMaxOngoingLogsPersisted)
1146 start = unsent_ongoing_logs_.size() - kMaxOngoingLogsPersisted;
1147 for (size_t i = start; i < unsent_ongoing_logs_.size(); ++i)
1148 unsent_ongoing_logs->Append(
[email protected]5e324b72008-12-18 00:07:591149 Value::CreateStringValue(unsent_ongoing_logs_[i]));
initial.commit09911bf2008-07-26 23:55:291150}
1151
1152void MetricsService::PreparePendingLogText() {
1153 DCHECK(pending_log());
1154 if (!pending_log_text_.empty())
1155 return;
1156 int original_size = pending_log_->GetEncodedLogSize();
1157 pending_log_->GetEncodedLog(WriteInto(&pending_log_text_, original_size),
1158 original_size);
1159}
1160
[email protected]d01b8732008-10-16 02:18:071161void MetricsService::PrepareFetchWithPendingLog() {
initial.commit09911bf2008-07-26 23:55:291162 DCHECK(pending_log());
1163 DCHECK(!current_fetch_.get());
1164 PreparePendingLogText();
1165 DCHECK(!pending_log_text_.empty());
1166
1167 // Allow security conscious users to see all metrics logs that we send.
1168 LOG(INFO) << "METRICS LOG: " << pending_log_text_;
1169
1170 std::string compressed_log;
[email protected]cac78842008-11-27 01:02:201171 if (!Bzip2Compress(pending_log_text_, &compressed_log)) {
initial.commit09911bf2008-07-26 23:55:291172 NOTREACHED() << "Failed to compress log for transmission.";
1173 DiscardPendingLog();
1174 StartLogTransmissionTimer(); // Maybe we'll do better on next log :-/.
1175 return;
1176 }
[email protected]cac78842008-11-27 01:02:201177
[email protected]79bf0b72009-04-27 21:30:551178 current_fetch_.reset(new URLFetcher(GURL(WideToUTF16(server_url_)),
1179 URLFetcher::POST,
initial.commit09911bf2008-07-26 23:55:291180 this));
1181 current_fetch_->set_request_context(Profile::GetDefaultRequestContext());
1182 current_fetch_->set_upload_data(kMetricsType, compressed_log);
initial.commit09911bf2008-07-26 23:55:291183}
1184
1185void MetricsService::DiscardPendingLog() {
1186 if (pending_log_) { // Shutdown might have deleted it!
1187 delete pending_log_;
1188 pending_log_ = NULL;
1189 }
1190 pending_log_text_.clear();
1191}
1192
1193// This implementation is based on the Firefox MetricsService implementation.
1194bool MetricsService::Bzip2Compress(const std::string& input,
1195 std::string* output) {
1196 bz_stream stream = {0};
1197 // As long as our input is smaller than the bzip2 block size, we should get
1198 // the best compression. For example, if your input was 250k, using a block
1199 // size of 300k or 500k should result in the same compression ratio. Since
1200 // our data should be under 100k, using the minimum block size of 100k should
1201 // allocate less temporary memory, but result in the same compression ratio.
1202 int result = BZ2_bzCompressInit(&stream,
1203 1, // 100k (min) block size
1204 0, // quiet
1205 0); // default "work factor"
1206 if (result != BZ_OK) { // out of memory?
1207 return false;
1208 }
1209
1210 output->clear();
1211
1212 stream.next_in = const_cast<char*>(input.data());
1213 stream.avail_in = static_cast<int>(input.size());
1214 // NOTE: we don't need a BZ_RUN phase since our input buffer contains
1215 // the entire input
1216 do {
1217 output->resize(output->size() + 1024);
1218 stream.next_out = &((*output)[stream.total_out_lo32]);
1219 stream.avail_out = static_cast<int>(output->size()) - stream.total_out_lo32;
1220 result = BZ2_bzCompress(&stream, BZ_FINISH);
1221 } while (result == BZ_FINISH_OK);
1222 if (result != BZ_STREAM_END) // unknown failure?
1223 return false;
1224 result = BZ2_bzCompressEnd(&stream);
1225 DCHECK(result == BZ_OK);
1226
1227 output->resize(stream.total_out_lo32);
1228
1229 return true;
1230}
1231
1232static const char* StatusToString(const URLRequestStatus& status) {
1233 switch (status.status()) {
1234 case URLRequestStatus::SUCCESS:
1235 return "SUCCESS";
1236
1237 case URLRequestStatus::IO_PENDING:
1238 return "IO_PENDING";
1239
1240 case URLRequestStatus::HANDLED_EXTERNALLY:
1241 return "HANDLED_EXTERNALLY";
1242
1243 case URLRequestStatus::CANCELED:
1244 return "CANCELED";
1245
1246 case URLRequestStatus::FAILED:
1247 return "FAILED";
1248
1249 default:
1250 NOTREACHED();
1251 return "Unknown";
1252 }
1253}
1254
1255void MetricsService::OnURLFetchComplete(const URLFetcher* source,
1256 const GURL& url,
1257 const URLRequestStatus& status,
1258 int response_code,
1259 const ResponseCookies& cookies,
1260 const std::string& data) {
1261 DCHECK(timer_pending_);
1262 timer_pending_ = false;
1263 DCHECK(current_fetch_.get());
1264 current_fetch_.reset(NULL); // We're not allowed to re-use it.
1265
1266 // Confirm send so that we can move on.
[email protected]281d2882009-01-20 20:32:421267 LOG(INFO) << "METRICS RESPONSE CODE: " << response_code << " status=" <<
[email protected]cac78842008-11-27 01:02:201268 StatusToString(status);
[email protected]252873ef2008-08-04 21:59:451269
[email protected]0eb34fee2009-01-21 08:04:381270 // Provide boolean for error recovery (allow us to ignore response_code).
[email protected]dc6f4962009-02-13 01:25:501271 bool discard_log = false;
[email protected]0eb34fee2009-01-21 08:04:381272
[email protected]68475e602008-08-22 03:21:151273 if (response_code != 200 &&
[email protected]dc6f4962009-02-13 01:25:501274 pending_log_text_.length() >
1275 static_cast<size_t>(kUploadLogAvoidRetransmitSize)) {
[email protected]553dba62009-02-24 19:08:231276 UMA_HISTOGRAM_COUNTS("UMA.Large Rejected Log was Discarded",
[email protected]68475e602008-08-22 03:21:151277 static_cast<int>(pending_log_text_.length()));
[email protected]0eb34fee2009-01-21 08:04:381278 discard_log = true;
1279 } else if (response_code == 400) {
1280 // Bad syntax. Retransmission won't work.
[email protected]553dba62009-02-24 19:08:231281 UMA_HISTOGRAM_COUNTS("UMA.Unacceptable_Log_Discarded", state_);
[email protected]0eb34fee2009-01-21 08:04:381282 discard_log = true;
[email protected]68475e602008-08-22 03:21:151283 }
1284
[email protected]0eb34fee2009-01-21 08:04:381285 if (response_code != 200 && !discard_log) {
[email protected]281d2882009-01-20 20:32:421286 LOG(INFO) << "METRICS: transmission attempt returned a failure code: "
1287 << response_code << ". Verify network connectivity";
[email protected]252873ef2008-08-04 21:59:451288 HandleBadResponseCode();
[email protected]0eb34fee2009-01-21 08:04:381289 } else { // Successful receipt (or we are discarding log).
[email protected]281d2882009-01-20 20:32:421290 LOG(INFO) << "METRICS RESPONSE DATA: " << data;
initial.commit09911bf2008-07-26 23:55:291291 switch (state_) {
1292 case INITIAL_LOG_READY:
1293 state_ = SEND_OLD_INITIAL_LOGS;
1294 break;
1295
1296 case SEND_OLD_INITIAL_LOGS:
1297 DCHECK(!unsent_initial_logs_.empty());
1298 unsent_initial_logs_.pop_back();
1299 StoreUnsentLogs();
1300 break;
1301
1302 case SENDING_OLD_LOGS:
1303 DCHECK(!unsent_ongoing_logs_.empty());
1304 unsent_ongoing_logs_.pop_back();
1305 StoreUnsentLogs();
1306 break;
1307
1308 case SENDING_CURRENT_LOGS:
1309 break;
1310
1311 default:
1312 DCHECK(false);
1313 break;
1314 }
[email protected]d01b8732008-10-16 02:18:071315
initial.commit09911bf2008-07-26 23:55:291316 DiscardPendingLog();
[email protected]29be92552008-08-07 22:49:271317 // Since we sent a log, make sure our in-memory state is recorded to disk.
1318 PrefService* local_state = g_browser_process->local_state();
1319 DCHECK(local_state);
1320 if (local_state)
[email protected]6faa0e0d2009-04-28 06:50:361321 local_state->ScheduleSavePersistentPrefs();
[email protected]252873ef2008-08-04 21:59:451322
[email protected]147bbc0b2009-01-06 19:37:401323 // Provide a default (free of exponetial backoff, other varances) in case
1324 // the server does not specify a value.
1325 interlog_duration_ = TimeDelta::FromSeconds(kMinSecondsPerLog);
1326
[email protected]252873ef2008-08-04 21:59:451327 GetSettingsFromResponseData(data);
[email protected]252873ef2008-08-04 21:59:451328 // Override server specified interlog delay if there are unsent logs to
[email protected]29be92552008-08-07 22:49:271329 // transmit.
initial.commit09911bf2008-07-26 23:55:291330 if (unsent_logs()) {
1331 DCHECK(state_ < SENDING_CURRENT_LOGS);
1332 interlog_duration_ = TimeDelta::FromSeconds(kUnsentLogDelay);
initial.commit09911bf2008-07-26 23:55:291333 }
1334 }
[email protected]252873ef2008-08-04 21:59:451335
initial.commit09911bf2008-07-26 23:55:291336 StartLogTransmissionTimer();
1337}
1338
[email protected]252873ef2008-08-04 21:59:451339void MetricsService::HandleBadResponseCode() {
[email protected]281d2882009-01-20 20:32:421340 LOG(INFO) << "Verify your metrics logs are formatted correctly. "
[email protected]79bf0b72009-04-27 21:30:551341 "Verify server is active at " << server_url_;
[email protected]252873ef2008-08-04 21:59:451342 if (!pending_log()) {
[email protected]281d2882009-01-20 20:32:421343 LOG(INFO) << "METRICS: Recorder shutdown during log transmission.";
[email protected]252873ef2008-08-04 21:59:451344 } else {
1345 // Send progressively less frequently.
1346 DCHECK(kBackoff > 1.0);
1347 interlog_duration_ = TimeDelta::FromMicroseconds(
1348 static_cast<int64>(kBackoff * interlog_duration_.InMicroseconds()));
1349
1350 if (kMaxBackoff * TimeDelta::FromSeconds(kMinSecondsPerLog) <
[email protected]cac78842008-11-27 01:02:201351 interlog_duration_) {
[email protected]252873ef2008-08-04 21:59:451352 interlog_duration_ = kMaxBackoff *
1353 TimeDelta::FromSeconds(kMinSecondsPerLog);
[email protected]cac78842008-11-27 01:02:201354 }
[email protected]252873ef2008-08-04 21:59:451355
[email protected]281d2882009-01-20 20:32:421356 LOG(INFO) << "METRICS: transmission retry being scheduled in " <<
[email protected]252873ef2008-08-04 21:59:451357 interlog_duration_.InSeconds() << " seconds for " <<
1358 pending_log_text_;
initial.commit09911bf2008-07-26 23:55:291359 }
initial.commit09911bf2008-07-26 23:55:291360}
1361
[email protected]252873ef2008-08-04 21:59:451362void MetricsService::GetSettingsFromResponseData(const std::string& data) {
1363 // We assume that the file is structured as a block opened by <response>
[email protected]d01b8732008-10-16 02:18:071364 // and that inside response, there is a block opened by tag <chrome_config>
1365 // other tags are ignored for now except the content of <chrome_config>.
[email protected]281d2882009-01-20 20:32:421366 LOG(INFO) << "METRICS: getting settings from response data: " << data;
[email protected]d01b8732008-10-16 02:18:071367
[email protected]252873ef2008-08-04 21:59:451368 int data_size = static_cast<int>(data.size());
1369 if (data_size < 0) {
[email protected]281d2882009-01-20 20:32:421370 LOG(INFO) << "METRICS: server response data bad size: " << data_size <<
[email protected]cac78842008-11-27 01:02:201371 "; aborting extraction of settings";
[email protected]252873ef2008-08-04 21:59:451372 return;
1373 }
[email protected]cac78842008-11-27 01:02:201374 xmlDocPtr doc = xmlReadMemory(data.c_str(), data_size, "", NULL, 0);
[email protected]252873ef2008-08-04 21:59:451375 DCHECK(doc);
[email protected]d01b8732008-10-16 02:18:071376 // If the document is malformed, we just use the settings that were there.
1377 if (!doc) {
[email protected]281d2882009-01-20 20:32:421378 LOG(INFO) << "METRICS: reading xml from server response data failed";
[email protected]252873ef2008-08-04 21:59:451379 return;
[email protected]d01b8732008-10-16 02:18:071380 }
[email protected]252873ef2008-08-04 21:59:451381
[email protected]d01b8732008-10-16 02:18:071382 xmlNodePtr top_node = xmlDocGetRootElement(doc), chrome_config_node = NULL;
1383 // Here, we find the chrome_config node by name.
[email protected]252873ef2008-08-04 21:59:451384 for (xmlNodePtr p = top_node->children; p; p = p->next) {
[email protected]d01b8732008-10-16 02:18:071385 if (xmlStrEqual(p->name, BAD_CAST "chrome_config")) {
1386 chrome_config_node = p;
[email protected]252873ef2008-08-04 21:59:451387 break;
1388 }
1389 }
1390 // If the server data is formatted wrong and there is no
1391 // config node where we expect, we just drop out.
[email protected]d01b8732008-10-16 02:18:071392 if (chrome_config_node != NULL)
1393 GetSettingsFromChromeConfigNode(chrome_config_node);
[email protected]252873ef2008-08-04 21:59:451394 xmlFreeDoc(doc);
1395}
1396
[email protected]d01b8732008-10-16 02:18:071397void MetricsService::GetSettingsFromChromeConfigNode(
1398 xmlNodePtr chrome_config_node) {
1399 // Iterate through all children of the config node.
1400 for (xmlNodePtr current_node = chrome_config_node->children;
1401 current_node;
1402 current_node = current_node->next) {
1403 // If we find the upload tag, we appeal to another function
1404 // GetSettingsFromUploadNode to read all the data in it.
[email protected]252873ef2008-08-04 21:59:451405 if (xmlStrEqual(current_node->name, BAD_CAST "upload")) {
[email protected]d01b8732008-10-16 02:18:071406 GetSettingsFromUploadNode(current_node);
[email protected]252873ef2008-08-04 21:59:451407 continue;
1408 }
1409 }
1410}
initial.commit09911bf2008-07-26 23:55:291411
[email protected]d01b8732008-10-16 02:18:071412void MetricsService::InheritedProperties::OverwriteWhereNeeded(
1413 xmlNodePtr node) {
1414 xmlChar* salt_value = xmlGetProp(node, BAD_CAST "salt");
1415 if (salt_value) // If the property isn't there, xmlGetProp returns NULL.
1416 salt = atoi(reinterpret_cast<char*>(salt_value));
1417 // If the property isn't there, we keep the value the property had before
1418
1419 xmlChar* denominator_value = xmlGetProp(node, BAD_CAST "denominator");
1420 if (denominator_value)
1421 denominator = atoi(reinterpret_cast<char*>(denominator_value));
1422}
1423
1424void MetricsService::GetSettingsFromUploadNode(xmlNodePtr upload_node) {
1425 InheritedProperties props;
1426 GetSettingsFromUploadNodeRecursive(upload_node, props, "", true);
1427}
1428
[email protected]cac78842008-11-27 01:02:201429void MetricsService::GetSettingsFromUploadNodeRecursive(
1430 xmlNodePtr node,
1431 InheritedProperties props,
1432 std::string path_prefix,
1433 bool uploadOn) {
[email protected]d01b8732008-10-16 02:18:071434 props.OverwriteWhereNeeded(node);
1435
1436 // The bool uploadOn is set to true if the data represented by current
1437 // node should be uploaded. This gets inherited in the tree; the children
1438 // of a node that has already been rejected for upload get rejected for
1439 // upload.
1440 uploadOn = uploadOn && NodeProbabilityTest(node, props);
1441
1442 // The path is a / separated list of the node names ancestral to the current
1443 // one. So, if you want to check if the current node has a certain name,
1444 // compare to name. If you want to check if it is a certan tag at a certain
1445 // place in the tree, compare to the whole path.
1446 std::string name = std::string(reinterpret_cast<const char*>(node->name));
1447 std::string path = path_prefix + "/" + name;
1448
1449 if (path == "/upload") {
1450 xmlChar* upload_interval_val = xmlGetProp(node, BAD_CAST "interval");
1451 if (upload_interval_val) {
1452 interlog_duration_ = TimeDelta::FromSeconds(
1453 atoi(reinterpret_cast<char*>(upload_interval_val)));
1454 }
1455
1456 server_permits_upload_ = uploadOn;
1457 }
1458 if (path == "/upload/logs") {
1459 xmlChar* log_event_limit_val = xmlGetProp(node, BAD_CAST "event_limit");
1460 if (log_event_limit_val)
1461 log_event_limit_ = atoi(reinterpret_cast<char*>(log_event_limit_val));
1462 }
1463 if (name == "histogram") {
1464 xmlChar* type_value = xmlGetProp(node, BAD_CAST "type");
1465 if (type_value) {
1466 std::string type = (reinterpret_cast<char*>(type_value));
1467 if (uploadOn)
1468 histograms_to_upload_.insert(type);
1469 else
1470 histograms_to_omit_.insert(type);
1471 }
1472 }
1473 if (name == "log") {
1474 xmlChar* type_value = xmlGetProp(node, BAD_CAST "type");
1475 if (type_value) {
1476 std::string type = (reinterpret_cast<char*>(type_value));
1477 if (uploadOn)
1478 logs_to_upload_.insert(type);
1479 else
1480 logs_to_omit_.insert(type);
1481 }
1482 }
1483
1484 // Recursive call. If the node is a leaf i.e. if it ends in a "/>", then it
1485 // doesn't have children, so node->children is NULL, and this loop doesn't
1486 // call (that's how the recursion ends).
1487 for (xmlNodePtr child_node = node->children;
[email protected]cac78842008-11-27 01:02:201488 child_node;
1489 child_node = child_node->next) {
[email protected]d01b8732008-10-16 02:18:071490 GetSettingsFromUploadNodeRecursive(child_node, props, path, uploadOn);
1491 }
1492}
1493
1494bool MetricsService::NodeProbabilityTest(xmlNodePtr node,
[email protected]cac78842008-11-27 01:02:201495 InheritedProperties props) const {
[email protected]d01b8732008-10-16 02:18:071496 // Default value of probability on any node is 1, but recall that
1497 // its parents can already have been rejected for upload.
1498 double probability = 1;
1499
1500 // If a probability is specified in the node, we use it instead.
1501 xmlChar* probability_value = xmlGetProp(node, BAD_CAST "probability");
1502 if (probability_value)
[email protected]0b33f80b2008-12-17 21:34:361503 probability = atoi(reinterpret_cast<char*>(probability_value));
[email protected]d01b8732008-10-16 02:18:071504
1505 return ProbabilityTest(probability, props.salt, props.denominator);
1506}
1507
1508bool MetricsService::ProbabilityTest(double probability,
1509 int salt,
1510 int denominator) const {
1511 // Okay, first we figure out how many of the digits of the
1512 // client_id_ we need in order to make a nice pseudorandomish
1513 // number in the range [0,denominator). Too many digits is
1514 // fine.
[email protected]d01b8732008-10-16 02:18:071515
1516 // n is the length of the client_id_ string
1517 size_t n = client_id_.size();
1518
1519 // idnumber is a positive integer generated from the client_id_.
1520 // It plus salt is going to give us our pseudorandom number.
1521 int idnumber = 0;
1522 const char* client_id_c_str = client_id_.c_str();
1523
1524 // Here we hash the relevant digits of the client_id_
1525 // string somehow to get a big integer idnumber (could be negative
1526 // from wraparound)
1527 int big = 1;
[email protected]5ed73342009-03-18 17:39:431528 int last_pos = n - 1;
1529 for (size_t j = 0; j < n; ++j) {
1530 idnumber += static_cast<int>(client_id_c_str[last_pos - j]) * big;
[email protected]d01b8732008-10-16 02:18:071531 big *= 10;
1532 }
1533
1534 // Mod id number by denominator making sure to get a non-negative
1535 // answer.
[email protected]cac78842008-11-27 01:02:201536 idnumber = ((idnumber % denominator) + denominator) % denominator;
[email protected]d01b8732008-10-16 02:18:071537
[email protected]cac78842008-11-27 01:02:201538 // ((idnumber + salt) % denominator) / denominator is in the range [0,1]
[email protected]d01b8732008-10-16 02:18:071539 // if it's less than probability we call that an affirmative coin
1540 // toss.
[email protected]cac78842008-11-27 01:02:201541 return static_cast<double>((idnumber + salt) % denominator) <
1542 probability * denominator;
[email protected]d01b8732008-10-16 02:18:071543}
1544
initial.commit09911bf2008-07-26 23:55:291545void MetricsService::LogWindowChange(NotificationType type,
1546 const NotificationSource& source,
1547 const NotificationDetails& details) {
[email protected]534e54b2008-08-13 15:40:091548 int controller_id = -1;
1549 uintptr_t window_or_tab = source.map_key();
initial.commit09911bf2008-07-26 23:55:291550 MetricsLog::WindowEventType window_type;
1551
1552 // Note: since we stop all logging when a single OTR session is active, it is
1553 // possible that we start getting notifications about a window that we don't
1554 // know about.
[email protected]534e54b2008-08-13 15:40:091555 if (window_map_.find(window_or_tab) == window_map_.end()) {
1556 controller_id = next_window_id_++;
1557 window_map_[window_or_tab] = controller_id;
initial.commit09911bf2008-07-26 23:55:291558 } else {
[email protected]534e54b2008-08-13 15:40:091559 controller_id = window_map_[window_or_tab];
initial.commit09911bf2008-07-26 23:55:291560 }
[email protected]534e54b2008-08-13 15:40:091561 DCHECK(controller_id != -1);
initial.commit09911bf2008-07-26 23:55:291562
[email protected]bfd04a62009-02-01 18:16:561563 switch (type.value) {
1564 case NotificationType::TAB_PARENTED:
1565 case NotificationType::BROWSER_OPENED:
initial.commit09911bf2008-07-26 23:55:291566 window_type = MetricsLog::WINDOW_CREATE;
1567 break;
1568
[email protected]bfd04a62009-02-01 18:16:561569 case NotificationType::TAB_CLOSING:
1570 case NotificationType::BROWSER_CLOSED:
[email protected]534e54b2008-08-13 15:40:091571 window_map_.erase(window_map_.find(window_or_tab));
initial.commit09911bf2008-07-26 23:55:291572 window_type = MetricsLog::WINDOW_DESTROY;
1573 break;
1574
1575 default:
1576 NOTREACHED();
[email protected]68d74f02009-02-13 01:36:501577 return;
initial.commit09911bf2008-07-26 23:55:291578 }
1579
[email protected]534e54b2008-08-13 15:40:091580 // TODO(brettw) we should have some kind of ID for the parent.
1581 current_log_->RecordWindowEvent(window_type, controller_id, 0);
initial.commit09911bf2008-07-26 23:55:291582}
1583
1584void MetricsService::LogLoadComplete(NotificationType type,
1585 const NotificationSource& source,
1586 const NotificationDetails& details) {
1587 if (details == NotificationService::NoDetails())
1588 return;
1589
[email protected]68475e602008-08-22 03:21:151590 // TODO(jar): There is a bug causing this to be called too many times, and
1591 // the log overflows. For now, we won't record these events.
[email protected]553dba62009-02-24 19:08:231592 UMA_HISTOGRAM_COUNTS("UMA.LogLoadComplete called", 1);
[email protected]68475e602008-08-22 03:21:151593 return;
1594
initial.commit09911bf2008-07-26 23:55:291595 const Details<LoadNotificationDetails> load_details(details);
[email protected]534e54b2008-08-13 15:40:091596 int controller_id = window_map_[details.map_key()];
1597 current_log_->RecordLoadEvent(controller_id,
initial.commit09911bf2008-07-26 23:55:291598 load_details->url(),
1599 load_details->origin(),
1600 load_details->session_index(),
1601 load_details->load_time());
1602}
1603
[email protected]e73c01972008-08-13 00:18:241604void MetricsService::IncrementPrefValue(const wchar_t* path) {
1605 PrefService* pref = g_browser_process->local_state();
1606 DCHECK(pref);
1607 int value = pref->GetInteger(path);
1608 pref->SetInteger(path, value + 1);
1609}
1610
[email protected]0bb1a622009-03-04 03:22:321611void MetricsService::IncrementLongPrefsValue(const wchar_t* path) {
1612 PrefService* pref = g_browser_process->local_state();
1613 DCHECK(pref);
1614 int64 value = pref->GetInt64(path);
1615 pref->SetInt64(path, value+1);
1616}
1617
initial.commit09911bf2008-07-26 23:55:291618void MetricsService::LogLoadStarted() {
[email protected]e73c01972008-08-13 00:18:241619 IncrementPrefValue(prefs::kStabilityPageLoadCount);
[email protected]0bb1a622009-03-04 03:22:321620 IncrementLongPrefsValue(prefs::kUninstallMetricsPageLoadCount);
[email protected]0b33f80b2008-12-17 21:34:361621 // We need to save the prefs, as page load count is a critical stat, and it
1622 // might be lost due to a crash :-(.
initial.commit09911bf2008-07-26 23:55:291623}
1624
1625void MetricsService::LogRendererInSandbox(bool on_sandbox_desktop) {
1626 PrefService* prefs = g_browser_process->local_state();
1627 DCHECK(prefs);
[email protected]e73c01972008-08-13 00:18:241628 if (on_sandbox_desktop)
1629 IncrementPrefValue(prefs::kSecurityRendererOnSboxDesktop);
1630 else
1631 IncrementPrefValue(prefs::kSecurityRendererOnDefaultDesktop);
initial.commit09911bf2008-07-26 23:55:291632}
1633
1634void MetricsService::LogRendererCrash() {
[email protected]e73c01972008-08-13 00:18:241635 IncrementPrefValue(prefs::kStabilityRendererCrashCount);
initial.commit09911bf2008-07-26 23:55:291636}
1637
1638void MetricsService::LogRendererHang() {
[email protected]e73c01972008-08-13 00:18:241639 IncrementPrefValue(prefs::kStabilityRendererHangCount);
initial.commit09911bf2008-07-26 23:55:291640}
1641
[email protected]a27a9382009-02-11 23:55:101642void MetricsService::LogChildProcessChange(
1643 NotificationType type,
1644 const NotificationSource& source,
1645 const NotificationDetails& details) {
1646 const std::wstring& child_name =
1647 Details<ChildProcessInfo>(details)->name();
initial.commit09911bf2008-07-26 23:55:291648
[email protected]a27a9382009-02-11 23:55:101649 if (child_process_stats_buffer_.find(child_name) ==
1650 child_process_stats_buffer_.end()) {
1651 child_process_stats_buffer_[child_name] = ChildProcessStats();
initial.commit09911bf2008-07-26 23:55:291652 }
1653
[email protected]a27a9382009-02-11 23:55:101654 ChildProcessStats& stats = child_process_stats_buffer_[child_name];
[email protected]bfd04a62009-02-01 18:16:561655 switch (type.value) {
[email protected]a27a9382009-02-11 23:55:101656 case NotificationType::CHILD_PROCESS_HOST_CONNECTED:
initial.commit09911bf2008-07-26 23:55:291657 stats.process_launches++;
1658 break;
1659
[email protected]a27a9382009-02-11 23:55:101660 case NotificationType::CHILD_INSTANCE_CREATED:
initial.commit09911bf2008-07-26 23:55:291661 stats.instances++;
1662 break;
1663
[email protected]a27a9382009-02-11 23:55:101664 case NotificationType::CHILD_PROCESS_CRASHED:
initial.commit09911bf2008-07-26 23:55:291665 stats.process_crashes++;
1666 break;
1667
1668 default:
[email protected]bfd04a62009-02-01 18:16:561669 NOTREACHED() << "Unexpected notification type " << type.value;
initial.commit09911bf2008-07-26 23:55:291670 return;
1671 }
1672}
1673
1674// Recursively counts the number of bookmarks and folders in node.
[email protected]d8e41ed2008-09-11 15:22:321675static void CountBookmarks(BookmarkNode* node, int* bookmarks, int* folders) {
initial.commit09911bf2008-07-26 23:55:291676 if (node->GetType() == history::StarredEntry::URL)
1677 (*bookmarks)++;
1678 else
1679 (*folders)++;
1680 for (int i = 0; i < node->GetChildCount(); ++i)
1681 CountBookmarks(node->GetChild(i), bookmarks, folders);
1682}
1683
[email protected]d8e41ed2008-09-11 15:22:321684void MetricsService::LogBookmarks(BookmarkNode* node,
initial.commit09911bf2008-07-26 23:55:291685 const wchar_t* num_bookmarks_key,
1686 const wchar_t* num_folders_key) {
1687 DCHECK(node);
1688 int num_bookmarks = 0;
1689 int num_folders = 0;
1690 CountBookmarks(node, &num_bookmarks, &num_folders);
1691 num_folders--; // Don't include the root folder in the count.
1692
1693 PrefService* pref = g_browser_process->local_state();
1694 DCHECK(pref);
1695 pref->SetInteger(num_bookmarks_key, num_bookmarks);
1696 pref->SetInteger(num_folders_key, num_folders);
1697}
1698
[email protected]d8e41ed2008-09-11 15:22:321699void MetricsService::LogBookmarks(BookmarkModel* model) {
initial.commit09911bf2008-07-26 23:55:291700 DCHECK(model);
1701 LogBookmarks(model->GetBookmarkBarNode(),
1702 prefs::kNumBookmarksOnBookmarkBar,
1703 prefs::kNumFoldersOnBookmarkBar);
1704 LogBookmarks(model->other_node(),
1705 prefs::kNumBookmarksInOtherBookmarkFolder,
1706 prefs::kNumFoldersInOtherBookmarkFolder);
1707 ScheduleNextStateSave();
1708}
1709
1710void MetricsService::LogKeywords(const TemplateURLModel* url_model) {
1711 DCHECK(url_model);
1712
1713 PrefService* pref = g_browser_process->local_state();
1714 DCHECK(pref);
1715 pref->SetInteger(prefs::kNumKeywords,
1716 static_cast<int>(url_model->GetTemplateURLs().size()));
1717 ScheduleNextStateSave();
1718}
1719
1720void MetricsService::RecordPluginChanges(PrefService* pref) {
1721 ListValue* plugins = pref->GetMutableList(prefs::kStabilityPluginStats);
1722 DCHECK(plugins);
1723
1724 for (ListValue::iterator value_iter = plugins->begin();
1725 value_iter != plugins->end(); ++value_iter) {
1726 if (!(*value_iter)->IsType(Value::TYPE_DICTIONARY)) {
1727 NOTREACHED();
1728 continue;
1729 }
1730
1731 DictionaryValue* plugin_dict = static_cast<DictionaryValue*>(*value_iter);
[email protected]8e50b602009-03-03 22:59:431732 std::wstring plugin_name;
1733 plugin_dict->GetString(prefs::kStabilityPluginName, &plugin_name);
[email protected]6470ee8f2009-03-03 20:46:401734 if (plugin_name.empty()) {
initial.commit09911bf2008-07-26 23:55:291735 NOTREACHED();
1736 continue;
1737 }
1738
[email protected]8e50b602009-03-03 22:59:431739 if (child_process_stats_buffer_.find(plugin_name) ==
[email protected]a27a9382009-02-11 23:55:101740 child_process_stats_buffer_.end())
initial.commit09911bf2008-07-26 23:55:291741 continue;
1742
[email protected]8e50b602009-03-03 22:59:431743 ChildProcessStats stats = child_process_stats_buffer_[plugin_name];
initial.commit09911bf2008-07-26 23:55:291744 if (stats.process_launches) {
1745 int launches = 0;
[email protected]8e50b602009-03-03 22:59:431746 plugin_dict->GetInteger(prefs::kStabilityPluginLaunches, &launches);
initial.commit09911bf2008-07-26 23:55:291747 launches += stats.process_launches;
[email protected]8e50b602009-03-03 22:59:431748 plugin_dict->SetInteger(prefs::kStabilityPluginLaunches, launches);
initial.commit09911bf2008-07-26 23:55:291749 }
1750 if (stats.process_crashes) {
1751 int crashes = 0;
[email protected]8e50b602009-03-03 22:59:431752 plugin_dict->GetInteger(prefs::kStabilityPluginCrashes, &crashes);
initial.commit09911bf2008-07-26 23:55:291753 crashes += stats.process_crashes;
[email protected]8e50b602009-03-03 22:59:431754 plugin_dict->SetInteger(prefs::kStabilityPluginCrashes, crashes);
initial.commit09911bf2008-07-26 23:55:291755 }
1756 if (stats.instances) {
1757 int instances = 0;
[email protected]8e50b602009-03-03 22:59:431758 plugin_dict->GetInteger(prefs::kStabilityPluginInstances, &instances);
initial.commit09911bf2008-07-26 23:55:291759 instances += stats.instances;
[email protected]8e50b602009-03-03 22:59:431760 plugin_dict->SetInteger(prefs::kStabilityPluginInstances, instances);
initial.commit09911bf2008-07-26 23:55:291761 }
1762
[email protected]8e50b602009-03-03 22:59:431763 child_process_stats_buffer_.erase(plugin_name);
initial.commit09911bf2008-07-26 23:55:291764 }
1765
1766 // Now go through and add dictionaries for plugins that didn't already have
1767 // reports in Local State.
[email protected]a27a9382009-02-11 23:55:101768 for (std::map<std::wstring, ChildProcessStats>::iterator cache_iter =
1769 child_process_stats_buffer_.begin();
1770 cache_iter != child_process_stats_buffer_.end(); ++cache_iter) {
1771 std::wstring plugin_name = cache_iter->first;
1772 ChildProcessStats stats = cache_iter->second;
initial.commit09911bf2008-07-26 23:55:291773 DictionaryValue* plugin_dict = new DictionaryValue;
1774
[email protected]8e50b602009-03-03 22:59:431775 plugin_dict->SetString(prefs::kStabilityPluginName, plugin_name);
1776 plugin_dict->SetInteger(prefs::kStabilityPluginLaunches,
initial.commit09911bf2008-07-26 23:55:291777 stats.process_launches);
[email protected]8e50b602009-03-03 22:59:431778 plugin_dict->SetInteger(prefs::kStabilityPluginCrashes,
initial.commit09911bf2008-07-26 23:55:291779 stats.process_crashes);
[email protected]8e50b602009-03-03 22:59:431780 plugin_dict->SetInteger(prefs::kStabilityPluginInstances,
initial.commit09911bf2008-07-26 23:55:291781 stats.instances);
1782 plugins->Append(plugin_dict);
1783 }
[email protected]a27a9382009-02-11 23:55:101784 child_process_stats_buffer_.clear();
initial.commit09911bf2008-07-26 23:55:291785}
1786
1787bool MetricsService::CanLogNotification(NotificationType type,
1788 const NotificationSource& source,
1789 const NotificationDetails& details) {
1790 // We simply don't log anything to UMA if there is a single off the record
1791 // session visible. The problem is that we always notify using the orginal
1792 // profile in order to simplify notification processing.
1793 return !BrowserList::IsOffTheRecordSessionActive();
1794}
1795
1796void MetricsService::RecordBooleanPrefValue(const wchar_t* path, bool value) {
1797 DCHECK(IsSingleThreaded());
1798
1799 PrefService* pref = g_browser_process->local_state();
1800 DCHECK(pref);
1801
1802 pref->SetBoolean(path, value);
1803 RecordCurrentState(pref);
1804}
1805
1806void MetricsService::RecordCurrentState(PrefService* pref) {
[email protected]0bb1a622009-03-04 03:22:321807 pref->SetInt64(prefs::kStabilityLastTimestampSec, Time::Now().ToTimeT());
initial.commit09911bf2008-07-26 23:55:291808
1809 RecordPluginChanges(pref);
1810}
1811
initial.commit09911bf2008-07-26 23:55:291812void MetricsService::RecordCurrentHistograms() {
1813 DCHECK(current_log_);
1814
initial.commit09911bf2008-07-26 23:55:291815 StatisticsRecorder::Histograms histograms;
1816 StatisticsRecorder::GetHistograms(&histograms);
1817 for (StatisticsRecorder::Histograms::iterator it = histograms.begin();
1818 histograms.end() != it;
[email protected]cac78842008-11-27 01:02:201819 ++it) {
initial.commit09911bf2008-07-26 23:55:291820 if ((*it)->flags() & kUmaTargetedHistogramFlag)
[email protected]0b33f80b2008-12-17 21:34:361821 // TODO(petersont): Only record historgrams if they are not precluded by
1822 // the UMA response data.
[email protected]d01b8732008-10-16 02:18:071823 // Bug http://code.google.com/p/chromium/issues/detail?id=2739.
initial.commit09911bf2008-07-26 23:55:291824 RecordHistogram(**it);
1825 }
1826}
1827
1828void MetricsService::RecordHistogram(const Histogram& histogram) {
1829 // Get up-to-date snapshot of sample stats.
1830 Histogram::SampleSet snapshot;
1831 histogram.SnapshotSample(&snapshot);
1832
1833 const std::string& histogram_name = histogram.histogram_name();
1834
1835 // Find the already sent stats, or create an empty set.
1836 LoggedSampleMap::iterator it = logged_samples_.find(histogram_name);
1837 Histogram::SampleSet* already_logged;
1838 if (logged_samples_.end() == it) {
1839 // Add new entry
1840 already_logged = &logged_samples_[histogram.histogram_name()];
1841 already_logged->Resize(histogram); // Complete initialization.
1842 } else {
1843 already_logged = &(it->second);
1844 // Deduct any stats we've already logged from our snapshot.
1845 snapshot.Subtract(*already_logged);
1846 }
1847
1848 // snapshot now contains only a delta to what we've already_logged.
1849
1850 if (snapshot.TotalCount() > 0) {
1851 current_log_->RecordHistogramDelta(histogram, snapshot);
1852 // Add new data into our running total.
1853 already_logged->Add(snapshot);
1854 }
1855}
1856
1857void MetricsService::AddProfileMetric(Profile* profile,
1858 const std::wstring& key,
1859 int value) {
1860 // Restriction of types is needed for writing values. See
1861 // MetricsLog::WriteProfileMetrics.
1862 DCHECK(profile && !key.empty());
1863 PrefService* prefs = g_browser_process->local_state();
1864 DCHECK(prefs);
1865
1866 // Key is stored in prefs, which interpret '.'s as paths. As such, key
1867 // shouldn't have any '.'s in it.
1868 DCHECK(key.find(L'.') == std::wstring::npos);
1869 // The id is most likely an email address. We shouldn't send it to the server.
1870 const std::wstring id_hash =
1871 UTF8ToWide(MetricsLog::CreateBase64Hash(WideToUTF8(profile->GetID())));
1872 DCHECK(id_hash.find('.') == std::string::npos);
1873
1874 DictionaryValue* prof_prefs = prefs->GetMutableDictionary(
1875 prefs::kProfileMetrics);
1876 DCHECK(prof_prefs);
1877 const std::wstring pref_key = std::wstring(prefs::kProfilePrefix) + id_hash +
1878 L"." + key;
[email protected]8e50b602009-03-03 22:59:431879 prof_prefs->SetInteger(pref_key.c_str(), value);
initial.commit09911bf2008-07-26 23:55:291880}
1881
1882static bool IsSingleThreaded() {
[email protected]dc6f4962009-02-13 01:25:501883 static PlatformThreadId thread_id = 0;
initial.commit09911bf2008-07-26 23:55:291884 if (!thread_id)
[email protected]dc6f4962009-02-13 01:25:501885 thread_id = PlatformThread::CurrentId();
1886 return PlatformThread::CurrentId() == thread_id;
initial.commit09911bf2008-07-26 23:55:291887}