blob: 20b7adc82ba3c6f5863849cd5612ba75e035b4d5 [file] [log] [blame]
[email protected]019191a2009-10-02 20:37:271// Copyright (c) 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]7ef52bf2009-08-06 19:04:50165#if defined(USE_SYSTEM_LIBBZ2)
166#include <bzlib.h>
167#else
168#include "third_party/bzip2/bzlib.h"
169#endif
170
[email protected]4d022ff2009-10-23 18:47:09171#include "base/thread.h"
[email protected]d8e41ed2008-09-11 15:22:32172#include "chrome/browser/bookmarks/bookmark_model.h"
initial.commit09911bf2008-07-26 23:55:29173#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"
initial.commit09911bf2008-07-26 23:55:29177#include "chrome/browser/profile.h"
[email protected]8c8657d62009-01-16 18:31:26178#include "chrome/browser/renderer_host/render_process_host.h"
[email protected]d54e03a52009-01-16 00:31:04179#include "chrome/browser/search_engines/template_url_model.h"
[email protected]92745242009-06-12 16:52:21180#include "chrome/common/chrome_switches.h"
[email protected]c9a3ef82009-05-28 22:02:46181#include "chrome/common/histogram_synchronizer.h"
[email protected]bfd04a62009-02-01 18:16:56182#include "chrome/common/notification_service.h"
initial.commit09911bf2008-07-26 23:55:29183#include "chrome/common/pref_names.h"
184#include "chrome/common/pref_service.h"
[email protected]e09ba552009-02-05 03:26:29185#include "chrome/common/render_messages.h"
[email protected]35fa6a22009-08-15 00:04:01186#include "webkit/glue/plugins/plugin_list.h"
initial.commit09911bf2008-07-26 23:55:29187
[email protected]4d022ff2009-10-23 18:47:09188#if !defined(OS_WIN)
189#include "base/rand_util.h"
190#endif
191
[email protected]dc6f4962009-02-13 01:25:50192#if defined(OS_POSIX)
193// TODO(port): Move these headers above as they are ported.
194#include "chrome/common/temp_scaffolding_stubs.h"
195#else
[email protected]79bf0b72009-04-27 21:30:55196#include "chrome/installer/util/browser_distribution.h"
[email protected]dc6f4962009-02-13 01:25:50197#endif
198
[email protected]e1acf6f2008-10-27 20:43:33199using base::Time;
200using base::TimeDelta;
201
initial.commit09911bf2008-07-26 23:55:29202// Check to see that we're being called on only one thread.
203static bool IsSingleThreaded();
204
initial.commit09911bf2008-07-26 23:55:29205static const char kMetricsType[] = "application/vnd.mozilla.metrics.bz2";
206
207// The delay, in seconds, after startup before sending the first log message.
[email protected]252873ef2008-08-04 21:59:45208static const int kInitialInterlogDuration = 60; // one minute
209
[email protected]c9a3ef82009-05-28 22:02:46210// This specifies the amount of time to wait for all renderers to send their
211// data.
212static const int kMaxHistogramGatheringWaitDuration = 60000; // 60 seconds.
213
[email protected]252873ef2008-08-04 21:59:45214// The default maximum number of events in a log uploaded to the UMA server.
[email protected]0b33f80b2008-12-17 21:34:36215static const int kInitialEventLimit = 2400;
[email protected]68475e602008-08-22 03:21:15216
217// If an upload fails, and the transmission was over this byte count, then we
218// will discard the log, and not try to retransmit it. We also don't persist
219// the log to the prefs for transmission during the next chrome session if this
220// limit is exceeded.
221static const int kUploadLogAvoidRetransmitSize = 50000;
initial.commit09911bf2008-07-26 23:55:29222
223// When we have logs from previous Chrome sessions to send, how long should we
224// delay (in seconds) between each log transmission.
225static const int kUnsentLogDelay = 15; // 15 seconds
226
227// Minimum time a log typically exists before sending, in seconds.
228// This number is supplied by the server, but until we parse it out of a server
229// response, we use this duration to specify how long we should wait before
230// sending the next log. If the channel is busy, such as when there is a
231// failure during an attempt to transmit a previous log, then a log may wait
232// (and continue to accrue now log entries) for a much greater period of time.
[email protected]0eb34fee2009-01-21 08:04:38233static const int kMinSecondsPerLog = 20 * 60; // Twenty minutes.
initial.commit09911bf2008-07-26 23:55:29234
initial.commit09911bf2008-07-26 23:55:29235// When we don't succeed at transmitting a log to a server, we progressively
236// wait longer and longer before sending the next log. This backoff process
237// help reduce load on the server, and makes the amount of backoff vary between
238// clients so that a collision (server overload?) on retransmit is less likely.
239// The following is the constant we use to expand that inter-log duration.
240static const double kBackoff = 1.1;
241// We limit the maximum backoff to be no greater than some multiple of the
242// default kMinSecondsPerLog. The following is that maximum ratio.
243static const int kMaxBackoff = 10;
244
245// Interval, in seconds, between state saves.
246static const int kSaveStateInterval = 5 * 60; // five minutes
247
248// The number of "initial" logs we're willing to save, and hope to send during
249// a future Chrome session. Initial logs contain crash stats, and are pretty
250// small.
251static const size_t kMaxInitialLogsPersisted = 20;
252
253// The number of ongoing logs we're willing to save persistently, and hope to
[email protected]281d2882009-01-20 20:32:42254// send during a this or future sessions. Note that each log may be pretty
initial.commit09911bf2008-07-26 23:55:29255// large, as presumably the related "initial" log wasn't sent (probably nothing
256// was, as the user was probably off-line). As a result, the log probably kept
257// accumulating while the "initial" log was stalled (pending_), and couldn't be
258// sent. As a result, we don't want to save too many of these mega-logs.
259// A "standard shutdown" will create a small log, including just the data that
260// was not yet been transmitted, and that is normal (to have exactly one
261// ongoing_log_ at startup).
[email protected]281d2882009-01-20 20:32:42262static const size_t kMaxOngoingLogsPersisted = 8;
initial.commit09911bf2008-07-26 23:55:29263
264
265// Handles asynchronous fetching of memory details.
266// Will run the provided task after finished.
267class MetricsMemoryDetails : public MemoryDetails {
268 public:
269 explicit MetricsMemoryDetails(Task* completion) : completion_(completion) {}
270
271 virtual void OnDetailsAvailable() {
272 MessageLoop::current()->PostTask(FROM_HERE, completion_);
273 }
274
275 private:
276 Task* completion_;
277 DISALLOW_EVIL_CONSTRUCTORS(MetricsMemoryDetails);
278};
279
280class MetricsService::GetPluginListTaskComplete : public Task {
[email protected]35fa6a22009-08-15 00:04:01281 public:
282 explicit GetPluginListTaskComplete(
283 const std::vector<WebPluginInfo>& plugins) : plugins_(plugins) { }
initial.commit09911bf2008-07-26 23:55:29284 virtual void Run() {
[email protected]35fa6a22009-08-15 00:04:01285 g_browser_process->metrics_service()->OnGetPluginListTaskComplete(plugins_);
initial.commit09911bf2008-07-26 23:55:29286 }
[email protected]35fa6a22009-08-15 00:04:01287
288 private:
289 std::vector<WebPluginInfo> plugins_;
initial.commit09911bf2008-07-26 23:55:29290};
291
292class MetricsService::GetPluginListTask : public Task {
293 public:
294 explicit GetPluginListTask(MessageLoop* callback_loop)
295 : callback_loop_(callback_loop) {}
296
297 virtual void Run() {
298 std::vector<WebPluginInfo> plugins;
[email protected]35fa6a22009-08-15 00:04:01299 NPAPI::PluginList::Singleton()->GetPlugins(false, &plugins);
initial.commit09911bf2008-07-26 23:55:29300
[email protected]35fa6a22009-08-15 00:04:01301 callback_loop_->PostTask(
302 FROM_HERE, new GetPluginListTaskComplete(plugins));
initial.commit09911bf2008-07-26 23:55:29303 }
304
305 private:
306 MessageLoop* callback_loop_;
307};
308
309// static
310void MetricsService::RegisterPrefs(PrefService* local_state) {
311 DCHECK(IsSingleThreaded());
312 local_state->RegisterStringPref(prefs::kMetricsClientID, L"");
[email protected]0bb1a622009-03-04 03:22:32313 local_state->RegisterInt64Pref(prefs::kMetricsClientIDTimestamp, 0);
314 local_state->RegisterInt64Pref(prefs::kStabilityLaunchTimeSec, 0);
315 local_state->RegisterInt64Pref(prefs::kStabilityLastTimestampSec, 0);
316 local_state->RegisterInt64Pref(prefs::kStabilityUptimeSec, 0);
[email protected]541f77922009-02-23 21:14:38317 local_state->RegisterStringPref(prefs::kStabilityStatsVersion, L"");
initial.commit09911bf2008-07-26 23:55:29318 local_state->RegisterBooleanPref(prefs::kStabilityExitedCleanly, true);
319 local_state->RegisterBooleanPref(prefs::kStabilitySessionEndCompleted, true);
320 local_state->RegisterIntegerPref(prefs::kMetricsSessionID, -1);
321 local_state->RegisterIntegerPref(prefs::kStabilityLaunchCount, 0);
322 local_state->RegisterIntegerPref(prefs::kStabilityCrashCount, 0);
323 local_state->RegisterIntegerPref(prefs::kStabilityIncompleteSessionEndCount,
324 0);
325 local_state->RegisterIntegerPref(prefs::kStabilityPageLoadCount, 0);
326 local_state->RegisterIntegerPref(prefs::kSecurityRendererOnSboxDesktop, 0);
327 local_state->RegisterIntegerPref(prefs::kSecurityRendererOnDefaultDesktop, 0);
328 local_state->RegisterIntegerPref(prefs::kStabilityRendererCrashCount, 0);
329 local_state->RegisterIntegerPref(prefs::kStabilityRendererHangCount, 0);
[email protected]e73c01972008-08-13 00:18:24330 local_state->RegisterIntegerPref(prefs::kStabilityBreakpadRegistrationFail,
331 0);
332 local_state->RegisterIntegerPref(prefs::kStabilityBreakpadRegistrationSuccess,
333 0);
334 local_state->RegisterIntegerPref(prefs::kStabilityDebuggerPresent, 0);
335 local_state->RegisterIntegerPref(prefs::kStabilityDebuggerNotPresent, 0);
336
initial.commit09911bf2008-07-26 23:55:29337 local_state->RegisterDictionaryPref(prefs::kProfileMetrics);
338 local_state->RegisterIntegerPref(prefs::kNumBookmarksOnBookmarkBar, 0);
339 local_state->RegisterIntegerPref(prefs::kNumFoldersOnBookmarkBar, 0);
340 local_state->RegisterIntegerPref(prefs::kNumBookmarksInOtherBookmarkFolder,
341 0);
342 local_state->RegisterIntegerPref(prefs::kNumFoldersInOtherBookmarkFolder, 0);
343 local_state->RegisterIntegerPref(prefs::kNumKeywords, 0);
344 local_state->RegisterListPref(prefs::kMetricsInitialLogs);
345 local_state->RegisterListPref(prefs::kMetricsOngoingLogs);
[email protected]0bb1a622009-03-04 03:22:32346
347 local_state->RegisterInt64Pref(prefs::kUninstallMetricsPageLoadCount, 0);
348 local_state->RegisterInt64Pref(prefs::kUninstallLaunchCount, 0);
[email protected]6b5f21d2009-04-13 17:01:35349 local_state->RegisterInt64Pref(prefs::kUninstallMetricsInstallDate, 0);
[email protected]0bb1a622009-03-04 03:22:32350 local_state->RegisterInt64Pref(prefs::kUninstallMetricsUptimeSec, 0);
351 local_state->RegisterInt64Pref(prefs::kUninstallLastLaunchTimeSec, 0);
352 local_state->RegisterInt64Pref(prefs::kUninstallLastObservedRunTimeSec, 0);
initial.commit09911bf2008-07-26 23:55:29353}
354
[email protected]541f77922009-02-23 21:14:38355// static
356void MetricsService::DiscardOldStabilityStats(PrefService* local_state) {
357 local_state->SetBoolean(prefs::kStabilityExitedCleanly, true);
[email protected]c9abf242009-07-18 06:00:38358 local_state->SetBoolean(prefs::kStabilitySessionEndCompleted, true);
[email protected]541f77922009-02-23 21:14:38359
360 local_state->SetInteger(prefs::kStabilityIncompleteSessionEndCount, 0);
361 local_state->SetInteger(prefs::kStabilityBreakpadRegistrationSuccess, 0);
362 local_state->SetInteger(prefs::kStabilityBreakpadRegistrationFail, 0);
363 local_state->SetInteger(prefs::kStabilityDebuggerPresent, 0);
364 local_state->SetInteger(prefs::kStabilityDebuggerNotPresent, 0);
365
366 local_state->SetInteger(prefs::kStabilityLaunchCount, 0);
367 local_state->SetInteger(prefs::kStabilityCrashCount, 0);
368
369 local_state->SetInteger(prefs::kStabilityPageLoadCount, 0);
370 local_state->SetInteger(prefs::kStabilityRendererCrashCount, 0);
371 local_state->SetInteger(prefs::kStabilityRendererHangCount, 0);
372
373 local_state->SetInteger(prefs::kSecurityRendererOnSboxDesktop, 0);
374 local_state->SetInteger(prefs::kSecurityRendererOnDefaultDesktop, 0);
375
[email protected]c9abf242009-07-18 06:00:38376 local_state->SetString(prefs::kStabilityLaunchTimeSec, L"0");
377 local_state->SetString(prefs::kStabilityLastTimestampSec, L"0");
[email protected]541f77922009-02-23 21:14:38378 local_state->SetString(prefs::kStabilityUptimeSec, L"0");
379
380 local_state->ClearPref(prefs::kStabilityPluginStats);
[email protected]ae155cb92009-06-19 06:10:37381
382 ListValue* unsent_initial_logs = local_state->GetMutableList(
383 prefs::kMetricsInitialLogs);
384 unsent_initial_logs->Clear();
385
386 ListValue* unsent_ongoing_logs = local_state->GetMutableList(
387 prefs::kMetricsOngoingLogs);
388 unsent_ongoing_logs->Clear();
[email protected]541f77922009-02-23 21:14:38389}
390
initial.commit09911bf2008-07-26 23:55:29391MetricsService::MetricsService()
[email protected]d01b8732008-10-16 02:18:07392 : recording_active_(false),
393 reporting_active_(false),
394 user_permits_upload_(false),
395 server_permits_upload_(true),
396 state_(INITIALIZED),
initial.commit09911bf2008-07-26 23:55:29397 pending_log_(NULL),
[email protected]9ffcccf42009-09-15 22:19:18398 pending_log_text_(),
initial.commit09911bf2008-07-26 23:55:29399 current_fetch_(NULL),
400 current_log_(NULL),
[email protected]d01b8732008-10-16 02:18:07401 idle_since_last_transmission_(false),
initial.commit09911bf2008-07-26 23:55:29402 next_window_id_(0),
[email protected]40bcc302009-03-02 20:50:39403 ALLOW_THIS_IN_INITIALIZER_LIST(log_sender_factory_(this)),
404 ALLOW_THIS_IN_INITIALIZER_LIST(state_saver_factory_(this)),
initial.commit09911bf2008-07-26 23:55:29405 logged_samples_(),
[email protected]252873ef2008-08-04 21:59:45406 interlog_duration_(TimeDelta::FromSeconds(kInitialInterlogDuration)),
[email protected]d01b8732008-10-16 02:18:07407 log_event_limit_(kInitialEventLimit),
initial.commit09911bf2008-07-26 23:55:29408 timer_pending_(false) {
409 DCHECK(IsSingleThreaded());
410 InitializeMetricsState();
411}
412
413MetricsService::~MetricsService() {
414 SetRecording(false);
[email protected]d8bc79bf2009-01-28 01:17:58415 if (pending_log_) {
416 delete pending_log_;
417 pending_log_ = NULL;
418 }
419 if (current_log_) {
420 delete current_log_;
421 current_log_ = NULL;
422 }
initial.commit09911bf2008-07-26 23:55:29423}
424
[email protected]d01b8732008-10-16 02:18:07425void MetricsService::SetUserPermitsUpload(bool enabled) {
426 HandleIdleSinceLastTransmission(false);
427 user_permits_upload_ = enabled;
428}
429
430void MetricsService::Start() {
431 SetRecording(true);
432 SetReporting(true);
433}
434
435void MetricsService::StartRecordingOnly() {
436 SetRecording(true);
437 SetReporting(false);
438}
439
440void MetricsService::Stop() {
441 SetReporting(false);
442 SetRecording(false);
443}
444
initial.commit09911bf2008-07-26 23:55:29445void MetricsService::SetRecording(bool enabled) {
446 DCHECK(IsSingleThreaded());
447
[email protected]d01b8732008-10-16 02:18:07448 if (enabled == recording_active_)
initial.commit09911bf2008-07-26 23:55:29449 return;
450
451 if (enabled) {
[email protected]b0c819f2009-03-08 04:52:15452 if (client_id_.empty()) {
453 PrefService* pref = g_browser_process->local_state();
454 DCHECK(pref);
455 client_id_ = WideToUTF8(pref->GetString(prefs::kMetricsClientID));
456 if (client_id_.empty()) {
457 client_id_ = GenerateClientID();
458 pref->SetString(prefs::kMetricsClientID, UTF8ToWide(client_id_));
459
460 // Might as well make a note of how long this ID has existed
461 pref->SetString(prefs::kMetricsClientIDTimestamp,
462 Int64ToWString(Time::Now().ToTimeT()));
463 }
464 }
initial.commit09911bf2008-07-26 23:55:29465 StartRecording();
[email protected]005ef3e2009-05-22 20:55:46466
467 registrar_.Add(this, NotificationType::BROWSER_OPENED,
468 NotificationService::AllSources());
469 registrar_.Add(this, NotificationType::BROWSER_CLOSED,
470 NotificationService::AllSources());
471 registrar_.Add(this, NotificationType::USER_ACTION,
472 NotificationService::AllSources());
473 registrar_.Add(this, NotificationType::TAB_PARENTED,
474 NotificationService::AllSources());
475 registrar_.Add(this, NotificationType::TAB_CLOSING,
476 NotificationService::AllSources());
477 registrar_.Add(this, NotificationType::LOAD_START,
478 NotificationService::AllSources());
479 registrar_.Add(this, NotificationType::LOAD_STOP,
480 NotificationService::AllSources());
481 registrar_.Add(this, NotificationType::RENDERER_PROCESS_IN_SBOX,
482 NotificationService::AllSources());
483 registrar_.Add(this, NotificationType::RENDERER_PROCESS_CLOSED,
484 NotificationService::AllSources());
485 registrar_.Add(this, NotificationType::RENDERER_PROCESS_HANG,
486 NotificationService::AllSources());
487 registrar_.Add(this, NotificationType::CHILD_PROCESS_HOST_CONNECTED,
488 NotificationService::AllSources());
489 registrar_.Add(this, NotificationType::CHILD_INSTANCE_CREATED,
490 NotificationService::AllSources());
491 registrar_.Add(this, NotificationType::CHILD_PROCESS_CRASHED,
492 NotificationService::AllSources());
493 registrar_.Add(this, NotificationType::TEMPLATE_URL_MODEL_LOADED,
494 NotificationService::AllSources());
495 registrar_.Add(this, NotificationType::OMNIBOX_OPENED_URL,
496 NotificationService::AllSources());
497 registrar_.Add(this, NotificationType::BOOKMARK_MODEL_LOADED,
498 NotificationService::AllSources());
initial.commit09911bf2008-07-26 23:55:29499 } else {
[email protected]005ef3e2009-05-22 20:55:46500 registrar_.RemoveAll();
initial.commit09911bf2008-07-26 23:55:29501 PushPendingLogsToUnsentLists();
502 DCHECK(!pending_log());
503 if (state_ > INITIAL_LOG_READY && unsent_logs())
504 state_ = SEND_OLD_INITIAL_LOGS;
505 }
[email protected]d01b8732008-10-16 02:18:07506 recording_active_ = enabled;
initial.commit09911bf2008-07-26 23:55:29507}
508
[email protected]d01b8732008-10-16 02:18:07509bool MetricsService::recording_active() const {
initial.commit09911bf2008-07-26 23:55:29510 DCHECK(IsSingleThreaded());
[email protected]d01b8732008-10-16 02:18:07511 return recording_active_;
initial.commit09911bf2008-07-26 23:55:29512}
513
[email protected]d01b8732008-10-16 02:18:07514void MetricsService::SetReporting(bool enable) {
515 if (reporting_active_ != enable) {
516 reporting_active_ = enable;
517 if (reporting_active_)
initial.commit09911bf2008-07-26 23:55:29518 StartLogTransmissionTimer();
519 }
[email protected]d01b8732008-10-16 02:18:07520}
521
522bool MetricsService::reporting_active() const {
523 DCHECK(IsSingleThreaded());
524 return reporting_active_;
initial.commit09911bf2008-07-26 23:55:29525}
526
527void MetricsService::Observe(NotificationType type,
528 const NotificationSource& source,
529 const NotificationDetails& details) {
530 DCHECK(current_log_);
531 DCHECK(IsSingleThreaded());
532
533 if (!CanLogNotification(type, source, details))
534 return;
535
[email protected]bfd04a62009-02-01 18:16:56536 switch (type.value) {
537 case NotificationType::USER_ACTION:
initial.commit09911bf2008-07-26 23:55:29538 current_log_->RecordUserAction(*Details<const wchar_t*>(details).ptr());
539 break;
540
[email protected]bfd04a62009-02-01 18:16:56541 case NotificationType::BROWSER_OPENED:
542 case NotificationType::BROWSER_CLOSED:
initial.commit09911bf2008-07-26 23:55:29543 LogWindowChange(type, source, details);
544 break;
545
[email protected]bfd04a62009-02-01 18:16:56546 case NotificationType::TAB_PARENTED:
547 case NotificationType::TAB_CLOSING:
initial.commit09911bf2008-07-26 23:55:29548 LogWindowChange(type, source, details);
549 break;
550
[email protected]bfd04a62009-02-01 18:16:56551 case NotificationType::LOAD_STOP:
initial.commit09911bf2008-07-26 23:55:29552 LogLoadComplete(type, source, details);
553 break;
554
[email protected]bfd04a62009-02-01 18:16:56555 case NotificationType::LOAD_START:
initial.commit09911bf2008-07-26 23:55:29556 LogLoadStarted();
557 break;
558
[email protected]6ba2ec22009-05-05 00:50:53559 case NotificationType::RENDERER_PROCESS_CLOSED:
560 if (*Details<bool>(details).ptr())
561 LogRendererCrash();
initial.commit09911bf2008-07-26 23:55:29562 break;
563
[email protected]bfd04a62009-02-01 18:16:56564 case NotificationType::RENDERER_PROCESS_HANG:
initial.commit09911bf2008-07-26 23:55:29565 LogRendererHang();
566 break;
567
[email protected]bfd04a62009-02-01 18:16:56568 case NotificationType::RENDERER_PROCESS_IN_SBOX:
initial.commit09911bf2008-07-26 23:55:29569 LogRendererInSandbox(*Details<bool>(details).ptr());
570 break;
571
[email protected]a27a9382009-02-11 23:55:10572 case NotificationType::CHILD_PROCESS_HOST_CONNECTED:
573 case NotificationType::CHILD_PROCESS_CRASHED:
574 case NotificationType::CHILD_INSTANCE_CREATED:
575 LogChildProcessChange(type, source, details);
initial.commit09911bf2008-07-26 23:55:29576 break;
577
[email protected]bfd04a62009-02-01 18:16:56578 case NotificationType::TEMPLATE_URL_MODEL_LOADED:
initial.commit09911bf2008-07-26 23:55:29579 LogKeywords(Source<TemplateURLModel>(source).ptr());
580 break;
581
[email protected]bfd04a62009-02-01 18:16:56582 case NotificationType::OMNIBOX_OPENED_URL:
initial.commit09911bf2008-07-26 23:55:29583 current_log_->RecordOmniboxOpenedURL(
584 *Details<AutocompleteLog>(details).ptr());
585 break;
586
[email protected]b61236c62009-04-09 22:43:55587 case NotificationType::BOOKMARK_MODEL_LOADED: {
588 Profile* p = Source<Profile>(source).ptr();
589 if (p)
590 LogBookmarks(p->GetBookmarkModel());
initial.commit09911bf2008-07-26 23:55:29591 break;
[email protected]b61236c62009-04-09 22:43:55592 }
initial.commit09911bf2008-07-26 23:55:29593 default:
594 NOTREACHED();
595 break;
596 }
[email protected]d01b8732008-10-16 02:18:07597
598 HandleIdleSinceLastTransmission(false);
599
600 if (current_log_)
[email protected]281d2882009-01-20 20:32:42601 DLOG(INFO) << "METRICS: NUMBER OF EVENTS = " << current_log_->num_events();
[email protected]d01b8732008-10-16 02:18:07602}
603
604void MetricsService::HandleIdleSinceLastTransmission(bool in_idle) {
605 // If there wasn't a lot of action, maybe the computer was asleep, in which
606 // case, the log transmissions should have stopped. Here we start them up
607 // again.
[email protected]cac78842008-11-27 01:02:20608 if (!in_idle && idle_since_last_transmission_)
609 StartLogTransmissionTimer();
610 idle_since_last_transmission_ = in_idle;
initial.commit09911bf2008-07-26 23:55:29611}
612
613void MetricsService::RecordCleanShutdown() {
614 RecordBooleanPrefValue(prefs::kStabilityExitedCleanly, true);
615}
616
617void MetricsService::RecordStartOfSessionEnd() {
618 RecordBooleanPrefValue(prefs::kStabilitySessionEndCompleted, false);
619}
620
621void MetricsService::RecordCompletedSessionEnd() {
622 RecordBooleanPrefValue(prefs::kStabilitySessionEndCompleted, true);
623}
624
[email protected]e73c01972008-08-13 00:18:24625void MetricsService:: RecordBreakpadRegistration(bool success) {
[email protected]68475e602008-08-22 03:21:15626 if (!success)
[email protected]e73c01972008-08-13 00:18:24627 IncrementPrefValue(prefs::kStabilityBreakpadRegistrationFail);
628 else
629 IncrementPrefValue(prefs::kStabilityBreakpadRegistrationSuccess);
630}
631
632void MetricsService::RecordBreakpadHasDebugger(bool has_debugger) {
633 if (!has_debugger)
634 IncrementPrefValue(prefs::kStabilityDebuggerNotPresent);
635 else
[email protected]68475e602008-08-22 03:21:15636 IncrementPrefValue(prefs::kStabilityDebuggerPresent);
[email protected]e73c01972008-08-13 00:18:24637}
638
initial.commit09911bf2008-07-26 23:55:29639//------------------------------------------------------------------------------
640// private methods
641//------------------------------------------------------------------------------
642
643
644//------------------------------------------------------------------------------
645// Initialization methods
646
647void MetricsService::InitializeMetricsState() {
[email protected]79bf0b72009-04-27 21:30:55648#if defined(OS_POSIX)
649 server_url_ = L"https://clients4.google.com/firefox/metrics/collect";
650#else
651 BrowserDistribution* dist = BrowserDistribution::GetDistribution();
652 server_url_ = dist->GetStatsServerURL();
653#endif
654
initial.commit09911bf2008-07-26 23:55:29655 PrefService* pref = g_browser_process->local_state();
656 DCHECK(pref);
657
[email protected]541f77922009-02-23 21:14:38658 if (WideToUTF8(pref->GetString(prefs::kStabilityStatsVersion)) !=
659 MetricsLog::GetVersionString()) {
660 // This is a new version, so we don't want to confuse the stats about the
661 // old version with info that we upload.
662 DiscardOldStabilityStats(pref);
663 pref->SetString(prefs::kStabilityStatsVersion,
664 UTF8ToWide(MetricsLog::GetVersionString()));
665 }
666
initial.commit09911bf2008-07-26 23:55:29667 // Update session ID
668 session_id_ = pref->GetInteger(prefs::kMetricsSessionID);
669 ++session_id_;
670 pref->SetInteger(prefs::kMetricsSessionID, session_id_);
671
initial.commit09911bf2008-07-26 23:55:29672 // Stability bookkeeping
[email protected]e73c01972008-08-13 00:18:24673 IncrementPrefValue(prefs::kStabilityLaunchCount);
initial.commit09911bf2008-07-26 23:55:29674
[email protected]e73c01972008-08-13 00:18:24675 if (!pref->GetBoolean(prefs::kStabilityExitedCleanly)) {
676 IncrementPrefValue(prefs::kStabilityCrashCount);
initial.commit09911bf2008-07-26 23:55:29677 }
[email protected]e73c01972008-08-13 00:18:24678
679 // This will be set to 'true' if we exit cleanly.
initial.commit09911bf2008-07-26 23:55:29680 pref->SetBoolean(prefs::kStabilityExitedCleanly, false);
681
[email protected]e73c01972008-08-13 00:18:24682 if (!pref->GetBoolean(prefs::kStabilitySessionEndCompleted)) {
683 IncrementPrefValue(prefs::kStabilityIncompleteSessionEndCount);
[email protected]c9abf242009-07-18 06:00:38684 // This is marked false when we get a WM_ENDSESSION.
685 pref->SetBoolean(prefs::kStabilitySessionEndCompleted, true);
initial.commit09911bf2008-07-26 23:55:29686 }
initial.commit09911bf2008-07-26 23:55:29687
[email protected]0bb1a622009-03-04 03:22:32688 int64 last_start_time = pref->GetInt64(prefs::kStabilityLaunchTimeSec);
689 int64 last_end_time = pref->GetInt64(prefs::kStabilityLastTimestampSec);
690 int64 uptime = pref->GetInt64(prefs::kStabilityUptimeSec);
691
692 // Same idea as uptime, except this one never gets reset and is used at
693 // uninstallation.
694 int64 uninstall_metrics_uptime =
695 pref->GetInt64(prefs::kUninstallMetricsUptimeSec);
initial.commit09911bf2008-07-26 23:55:29696
697 if (last_start_time && last_end_time) {
698 // TODO(JAR): Exclude sleep time. ... which must be gathered in UI loop.
[email protected]0bb1a622009-03-04 03:22:32699 int64 uptime_increment = last_end_time - last_start_time;
700 uptime += uptime_increment;
701 pref->SetInt64(prefs::kStabilityUptimeSec, uptime);
702
703 uninstall_metrics_uptime += uptime_increment;
704 pref->SetInt64(prefs::kUninstallMetricsUptimeSec,
705 uninstall_metrics_uptime);
initial.commit09911bf2008-07-26 23:55:29706 }
[email protected]0bb1a622009-03-04 03:22:32707 pref->SetInt64(prefs::kStabilityLaunchTimeSec, Time::Now().ToTimeT());
708
709 // Bookkeeping for the uninstall metrics.
710 IncrementLongPrefsValue(prefs::kUninstallLaunchCount);
initial.commit09911bf2008-07-26 23:55:29711
712 // Save profile metrics.
713 PrefService* prefs = g_browser_process->local_state();
714 if (prefs) {
715 // Remove the current dictionary and store it for use when sending data to
716 // server. By removing the value we prune potentially dead profiles
717 // (and keys). All valid values are added back once services startup.
718 const DictionaryValue* profile_dictionary =
719 prefs->GetDictionary(prefs::kProfileMetrics);
720 if (profile_dictionary) {
721 // Do a deep copy of profile_dictionary since ClearPref will delete it.
722 profile_dictionary_.reset(static_cast<DictionaryValue*>(
723 profile_dictionary->DeepCopy()));
724 prefs->ClearPref(prefs::kProfileMetrics);
725 }
726 }
727
[email protected]92745242009-06-12 16:52:21728 // Get stats on use of command line.
729 const CommandLine* command_line(CommandLine::ForCurrentProcess());
730 size_t common_commands = 0;
731 if (command_line->HasSwitch(switches::kUserDataDir)) {
732 ++common_commands;
733 UMA_HISTOGRAM_COUNTS_100("Chrome.CommandLineDatDirCount", 1);
734 }
735
736 if (command_line->HasSwitch(switches::kApp)) {
737 ++common_commands;
738 UMA_HISTOGRAM_COUNTS_100("Chrome.CommandLineAppModeCount", 1);
739 }
740
741 UMA_HISTOGRAM_COUNTS_100("Chrome.CommandLineFlagCount",
742 command_line->GetSwitchCount());
743 UMA_HISTOGRAM_COUNTS_100("Chrome.CommandLineUncommonFlagCount",
744 command_line->GetSwitchCount() - common_commands);
745
initial.commit09911bf2008-07-26 23:55:29746 // Kick off the process of saving the state (so the uptime numbers keep
747 // getting updated) every n minutes.
748 ScheduleNextStateSave();
749}
750
[email protected]35fa6a22009-08-15 00:04:01751void MetricsService::OnGetPluginListTaskComplete(
752 const std::vector<WebPluginInfo>& plugins) {
initial.commit09911bf2008-07-26 23:55:29753 DCHECK(state_ == PLUGIN_LIST_REQUESTED);
[email protected]35fa6a22009-08-15 00:04:01754 plugins_ = plugins;
initial.commit09911bf2008-07-26 23:55:29755 if (state_ == PLUGIN_LIST_REQUESTED)
756 state_ = PLUGIN_LIST_ARRIVED;
757}
758
759std::string MetricsService::GenerateClientID() {
[email protected]dc6f4962009-02-13 01:25:50760#if defined(OS_WIN)
initial.commit09911bf2008-07-26 23:55:29761 const int kGUIDSize = 39;
762
763 GUID guid;
764 HRESULT guid_result = CoCreateGuid(&guid);
765 DCHECK(SUCCEEDED(guid_result));
766
767 std::wstring guid_string;
768 int result = StringFromGUID2(guid,
769 WriteInto(&guid_string, kGUIDSize), kGUIDSize);
770 DCHECK(result == kGUIDSize);
771
772 return WideToUTF8(guid_string.substr(1, guid_string.length() - 2));
[email protected]271b24f2009-07-28 16:05:51773#else
[email protected]06aaac22009-07-08 20:54:13774 uint64 sixteen_bytes[2] = { base::RandUint64(), base::RandUint64() };
775 return RandomBytesToGUIDString(sixteen_bytes);
[email protected]dc6f4962009-02-13 01:25:50776#endif
initial.commit09911bf2008-07-26 23:55:29777}
778
[email protected]06aaac22009-07-08 20:54:13779#if defined(OS_POSIX)
780// TODO(cmasone): Once we're comfortable this works, migrate Windows code to
781// use this as well.
782std::string MetricsService::RandomBytesToGUIDString(const uint64 bytes[2]) {
783 return StringPrintf("%08llX-%04llX-%04llX-%04llX-%012llX",
784 bytes[0] >> 32,
785 (bytes[0] >> 16) & 0x0000ffff,
786 bytes[0] & 0x0000ffff,
787 bytes[1] >> 48,
788 bytes[1] & 0x0000ffffffffffffULL);
789}
790#endif
initial.commit09911bf2008-07-26 23:55:29791
792//------------------------------------------------------------------------------
793// State save methods
794
795void MetricsService::ScheduleNextStateSave() {
796 state_saver_factory_.RevokeAll();
797
798 MessageLoop::current()->PostDelayedTask(FROM_HERE,
799 state_saver_factory_.NewRunnableMethod(&MetricsService::SaveLocalState),
800 kSaveStateInterval * 1000);
801}
802
803void MetricsService::SaveLocalState() {
804 PrefService* pref = g_browser_process->local_state();
805 if (!pref) {
806 NOTREACHED();
807 return;
808 }
809
810 RecordCurrentState(pref);
[email protected]6faa0e0d2009-04-28 06:50:36811 pref->ScheduleSavePersistentPrefs();
initial.commit09911bf2008-07-26 23:55:29812
[email protected]281d2882009-01-20 20:32:42813 // TODO(jar): Does this run down the batteries????
initial.commit09911bf2008-07-26 23:55:29814 ScheduleNextStateSave();
815}
816
817
818//------------------------------------------------------------------------------
819// Recording control methods
820
821void MetricsService::StartRecording() {
822 if (current_log_)
823 return;
824
825 current_log_ = new MetricsLog(client_id_, session_id_);
826 if (state_ == INITIALIZED) {
827 // We only need to schedule that run once.
828 state_ = PLUGIN_LIST_REQUESTED;
829
830 // Make sure the plugin list is loaded before the inital log is sent, so
831 // that the main thread isn't blocked generating the list.
832 g_browser_process->file_thread()->message_loop()->PostDelayedTask(FROM_HERE,
833 new GetPluginListTask(MessageLoop::current()),
[email protected]252873ef2008-08-04 21:59:45834 kInitialInterlogDuration * 1000 / 2);
initial.commit09911bf2008-07-26 23:55:29835 }
836}
837
838void MetricsService::StopRecording(MetricsLog** log) {
839 if (!current_log_)
840 return;
841
[email protected]68475e602008-08-22 03:21:15842 // TODO(jar): Integrate bounds on log recording more consistently, so that we
843 // can stop recording logs that are too big much sooner.
[email protected]d01b8732008-10-16 02:18:07844 if (current_log_->num_events() > log_event_limit_) {
[email protected]553dba62009-02-24 19:08:23845 UMA_HISTOGRAM_COUNTS("UMA.Discarded Log Events",
[email protected]68475e602008-08-22 03:21:15846 current_log_->num_events());
847 current_log_->CloseLog();
848 delete current_log_;
[email protected]294638782008-09-24 00:22:41849 current_log_ = NULL;
[email protected]68475e602008-08-22 03:21:15850 StartRecording(); // Start trivial log to hold our histograms.
851 }
852
[email protected]0b33f80b2008-12-17 21:34:36853 // Put incremental data (histogram deltas, and realtime stats deltas) at the
[email protected]147bbc0b2009-01-06 19:37:40854 // end of all log transmissions (initial log handles this separately).
initial.commit09911bf2008-07-26 23:55:29855 // Don't bother if we're going to discard current_log_.
[email protected]0b33f80b2008-12-17 21:34:36856 if (log) {
[email protected]c96d53092009-02-24 01:25:06857 current_log_->RecordIncrementalStabilityElements();
initial.commit09911bf2008-07-26 23:55:29858 RecordCurrentHistograms();
[email protected]0b33f80b2008-12-17 21:34:36859 }
initial.commit09911bf2008-07-26 23:55:29860
861 current_log_->CloseLog();
[email protected]cac78842008-11-27 01:02:20862 if (log)
initial.commit09911bf2008-07-26 23:55:29863 *log = current_log_;
[email protected]cac78842008-11-27 01:02:20864 else
initial.commit09911bf2008-07-26 23:55:29865 delete current_log_;
initial.commit09911bf2008-07-26 23:55:29866 current_log_ = NULL;
867}
868
initial.commit09911bf2008-07-26 23:55:29869void MetricsService::PushPendingLogsToUnsentLists() {
870 if (state_ < INITIAL_LOG_READY)
[email protected]28ab7f92009-01-06 21:39:04871 return; // We didn't and still don't have time to get plugin list etc.
initial.commit09911bf2008-07-26 23:55:29872
873 if (pending_log()) {
874 PreparePendingLogText();
875 if (state_ == INITIAL_LOG_READY) {
876 // We may race here, and send second copy of initial log later.
877 unsent_initial_logs_.push_back(pending_log_text_);
[email protected]d01b8732008-10-16 02:18:07878 state_ = SEND_OLD_INITIAL_LOGS;
initial.commit09911bf2008-07-26 23:55:29879 } else {
[email protected]281d2882009-01-20 20:32:42880 // TODO(jar): Verify correctness in other states, including sending unsent
[email protected]541f77922009-02-23 21:14:38881 // initial logs.
[email protected]68475e602008-08-22 03:21:15882 PushPendingLogTextToUnsentOngoingLogs();
initial.commit09911bf2008-07-26 23:55:29883 }
884 DiscardPendingLog();
885 }
886 DCHECK(!pending_log());
887 StopRecording(&pending_log_);
888 PreparePendingLogText();
[email protected]68475e602008-08-22 03:21:15889 PushPendingLogTextToUnsentOngoingLogs();
initial.commit09911bf2008-07-26 23:55:29890 DiscardPendingLog();
891 StoreUnsentLogs();
892}
893
[email protected]68475e602008-08-22 03:21:15894void MetricsService::PushPendingLogTextToUnsentOngoingLogs() {
[email protected]d01b8732008-10-16 02:18:07895 // If UMA response told us not to upload, there's no need to save the pending
896 // log. It wasn't supposed to be uploaded anyway.
897 if (!server_permits_upload_)
898 return;
899
[email protected]dc6f4962009-02-13 01:25:50900 if (pending_log_text_.length() >
901 static_cast<size_t>(kUploadLogAvoidRetransmitSize)) {
[email protected]553dba62009-02-24 19:08:23902 UMA_HISTOGRAM_COUNTS("UMA.Large Accumulated Log Not Persisted",
[email protected]68475e602008-08-22 03:21:15903 static_cast<int>(pending_log_text_.length()));
904 return;
905 }
906 unsent_ongoing_logs_.push_back(pending_log_text_);
907}
908
initial.commit09911bf2008-07-26 23:55:29909//------------------------------------------------------------------------------
910// Transmission of logs methods
911
912void MetricsService::StartLogTransmissionTimer() {
[email protected]d01b8732008-10-16 02:18:07913 // If we're not reporting, there's no point in starting a log transmission
914 // timer.
915 if (!reporting_active())
916 return;
917
initial.commit09911bf2008-07-26 23:55:29918 if (!current_log_)
919 return; // Recorder is shutdown.
[email protected]d01b8732008-10-16 02:18:07920
921 // If there is already a timer running, we leave it running.
922 // If timer_pending is true because the fetch is waiting for a response,
923 // we return for now and let the response handler start the timer.
924 if (timer_pending_)
initial.commit09911bf2008-07-26 23:55:29925 return;
[email protected]d01b8732008-10-16 02:18:07926
[email protected]d01b8732008-10-16 02:18:07927 // Before starting the timer, set timer_pending_ to true.
initial.commit09911bf2008-07-26 23:55:29928 timer_pending_ = true;
[email protected]d01b8732008-10-16 02:18:07929
930 // Right before the UMA transmission gets started, there's one more thing we'd
931 // like to record: the histogram of memory usage, so we spawn a task to
[email protected]c9a3ef82009-05-28 22:02:46932 // collect the memory details and when that task is finished, it will call
933 // OnMemoryDetailCollectionDone, which will call HistogramSynchronization to
934 // collect histograms from all renderers and then we will call
935 // OnHistogramSynchronizationDone to continue processing.
initial.commit09911bf2008-07-26 23:55:29936 MessageLoop::current()->PostDelayedTask(FROM_HERE,
937 log_sender_factory_.
[email protected]c9a3ef82009-05-28 22:02:46938 NewRunnableMethod(&MetricsService::LogTransmissionTimerDone),
[email protected]743ace42009-06-17 17:23:51939 interlog_duration_.InMilliseconds());
initial.commit09911bf2008-07-26 23:55:29940}
941
[email protected]c9a3ef82009-05-28 22:02:46942void MetricsService::LogTransmissionTimerDone() {
943 Task* task = log_sender_factory_.
944 NewRunnableMethod(&MetricsService::OnMemoryDetailCollectionDone);
945
946 MetricsMemoryDetails* details = new MetricsMemoryDetails(task);
947 details->StartFetch();
948
949 // Collect WebCore cache information to put into a histogram.
[email protected]019191a2009-10-02 20:37:27950 for (RenderProcessHost::iterator i(RenderProcessHost::AllHostsIterator());
951 !i.IsAtEnd(); i.Advance())
952 i.GetCurrentValue()->Send(new ViewMsg_GetCacheResourceStats());
[email protected]c9a3ef82009-05-28 22:02:46953}
954
955void MetricsService::OnMemoryDetailCollectionDone() {
956 DCHECK(IsSingleThreaded());
957
958 // HistogramSynchronizer will Collect histograms from all renderers and it
959 // will call OnHistogramSynchronizationDone (if wait time elapses before it
960 // heard from all renderers, then also it will call
961 // OnHistogramSynchronizationDone).
962
963 // Create a callback_task for OnHistogramSynchronizationDone.
964 Task* callback_task = log_sender_factory_.NewRunnableMethod(
965 &MetricsService::OnHistogramSynchronizationDone);
966
967 // Set up the callback to task to call after we receive histograms from all
968 // renderer processes. Wait time specifies how long to wait before absolutely
969 // calling us back on the task.
970 HistogramSynchronizer::FetchRendererHistogramsAsynchronously(
971 MessageLoop::current(), callback_task,
972 kMaxHistogramGatheringWaitDuration);
973}
974
975void MetricsService::OnHistogramSynchronizationDone() {
initial.commit09911bf2008-07-26 23:55:29976 DCHECK(IsSingleThreaded());
977
[email protected]d01b8732008-10-16 02:18:07978 // This function should only be called via timer, so timer_pending_
979 // should be true.
980 DCHECK(timer_pending_);
981 timer_pending_ = false;
initial.commit09911bf2008-07-26 23:55:29982
983 DCHECK(!current_fetch_.get());
initial.commit09911bf2008-07-26 23:55:29984
[email protected]d01b8732008-10-16 02:18:07985 // If we're getting no notifications, then the log won't have much in it, and
986 // it's possible the computer is about to go to sleep, so don't upload and
987 // don't restart the transmission timer.
988 if (idle_since_last_transmission_)
989 return;
990
991 // If somehow there is a fetch in progress, we return setting timer_pending_
992 // to true and hope things work out.
993 if (current_fetch_.get()) {
994 timer_pending_ = true;
995 return;
996 }
997
998 // If uploads are forbidden by UMA response, there's no point in keeping
999 // the current_log_, and the more often we delete it, the less likely it is
1000 // to expand forever.
1001 if (!server_permits_upload_ && current_log_) {
1002 StopRecording(NULL);
1003 StartRecording();
1004 }
initial.commit09911bf2008-07-26 23:55:291005
1006 if (!current_log_)
1007 return; // Logging was disabled.
[email protected]d01b8732008-10-16 02:18:071008 if (!reporting_active())
initial.commit09911bf2008-07-26 23:55:291009 return; // Don't do work if we're not going to send anything now.
1010
[email protected]d01b8732008-10-16 02:18:071011 MakePendingLog();
initial.commit09911bf2008-07-26 23:55:291012
[email protected]d01b8732008-10-16 02:18:071013 // MakePendingLog should have put something in the pending log, if it didn't,
1014 // we start the timer again, return and hope things work out.
1015 if (!pending_log()) {
1016 StartLogTransmissionTimer();
1017 return;
1018 }
initial.commit09911bf2008-07-26 23:55:291019
[email protected]d01b8732008-10-16 02:18:071020 // If we're not supposed to upload any UMA data because the response or the
1021 // user said so, cancel the upload at this point, but start the timer.
1022 if (!TransmissionPermitted()) {
1023 DiscardPendingLog();
1024 StartLogTransmissionTimer();
1025 return;
1026 }
initial.commit09911bf2008-07-26 23:55:291027
[email protected]d01b8732008-10-16 02:18:071028 PrepareFetchWithPendingLog();
1029
1030 if (!current_fetch_.get()) {
1031 // Compression failed, and log discarded :-/.
1032 DiscardPendingLog();
1033 StartLogTransmissionTimer(); // Maybe we'll do better next time
1034 // TODO(jar): If compression failed, we should have created a tiny log and
1035 // compressed that, so that we can signal that we're losing logs.
1036 return;
1037 }
1038
1039 DCHECK(!timer_pending_);
1040
1041 // The URL fetch is a like timer in that after a while we get called back
1042 // so we set timer_pending_ true just as we start the url fetch.
1043 timer_pending_ = true;
1044 current_fetch_->Start();
1045
1046 HandleIdleSinceLastTransmission(true);
1047}
1048
1049
1050void MetricsService::MakePendingLog() {
1051 if (pending_log())
1052 return;
1053
1054 switch (state_) {
1055 case INITIALIZED:
1056 case PLUGIN_LIST_REQUESTED: // We should be further along by now.
1057 DCHECK(false);
1058 return;
1059
1060 case PLUGIN_LIST_ARRIVED:
1061 // We need to wait for the initial log to be ready before sending
1062 // anything, because the server will tell us whether it wants to hear
1063 // from us.
1064 PrepareInitialLog();
1065 DCHECK(state_ == PLUGIN_LIST_ARRIVED);
1066 RecallUnsentLogs();
1067 state_ = INITIAL_LOG_READY;
1068 break;
1069
1070 case SEND_OLD_INITIAL_LOGS:
[email protected]cac78842008-11-27 01:02:201071 if (!unsent_initial_logs_.empty()) {
1072 pending_log_text_ = unsent_initial_logs_.back();
1073 break;
1074 }
[email protected]d01b8732008-10-16 02:18:071075 state_ = SENDING_OLD_LOGS;
1076 // Fall through.
initial.commit09911bf2008-07-26 23:55:291077
[email protected]d01b8732008-10-16 02:18:071078 case SENDING_OLD_LOGS:
1079 if (!unsent_ongoing_logs_.empty()) {
1080 pending_log_text_ = unsent_ongoing_logs_.back();
1081 break;
1082 }
1083 state_ = SENDING_CURRENT_LOGS;
1084 // Fall through.
1085
1086 case SENDING_CURRENT_LOGS:
1087 StopRecording(&pending_log_);
1088 StartRecording();
1089 break;
1090
1091 default:
1092 DCHECK(false);
1093 return;
1094 }
1095
1096 DCHECK(pending_log());
1097}
1098
1099bool MetricsService::TransmissionPermitted() const {
1100 // If the user forbids uploading that's they're business, and we don't upload
1101 // anything. If the server forbids uploading, that's our business, so we take
1102 // that to mean it forbids current logs, but we still send up the inital logs
1103 // and any old logs.
[email protected]d01b8732008-10-16 02:18:071104 if (!user_permits_upload_)
1105 return false;
[email protected]cac78842008-11-27 01:02:201106 if (server_permits_upload_)
[email protected]d01b8732008-10-16 02:18:071107 return true;
initial.commit09911bf2008-07-26 23:55:291108
[email protected]cac78842008-11-27 01:02:201109 switch (state_) {
1110 case INITIAL_LOG_READY:
1111 case SEND_OLD_INITIAL_LOGS:
1112 case SENDING_OLD_LOGS:
1113 return true;
1114
1115 case SENDING_CURRENT_LOGS:
1116 default:
1117 return false;
[email protected]8c8824b2008-09-20 01:55:501118 }
initial.commit09911bf2008-07-26 23:55:291119}
1120
initial.commit09911bf2008-07-26 23:55:291121void MetricsService::PrepareInitialLog() {
1122 DCHECK(state_ == PLUGIN_LIST_ARRIVED);
initial.commit09911bf2008-07-26 23:55:291123
1124 MetricsLog* log = new MetricsLog(client_id_, session_id_);
[email protected]35fa6a22009-08-15 00:04:011125 log->RecordEnvironment(plugins_, profile_dictionary_.get());
initial.commit09911bf2008-07-26 23:55:291126
1127 // Histograms only get written to current_log_, so setup for the write.
1128 MetricsLog* save_log = current_log_;
1129 current_log_ = log;
1130 RecordCurrentHistograms(); // Into current_log_... which is really log.
1131 current_log_ = save_log;
1132
1133 log->CloseLog();
1134 DCHECK(!pending_log());
1135 pending_log_ = log;
1136}
1137
1138void MetricsService::RecallUnsentLogs() {
1139 DCHECK(unsent_initial_logs_.empty());
1140 DCHECK(unsent_ongoing_logs_.empty());
1141
1142 PrefService* local_state = g_browser_process->local_state();
1143 DCHECK(local_state);
1144
1145 ListValue* unsent_initial_logs = local_state->GetMutableList(
1146 prefs::kMetricsInitialLogs);
1147 for (ListValue::iterator it = unsent_initial_logs->begin();
1148 it != unsent_initial_logs->end(); ++it) {
[email protected]5e324b72008-12-18 00:07:591149 std::string log;
1150 (*it)->GetAsString(&log);
1151 unsent_initial_logs_.push_back(log);
initial.commit09911bf2008-07-26 23:55:291152 }
1153
1154 ListValue* unsent_ongoing_logs = local_state->GetMutableList(
1155 prefs::kMetricsOngoingLogs);
1156 for (ListValue::iterator it = unsent_ongoing_logs->begin();
1157 it != unsent_ongoing_logs->end(); ++it) {
[email protected]5e324b72008-12-18 00:07:591158 std::string log;
1159 (*it)->GetAsString(&log);
1160 unsent_ongoing_logs_.push_back(log);
initial.commit09911bf2008-07-26 23:55:291161 }
1162}
1163
1164void MetricsService::StoreUnsentLogs() {
1165 if (state_ < INITIAL_LOG_READY)
1166 return; // We never Recalled the prior unsent logs.
1167
1168 PrefService* local_state = g_browser_process->local_state();
1169 DCHECK(local_state);
1170
1171 ListValue* unsent_initial_logs = local_state->GetMutableList(
1172 prefs::kMetricsInitialLogs);
1173 unsent_initial_logs->Clear();
1174 size_t start = 0;
1175 if (unsent_initial_logs_.size() > kMaxInitialLogsPersisted)
1176 start = unsent_initial_logs_.size() - kMaxInitialLogsPersisted;
1177 for (size_t i = start; i < unsent_initial_logs_.size(); ++i)
1178 unsent_initial_logs->Append(
[email protected]5e324b72008-12-18 00:07:591179 Value::CreateStringValue(unsent_initial_logs_[i]));
initial.commit09911bf2008-07-26 23:55:291180
1181 ListValue* unsent_ongoing_logs = local_state->GetMutableList(
1182 prefs::kMetricsOngoingLogs);
1183 unsent_ongoing_logs->Clear();
1184 start = 0;
1185 if (unsent_ongoing_logs_.size() > kMaxOngoingLogsPersisted)
1186 start = unsent_ongoing_logs_.size() - kMaxOngoingLogsPersisted;
1187 for (size_t i = start; i < unsent_ongoing_logs_.size(); ++i)
1188 unsent_ongoing_logs->Append(
[email protected]5e324b72008-12-18 00:07:591189 Value::CreateStringValue(unsent_ongoing_logs_[i]));
initial.commit09911bf2008-07-26 23:55:291190}
1191
1192void MetricsService::PreparePendingLogText() {
1193 DCHECK(pending_log());
1194 if (!pending_log_text_.empty())
1195 return;
[email protected]9ffcccf42009-09-15 22:19:181196 int text_size = pending_log_->GetEncodedLogSize();
1197
1198 // Leave room for the NUL terminator.
1199 pending_log_->GetEncodedLog(WriteInto(&pending_log_text_, text_size + 1),
1200 text_size);
initial.commit09911bf2008-07-26 23:55:291201}
1202
[email protected]d01b8732008-10-16 02:18:071203void MetricsService::PrepareFetchWithPendingLog() {
initial.commit09911bf2008-07-26 23:55:291204 DCHECK(pending_log());
1205 DCHECK(!current_fetch_.get());
1206 PreparePendingLogText();
1207 DCHECK(!pending_log_text_.empty());
1208
1209 // Allow security conscious users to see all metrics logs that we send.
1210 LOG(INFO) << "METRICS LOG: " << pending_log_text_;
1211
1212 std::string compressed_log;
[email protected]cac78842008-11-27 01:02:201213 if (!Bzip2Compress(pending_log_text_, &compressed_log)) {
initial.commit09911bf2008-07-26 23:55:291214 NOTREACHED() << "Failed to compress log for transmission.";
1215 DiscardPendingLog();
1216 StartLogTransmissionTimer(); // Maybe we'll do better on next log :-/.
1217 return;
1218 }
[email protected]cac78842008-11-27 01:02:201219
[email protected]79bf0b72009-04-27 21:30:551220 current_fetch_.reset(new URLFetcher(GURL(WideToUTF16(server_url_)),
1221 URLFetcher::POST,
initial.commit09911bf2008-07-26 23:55:291222 this));
1223 current_fetch_->set_request_context(Profile::GetDefaultRequestContext());
1224 current_fetch_->set_upload_data(kMetricsType, compressed_log);
initial.commit09911bf2008-07-26 23:55:291225}
1226
1227void MetricsService::DiscardPendingLog() {
1228 if (pending_log_) { // Shutdown might have deleted it!
1229 delete pending_log_;
1230 pending_log_ = NULL;
1231 }
1232 pending_log_text_.clear();
1233}
1234
1235// This implementation is based on the Firefox MetricsService implementation.
1236bool MetricsService::Bzip2Compress(const std::string& input,
1237 std::string* output) {
1238 bz_stream stream = {0};
1239 // As long as our input is smaller than the bzip2 block size, we should get
1240 // the best compression. For example, if your input was 250k, using a block
1241 // size of 300k or 500k should result in the same compression ratio. Since
1242 // our data should be under 100k, using the minimum block size of 100k should
1243 // allocate less temporary memory, but result in the same compression ratio.
1244 int result = BZ2_bzCompressInit(&stream,
1245 1, // 100k (min) block size
1246 0, // quiet
1247 0); // default "work factor"
1248 if (result != BZ_OK) { // out of memory?
1249 return false;
1250 }
1251
1252 output->clear();
1253
1254 stream.next_in = const_cast<char*>(input.data());
1255 stream.avail_in = static_cast<int>(input.size());
1256 // NOTE: we don't need a BZ_RUN phase since our input buffer contains
1257 // the entire input
1258 do {
1259 output->resize(output->size() + 1024);
1260 stream.next_out = &((*output)[stream.total_out_lo32]);
1261 stream.avail_out = static_cast<int>(output->size()) - stream.total_out_lo32;
1262 result = BZ2_bzCompress(&stream, BZ_FINISH);
1263 } while (result == BZ_FINISH_OK);
1264 if (result != BZ_STREAM_END) // unknown failure?
1265 return false;
1266 result = BZ2_bzCompressEnd(&stream);
1267 DCHECK(result == BZ_OK);
1268
1269 output->resize(stream.total_out_lo32);
1270
1271 return true;
1272}
1273
1274static const char* StatusToString(const URLRequestStatus& status) {
1275 switch (status.status()) {
1276 case URLRequestStatus::SUCCESS:
1277 return "SUCCESS";
1278
1279 case URLRequestStatus::IO_PENDING:
1280 return "IO_PENDING";
1281
1282 case URLRequestStatus::HANDLED_EXTERNALLY:
1283 return "HANDLED_EXTERNALLY";
1284
1285 case URLRequestStatus::CANCELED:
1286 return "CANCELED";
1287
1288 case URLRequestStatus::FAILED:
1289 return "FAILED";
1290
1291 default:
1292 NOTREACHED();
1293 return "Unknown";
1294 }
1295}
1296
1297void MetricsService::OnURLFetchComplete(const URLFetcher* source,
1298 const GURL& url,
1299 const URLRequestStatus& status,
1300 int response_code,
1301 const ResponseCookies& cookies,
1302 const std::string& data) {
1303 DCHECK(timer_pending_);
1304 timer_pending_ = false;
1305 DCHECK(current_fetch_.get());
1306 current_fetch_.reset(NULL); // We're not allowed to re-use it.
1307
1308 // Confirm send so that we can move on.
[email protected]281d2882009-01-20 20:32:421309 LOG(INFO) << "METRICS RESPONSE CODE: " << response_code << " status=" <<
[email protected]cac78842008-11-27 01:02:201310 StatusToString(status);
[email protected]252873ef2008-08-04 21:59:451311
[email protected]0eb34fee2009-01-21 08:04:381312 // Provide boolean for error recovery (allow us to ignore response_code).
[email protected]dc6f4962009-02-13 01:25:501313 bool discard_log = false;
[email protected]0eb34fee2009-01-21 08:04:381314
[email protected]68475e602008-08-22 03:21:151315 if (response_code != 200 &&
[email protected]dc6f4962009-02-13 01:25:501316 pending_log_text_.length() >
1317 static_cast<size_t>(kUploadLogAvoidRetransmitSize)) {
[email protected]553dba62009-02-24 19:08:231318 UMA_HISTOGRAM_COUNTS("UMA.Large Rejected Log was Discarded",
[email protected]68475e602008-08-22 03:21:151319 static_cast<int>(pending_log_text_.length()));
[email protected]0eb34fee2009-01-21 08:04:381320 discard_log = true;
1321 } else if (response_code == 400) {
1322 // Bad syntax. Retransmission won't work.
[email protected]553dba62009-02-24 19:08:231323 UMA_HISTOGRAM_COUNTS("UMA.Unacceptable_Log_Discarded", state_);
[email protected]0eb34fee2009-01-21 08:04:381324 discard_log = true;
[email protected]68475e602008-08-22 03:21:151325 }
1326
[email protected]0eb34fee2009-01-21 08:04:381327 if (response_code != 200 && !discard_log) {
[email protected]281d2882009-01-20 20:32:421328 LOG(INFO) << "METRICS: transmission attempt returned a failure code: "
1329 << response_code << ". Verify network connectivity";
[email protected]252873ef2008-08-04 21:59:451330 HandleBadResponseCode();
[email protected]0eb34fee2009-01-21 08:04:381331 } else { // Successful receipt (or we are discarding log).
[email protected]281d2882009-01-20 20:32:421332 LOG(INFO) << "METRICS RESPONSE DATA: " << data;
initial.commit09911bf2008-07-26 23:55:291333 switch (state_) {
1334 case INITIAL_LOG_READY:
1335 state_ = SEND_OLD_INITIAL_LOGS;
1336 break;
1337
1338 case SEND_OLD_INITIAL_LOGS:
1339 DCHECK(!unsent_initial_logs_.empty());
1340 unsent_initial_logs_.pop_back();
1341 StoreUnsentLogs();
1342 break;
1343
1344 case SENDING_OLD_LOGS:
1345 DCHECK(!unsent_ongoing_logs_.empty());
1346 unsent_ongoing_logs_.pop_back();
1347 StoreUnsentLogs();
1348 break;
1349
1350 case SENDING_CURRENT_LOGS:
1351 break;
1352
1353 default:
1354 DCHECK(false);
1355 break;
1356 }
[email protected]d01b8732008-10-16 02:18:071357
initial.commit09911bf2008-07-26 23:55:291358 DiscardPendingLog();
[email protected]29be92552008-08-07 22:49:271359 // Since we sent a log, make sure our in-memory state is recorded to disk.
1360 PrefService* local_state = g_browser_process->local_state();
1361 DCHECK(local_state);
1362 if (local_state)
[email protected]6faa0e0d2009-04-28 06:50:361363 local_state->ScheduleSavePersistentPrefs();
[email protected]252873ef2008-08-04 21:59:451364
[email protected]147bbc0b2009-01-06 19:37:401365 // Provide a default (free of exponetial backoff, other varances) in case
1366 // the server does not specify a value.
1367 interlog_duration_ = TimeDelta::FromSeconds(kMinSecondsPerLog);
1368
[email protected]252873ef2008-08-04 21:59:451369 GetSettingsFromResponseData(data);
[email protected]252873ef2008-08-04 21:59:451370 // Override server specified interlog delay if there are unsent logs to
[email protected]29be92552008-08-07 22:49:271371 // transmit.
initial.commit09911bf2008-07-26 23:55:291372 if (unsent_logs()) {
1373 DCHECK(state_ < SENDING_CURRENT_LOGS);
1374 interlog_duration_ = TimeDelta::FromSeconds(kUnsentLogDelay);
initial.commit09911bf2008-07-26 23:55:291375 }
1376 }
[email protected]252873ef2008-08-04 21:59:451377
initial.commit09911bf2008-07-26 23:55:291378 StartLogTransmissionTimer();
1379}
1380
[email protected]252873ef2008-08-04 21:59:451381void MetricsService::HandleBadResponseCode() {
[email protected]281d2882009-01-20 20:32:421382 LOG(INFO) << "Verify your metrics logs are formatted correctly. "
[email protected]79bf0b72009-04-27 21:30:551383 "Verify server is active at " << server_url_;
[email protected]252873ef2008-08-04 21:59:451384 if (!pending_log()) {
[email protected]281d2882009-01-20 20:32:421385 LOG(INFO) << "METRICS: Recorder shutdown during log transmission.";
[email protected]252873ef2008-08-04 21:59:451386 } else {
1387 // Send progressively less frequently.
1388 DCHECK(kBackoff > 1.0);
1389 interlog_duration_ = TimeDelta::FromMicroseconds(
1390 static_cast<int64>(kBackoff * interlog_duration_.InMicroseconds()));
1391
1392 if (kMaxBackoff * TimeDelta::FromSeconds(kMinSecondsPerLog) <
[email protected]cac78842008-11-27 01:02:201393 interlog_duration_) {
[email protected]252873ef2008-08-04 21:59:451394 interlog_duration_ = kMaxBackoff *
1395 TimeDelta::FromSeconds(kMinSecondsPerLog);
[email protected]cac78842008-11-27 01:02:201396 }
[email protected]252873ef2008-08-04 21:59:451397
[email protected]281d2882009-01-20 20:32:421398 LOG(INFO) << "METRICS: transmission retry being scheduled in " <<
[email protected]252873ef2008-08-04 21:59:451399 interlog_duration_.InSeconds() << " seconds for " <<
1400 pending_log_text_;
initial.commit09911bf2008-07-26 23:55:291401 }
initial.commit09911bf2008-07-26 23:55:291402}
1403
[email protected]252873ef2008-08-04 21:59:451404void MetricsService::GetSettingsFromResponseData(const std::string& data) {
1405 // We assume that the file is structured as a block opened by <response>
[email protected]d01b8732008-10-16 02:18:071406 // and that inside response, there is a block opened by tag <chrome_config>
1407 // other tags are ignored for now except the content of <chrome_config>.
[email protected]281d2882009-01-20 20:32:421408 LOG(INFO) << "METRICS: getting settings from response data: " << data;
[email protected]d01b8732008-10-16 02:18:071409
[email protected]252873ef2008-08-04 21:59:451410 int data_size = static_cast<int>(data.size());
1411 if (data_size < 0) {
[email protected]281d2882009-01-20 20:32:421412 LOG(INFO) << "METRICS: server response data bad size: " << data_size <<
[email protected]cac78842008-11-27 01:02:201413 "; aborting extraction of settings";
[email protected]252873ef2008-08-04 21:59:451414 return;
1415 }
[email protected]cac78842008-11-27 01:02:201416 xmlDocPtr doc = xmlReadMemory(data.c_str(), data_size, "", NULL, 0);
[email protected]252873ef2008-08-04 21:59:451417 DCHECK(doc);
[email protected]d01b8732008-10-16 02:18:071418 // If the document is malformed, we just use the settings that were there.
1419 if (!doc) {
[email protected]281d2882009-01-20 20:32:421420 LOG(INFO) << "METRICS: reading xml from server response data failed";
[email protected]252873ef2008-08-04 21:59:451421 return;
[email protected]d01b8732008-10-16 02:18:071422 }
[email protected]252873ef2008-08-04 21:59:451423
[email protected]d01b8732008-10-16 02:18:071424 xmlNodePtr top_node = xmlDocGetRootElement(doc), chrome_config_node = NULL;
1425 // Here, we find the chrome_config node by name.
[email protected]252873ef2008-08-04 21:59:451426 for (xmlNodePtr p = top_node->children; p; p = p->next) {
[email protected]d01b8732008-10-16 02:18:071427 if (xmlStrEqual(p->name, BAD_CAST "chrome_config")) {
1428 chrome_config_node = p;
[email protected]252873ef2008-08-04 21:59:451429 break;
1430 }
1431 }
1432 // If the server data is formatted wrong and there is no
1433 // config node where we expect, we just drop out.
[email protected]d01b8732008-10-16 02:18:071434 if (chrome_config_node != NULL)
1435 GetSettingsFromChromeConfigNode(chrome_config_node);
[email protected]252873ef2008-08-04 21:59:451436 xmlFreeDoc(doc);
1437}
1438
[email protected]d01b8732008-10-16 02:18:071439void MetricsService::GetSettingsFromChromeConfigNode(
1440 xmlNodePtr chrome_config_node) {
1441 // Iterate through all children of the config node.
1442 for (xmlNodePtr current_node = chrome_config_node->children;
1443 current_node;
1444 current_node = current_node->next) {
1445 // If we find the upload tag, we appeal to another function
1446 // GetSettingsFromUploadNode to read all the data in it.
[email protected]252873ef2008-08-04 21:59:451447 if (xmlStrEqual(current_node->name, BAD_CAST "upload")) {
[email protected]d01b8732008-10-16 02:18:071448 GetSettingsFromUploadNode(current_node);
[email protected]252873ef2008-08-04 21:59:451449 continue;
1450 }
1451 }
1452}
initial.commit09911bf2008-07-26 23:55:291453
[email protected]d01b8732008-10-16 02:18:071454void MetricsService::InheritedProperties::OverwriteWhereNeeded(
1455 xmlNodePtr node) {
1456 xmlChar* salt_value = xmlGetProp(node, BAD_CAST "salt");
1457 if (salt_value) // If the property isn't there, xmlGetProp returns NULL.
1458 salt = atoi(reinterpret_cast<char*>(salt_value));
1459 // If the property isn't there, we keep the value the property had before
1460
1461 xmlChar* denominator_value = xmlGetProp(node, BAD_CAST "denominator");
1462 if (denominator_value)
1463 denominator = atoi(reinterpret_cast<char*>(denominator_value));
1464}
1465
1466void MetricsService::GetSettingsFromUploadNode(xmlNodePtr upload_node) {
1467 InheritedProperties props;
1468 GetSettingsFromUploadNodeRecursive(upload_node, props, "", true);
1469}
1470
[email protected]cac78842008-11-27 01:02:201471void MetricsService::GetSettingsFromUploadNodeRecursive(
1472 xmlNodePtr node,
1473 InheritedProperties props,
1474 std::string path_prefix,
1475 bool uploadOn) {
[email protected]d01b8732008-10-16 02:18:071476 props.OverwriteWhereNeeded(node);
1477
1478 // The bool uploadOn is set to true if the data represented by current
1479 // node should be uploaded. This gets inherited in the tree; the children
1480 // of a node that has already been rejected for upload get rejected for
1481 // upload.
1482 uploadOn = uploadOn && NodeProbabilityTest(node, props);
1483
1484 // The path is a / separated list of the node names ancestral to the current
1485 // one. So, if you want to check if the current node has a certain name,
1486 // compare to name. If you want to check if it is a certan tag at a certain
1487 // place in the tree, compare to the whole path.
1488 std::string name = std::string(reinterpret_cast<const char*>(node->name));
1489 std::string path = path_prefix + "/" + name;
1490
1491 if (path == "/upload") {
1492 xmlChar* upload_interval_val = xmlGetProp(node, BAD_CAST "interval");
1493 if (upload_interval_val) {
1494 interlog_duration_ = TimeDelta::FromSeconds(
1495 atoi(reinterpret_cast<char*>(upload_interval_val)));
1496 }
1497
1498 server_permits_upload_ = uploadOn;
1499 }
1500 if (path == "/upload/logs") {
1501 xmlChar* log_event_limit_val = xmlGetProp(node, BAD_CAST "event_limit");
1502 if (log_event_limit_val)
1503 log_event_limit_ = atoi(reinterpret_cast<char*>(log_event_limit_val));
1504 }
1505 if (name == "histogram") {
1506 xmlChar* type_value = xmlGetProp(node, BAD_CAST "type");
1507 if (type_value) {
1508 std::string type = (reinterpret_cast<char*>(type_value));
1509 if (uploadOn)
1510 histograms_to_upload_.insert(type);
1511 else
1512 histograms_to_omit_.insert(type);
1513 }
1514 }
1515 if (name == "log") {
1516 xmlChar* type_value = xmlGetProp(node, BAD_CAST "type");
1517 if (type_value) {
1518 std::string type = (reinterpret_cast<char*>(type_value));
1519 if (uploadOn)
1520 logs_to_upload_.insert(type);
1521 else
1522 logs_to_omit_.insert(type);
1523 }
1524 }
1525
1526 // Recursive call. If the node is a leaf i.e. if it ends in a "/>", then it
1527 // doesn't have children, so node->children is NULL, and this loop doesn't
1528 // call (that's how the recursion ends).
1529 for (xmlNodePtr child_node = node->children;
[email protected]cac78842008-11-27 01:02:201530 child_node;
1531 child_node = child_node->next) {
[email protected]d01b8732008-10-16 02:18:071532 GetSettingsFromUploadNodeRecursive(child_node, props, path, uploadOn);
1533 }
1534}
1535
1536bool MetricsService::NodeProbabilityTest(xmlNodePtr node,
[email protected]cac78842008-11-27 01:02:201537 InheritedProperties props) const {
[email protected]d01b8732008-10-16 02:18:071538 // Default value of probability on any node is 1, but recall that
1539 // its parents can already have been rejected for upload.
1540 double probability = 1;
1541
1542 // If a probability is specified in the node, we use it instead.
1543 xmlChar* probability_value = xmlGetProp(node, BAD_CAST "probability");
1544 if (probability_value)
[email protected]0b33f80b2008-12-17 21:34:361545 probability = atoi(reinterpret_cast<char*>(probability_value));
[email protected]d01b8732008-10-16 02:18:071546
1547 return ProbabilityTest(probability, props.salt, props.denominator);
1548}
1549
1550bool MetricsService::ProbabilityTest(double probability,
1551 int salt,
1552 int denominator) const {
1553 // Okay, first we figure out how many of the digits of the
1554 // client_id_ we need in order to make a nice pseudorandomish
1555 // number in the range [0,denominator). Too many digits is
1556 // fine.
[email protected]d01b8732008-10-16 02:18:071557
1558 // n is the length of the client_id_ string
1559 size_t n = client_id_.size();
1560
1561 // idnumber is a positive integer generated from the client_id_.
1562 // It plus salt is going to give us our pseudorandom number.
1563 int idnumber = 0;
1564 const char* client_id_c_str = client_id_.c_str();
1565
1566 // Here we hash the relevant digits of the client_id_
1567 // string somehow to get a big integer idnumber (could be negative
1568 // from wraparound)
1569 int big = 1;
[email protected]5ed73342009-03-18 17:39:431570 int last_pos = n - 1;
1571 for (size_t j = 0; j < n; ++j) {
1572 idnumber += static_cast<int>(client_id_c_str[last_pos - j]) * big;
[email protected]d01b8732008-10-16 02:18:071573 big *= 10;
1574 }
1575
1576 // Mod id number by denominator making sure to get a non-negative
1577 // answer.
[email protected]cac78842008-11-27 01:02:201578 idnumber = ((idnumber % denominator) + denominator) % denominator;
[email protected]d01b8732008-10-16 02:18:071579
[email protected]cac78842008-11-27 01:02:201580 // ((idnumber + salt) % denominator) / denominator is in the range [0,1]
[email protected]d01b8732008-10-16 02:18:071581 // if it's less than probability we call that an affirmative coin
1582 // toss.
[email protected]cac78842008-11-27 01:02:201583 return static_cast<double>((idnumber + salt) % denominator) <
1584 probability * denominator;
[email protected]d01b8732008-10-16 02:18:071585}
1586
initial.commit09911bf2008-07-26 23:55:291587void MetricsService::LogWindowChange(NotificationType type,
1588 const NotificationSource& source,
1589 const NotificationDetails& details) {
[email protected]534e54b2008-08-13 15:40:091590 int controller_id = -1;
1591 uintptr_t window_or_tab = source.map_key();
initial.commit09911bf2008-07-26 23:55:291592 MetricsLog::WindowEventType window_type;
1593
1594 // Note: since we stop all logging when a single OTR session is active, it is
1595 // possible that we start getting notifications about a window that we don't
1596 // know about.
[email protected]534e54b2008-08-13 15:40:091597 if (window_map_.find(window_or_tab) == window_map_.end()) {
1598 controller_id = next_window_id_++;
1599 window_map_[window_or_tab] = controller_id;
initial.commit09911bf2008-07-26 23:55:291600 } else {
[email protected]534e54b2008-08-13 15:40:091601 controller_id = window_map_[window_or_tab];
initial.commit09911bf2008-07-26 23:55:291602 }
[email protected]92745242009-06-12 16:52:211603 DCHECK_NE(controller_id, -1);
initial.commit09911bf2008-07-26 23:55:291604
[email protected]bfd04a62009-02-01 18:16:561605 switch (type.value) {
1606 case NotificationType::TAB_PARENTED:
1607 case NotificationType::BROWSER_OPENED:
initial.commit09911bf2008-07-26 23:55:291608 window_type = MetricsLog::WINDOW_CREATE;
1609 break;
1610
[email protected]bfd04a62009-02-01 18:16:561611 case NotificationType::TAB_CLOSING:
1612 case NotificationType::BROWSER_CLOSED:
[email protected]534e54b2008-08-13 15:40:091613 window_map_.erase(window_map_.find(window_or_tab));
initial.commit09911bf2008-07-26 23:55:291614 window_type = MetricsLog::WINDOW_DESTROY;
1615 break;
1616
1617 default:
1618 NOTREACHED();
[email protected]68d74f02009-02-13 01:36:501619 return;
initial.commit09911bf2008-07-26 23:55:291620 }
1621
[email protected]534e54b2008-08-13 15:40:091622 // TODO(brettw) we should have some kind of ID for the parent.
1623 current_log_->RecordWindowEvent(window_type, controller_id, 0);
initial.commit09911bf2008-07-26 23:55:291624}
1625
1626void MetricsService::LogLoadComplete(NotificationType type,
1627 const NotificationSource& source,
1628 const NotificationDetails& details) {
1629 if (details == NotificationService::NoDetails())
1630 return;
1631
[email protected]68475e602008-08-22 03:21:151632 // TODO(jar): There is a bug causing this to be called too many times, and
1633 // the log overflows. For now, we won't record these events.
[email protected]553dba62009-02-24 19:08:231634 UMA_HISTOGRAM_COUNTS("UMA.LogLoadComplete called", 1);
[email protected]68475e602008-08-22 03:21:151635 return;
1636
initial.commit09911bf2008-07-26 23:55:291637 const Details<LoadNotificationDetails> load_details(details);
[email protected]534e54b2008-08-13 15:40:091638 int controller_id = window_map_[details.map_key()];
1639 current_log_->RecordLoadEvent(controller_id,
initial.commit09911bf2008-07-26 23:55:291640 load_details->url(),
1641 load_details->origin(),
1642 load_details->session_index(),
1643 load_details->load_time());
1644}
1645
[email protected]e73c01972008-08-13 00:18:241646void MetricsService::IncrementPrefValue(const wchar_t* path) {
1647 PrefService* pref = g_browser_process->local_state();
1648 DCHECK(pref);
1649 int value = pref->GetInteger(path);
1650 pref->SetInteger(path, value + 1);
1651}
1652
[email protected]0bb1a622009-03-04 03:22:321653void MetricsService::IncrementLongPrefsValue(const wchar_t* path) {
1654 PrefService* pref = g_browser_process->local_state();
1655 DCHECK(pref);
1656 int64 value = pref->GetInt64(path);
1657 pref->SetInt64(path, value+1);
1658}
1659
initial.commit09911bf2008-07-26 23:55:291660void MetricsService::LogLoadStarted() {
[email protected]e73c01972008-08-13 00:18:241661 IncrementPrefValue(prefs::kStabilityPageLoadCount);
[email protected]0bb1a622009-03-04 03:22:321662 IncrementLongPrefsValue(prefs::kUninstallMetricsPageLoadCount);
[email protected]0b33f80b2008-12-17 21:34:361663 // We need to save the prefs, as page load count is a critical stat, and it
1664 // might be lost due to a crash :-(.
initial.commit09911bf2008-07-26 23:55:291665}
1666
1667void MetricsService::LogRendererInSandbox(bool on_sandbox_desktop) {
1668 PrefService* prefs = g_browser_process->local_state();
1669 DCHECK(prefs);
[email protected]e73c01972008-08-13 00:18:241670 if (on_sandbox_desktop)
1671 IncrementPrefValue(prefs::kSecurityRendererOnSboxDesktop);
1672 else
1673 IncrementPrefValue(prefs::kSecurityRendererOnDefaultDesktop);
initial.commit09911bf2008-07-26 23:55:291674}
1675
1676void MetricsService::LogRendererCrash() {
[email protected]e73c01972008-08-13 00:18:241677 IncrementPrefValue(prefs::kStabilityRendererCrashCount);
initial.commit09911bf2008-07-26 23:55:291678}
1679
1680void MetricsService::LogRendererHang() {
[email protected]e73c01972008-08-13 00:18:241681 IncrementPrefValue(prefs::kStabilityRendererHangCount);
initial.commit09911bf2008-07-26 23:55:291682}
1683
[email protected]a27a9382009-02-11 23:55:101684void MetricsService::LogChildProcessChange(
1685 NotificationType type,
1686 const NotificationSource& source,
1687 const NotificationDetails& details) {
[email protected]0d84c5d2009-10-09 01:10:421688 Details<ChildProcessInfo> child_details(details);
1689 const std::wstring& child_name = child_details->name();
1690
initial.commit09911bf2008-07-26 23:55:291691
[email protected]a27a9382009-02-11 23:55:101692 if (child_process_stats_buffer_.find(child_name) ==
1693 child_process_stats_buffer_.end()) {
[email protected]0d84c5d2009-10-09 01:10:421694 child_process_stats_buffer_[child_name] =
1695 ChildProcessStats(child_details->type());
initial.commit09911bf2008-07-26 23:55:291696 }
1697
[email protected]a27a9382009-02-11 23:55:101698 ChildProcessStats& stats = child_process_stats_buffer_[child_name];
[email protected]bfd04a62009-02-01 18:16:561699 switch (type.value) {
[email protected]a27a9382009-02-11 23:55:101700 case NotificationType::CHILD_PROCESS_HOST_CONNECTED:
initial.commit09911bf2008-07-26 23:55:291701 stats.process_launches++;
1702 break;
1703
[email protected]a27a9382009-02-11 23:55:101704 case NotificationType::CHILD_INSTANCE_CREATED:
initial.commit09911bf2008-07-26 23:55:291705 stats.instances++;
1706 break;
1707
[email protected]a27a9382009-02-11 23:55:101708 case NotificationType::CHILD_PROCESS_CRASHED:
initial.commit09911bf2008-07-26 23:55:291709 stats.process_crashes++;
1710 break;
1711
1712 default:
[email protected]bfd04a62009-02-01 18:16:561713 NOTREACHED() << "Unexpected notification type " << type.value;
initial.commit09911bf2008-07-26 23:55:291714 return;
1715 }
1716}
1717
1718// Recursively counts the number of bookmarks and folders in node.
[email protected]b3c33d462009-06-26 22:29:201719static void CountBookmarks(const BookmarkNode* node,
1720 int* bookmarks,
1721 int* folders) {
[email protected]037db002009-10-19 20:06:081722 if (node->type() == BookmarkNode::URL)
initial.commit09911bf2008-07-26 23:55:291723 (*bookmarks)++;
1724 else
1725 (*folders)++;
1726 for (int i = 0; i < node->GetChildCount(); ++i)
1727 CountBookmarks(node->GetChild(i), bookmarks, folders);
1728}
1729
[email protected]b3c33d462009-06-26 22:29:201730void MetricsService::LogBookmarks(const BookmarkNode* node,
initial.commit09911bf2008-07-26 23:55:291731 const wchar_t* num_bookmarks_key,
1732 const wchar_t* num_folders_key) {
1733 DCHECK(node);
1734 int num_bookmarks = 0;
1735 int num_folders = 0;
1736 CountBookmarks(node, &num_bookmarks, &num_folders);
1737 num_folders--; // Don't include the root folder in the count.
1738
1739 PrefService* pref = g_browser_process->local_state();
1740 DCHECK(pref);
1741 pref->SetInteger(num_bookmarks_key, num_bookmarks);
1742 pref->SetInteger(num_folders_key, num_folders);
1743}
1744
[email protected]d8e41ed2008-09-11 15:22:321745void MetricsService::LogBookmarks(BookmarkModel* model) {
initial.commit09911bf2008-07-26 23:55:291746 DCHECK(model);
1747 LogBookmarks(model->GetBookmarkBarNode(),
1748 prefs::kNumBookmarksOnBookmarkBar,
1749 prefs::kNumFoldersOnBookmarkBar);
1750 LogBookmarks(model->other_node(),
1751 prefs::kNumBookmarksInOtherBookmarkFolder,
1752 prefs::kNumFoldersInOtherBookmarkFolder);
1753 ScheduleNextStateSave();
1754}
1755
1756void MetricsService::LogKeywords(const TemplateURLModel* url_model) {
1757 DCHECK(url_model);
1758
1759 PrefService* pref = g_browser_process->local_state();
1760 DCHECK(pref);
1761 pref->SetInteger(prefs::kNumKeywords,
1762 static_cast<int>(url_model->GetTemplateURLs().size()));
1763 ScheduleNextStateSave();
1764}
1765
1766void MetricsService::RecordPluginChanges(PrefService* pref) {
1767 ListValue* plugins = pref->GetMutableList(prefs::kStabilityPluginStats);
1768 DCHECK(plugins);
1769
1770 for (ListValue::iterator value_iter = plugins->begin();
1771 value_iter != plugins->end(); ++value_iter) {
1772 if (!(*value_iter)->IsType(Value::TYPE_DICTIONARY)) {
1773 NOTREACHED();
1774 continue;
1775 }
1776
1777 DictionaryValue* plugin_dict = static_cast<DictionaryValue*>(*value_iter);
[email protected]8e50b602009-03-03 22:59:431778 std::wstring plugin_name;
1779 plugin_dict->GetString(prefs::kStabilityPluginName, &plugin_name);
[email protected]6470ee8f2009-03-03 20:46:401780 if (plugin_name.empty()) {
initial.commit09911bf2008-07-26 23:55:291781 NOTREACHED();
1782 continue;
1783 }
1784
[email protected]8e50b602009-03-03 22:59:431785 if (child_process_stats_buffer_.find(plugin_name) ==
[email protected]a27a9382009-02-11 23:55:101786 child_process_stats_buffer_.end())
initial.commit09911bf2008-07-26 23:55:291787 continue;
1788
[email protected]8e50b602009-03-03 22:59:431789 ChildProcessStats stats = child_process_stats_buffer_[plugin_name];
initial.commit09911bf2008-07-26 23:55:291790 if (stats.process_launches) {
1791 int launches = 0;
[email protected]8e50b602009-03-03 22:59:431792 plugin_dict->GetInteger(prefs::kStabilityPluginLaunches, &launches);
initial.commit09911bf2008-07-26 23:55:291793 launches += stats.process_launches;
[email protected]8e50b602009-03-03 22:59:431794 plugin_dict->SetInteger(prefs::kStabilityPluginLaunches, launches);
initial.commit09911bf2008-07-26 23:55:291795 }
1796 if (stats.process_crashes) {
1797 int crashes = 0;
[email protected]8e50b602009-03-03 22:59:431798 plugin_dict->GetInteger(prefs::kStabilityPluginCrashes, &crashes);
initial.commit09911bf2008-07-26 23:55:291799 crashes += stats.process_crashes;
[email protected]8e50b602009-03-03 22:59:431800 plugin_dict->SetInteger(prefs::kStabilityPluginCrashes, crashes);
initial.commit09911bf2008-07-26 23:55:291801 }
1802 if (stats.instances) {
1803 int instances = 0;
[email protected]8e50b602009-03-03 22:59:431804 plugin_dict->GetInteger(prefs::kStabilityPluginInstances, &instances);
initial.commit09911bf2008-07-26 23:55:291805 instances += stats.instances;
[email protected]8e50b602009-03-03 22:59:431806 plugin_dict->SetInteger(prefs::kStabilityPluginInstances, instances);
initial.commit09911bf2008-07-26 23:55:291807 }
1808
[email protected]8e50b602009-03-03 22:59:431809 child_process_stats_buffer_.erase(plugin_name);
initial.commit09911bf2008-07-26 23:55:291810 }
1811
1812 // Now go through and add dictionaries for plugins that didn't already have
1813 // reports in Local State.
[email protected]a27a9382009-02-11 23:55:101814 for (std::map<std::wstring, ChildProcessStats>::iterator cache_iter =
1815 child_process_stats_buffer_.begin();
1816 cache_iter != child_process_stats_buffer_.end(); ++cache_iter) {
[email protected]a27a9382009-02-11 23:55:101817 ChildProcessStats stats = cache_iter->second;
[email protected]0d84c5d2009-10-09 01:10:421818
1819 // Insert only plugins information into the plugins list.
1820 if (ChildProcessInfo::PLUGIN_PROCESS != stats.process_type)
1821 continue;
1822
1823 std::wstring plugin_name = cache_iter->first;
1824
initial.commit09911bf2008-07-26 23:55:291825 DictionaryValue* plugin_dict = new DictionaryValue;
1826
[email protected]8e50b602009-03-03 22:59:431827 plugin_dict->SetString(prefs::kStabilityPluginName, plugin_name);
1828 plugin_dict->SetInteger(prefs::kStabilityPluginLaunches,
initial.commit09911bf2008-07-26 23:55:291829 stats.process_launches);
[email protected]8e50b602009-03-03 22:59:431830 plugin_dict->SetInteger(prefs::kStabilityPluginCrashes,
initial.commit09911bf2008-07-26 23:55:291831 stats.process_crashes);
[email protected]8e50b602009-03-03 22:59:431832 plugin_dict->SetInteger(prefs::kStabilityPluginInstances,
initial.commit09911bf2008-07-26 23:55:291833 stats.instances);
1834 plugins->Append(plugin_dict);
1835 }
[email protected]a27a9382009-02-11 23:55:101836 child_process_stats_buffer_.clear();
initial.commit09911bf2008-07-26 23:55:291837}
1838
1839bool MetricsService::CanLogNotification(NotificationType type,
1840 const NotificationSource& source,
1841 const NotificationDetails& details) {
1842 // We simply don't log anything to UMA if there is a single off the record
1843 // session visible. The problem is that we always notify using the orginal
1844 // profile in order to simplify notification processing.
1845 return !BrowserList::IsOffTheRecordSessionActive();
1846}
1847
1848void MetricsService::RecordBooleanPrefValue(const wchar_t* path, bool value) {
1849 DCHECK(IsSingleThreaded());
1850
1851 PrefService* pref = g_browser_process->local_state();
1852 DCHECK(pref);
1853
1854 pref->SetBoolean(path, value);
1855 RecordCurrentState(pref);
1856}
1857
1858void MetricsService::RecordCurrentState(PrefService* pref) {
[email protected]0bb1a622009-03-04 03:22:321859 pref->SetInt64(prefs::kStabilityLastTimestampSec, Time::Now().ToTimeT());
initial.commit09911bf2008-07-26 23:55:291860
1861 RecordPluginChanges(pref);
1862}
1863
1864void MetricsService::RecordCurrentHistograms() {
1865 DCHECK(current_log_);
1866
1867 StatisticsRecorder::Histograms histograms;
1868 StatisticsRecorder::GetHistograms(&histograms);
1869 for (StatisticsRecorder::Histograms::iterator it = histograms.begin();
1870 histograms.end() != it;
[email protected]cac78842008-11-27 01:02:201871 ++it) {
initial.commit09911bf2008-07-26 23:55:291872 if ((*it)->flags() & kUmaTargetedHistogramFlag)
[email protected]0b33f80b2008-12-17 21:34:361873 // TODO(petersont): Only record historgrams if they are not precluded by
1874 // the UMA response data.
[email protected]d01b8732008-10-16 02:18:071875 // Bug http://code.google.com/p/chromium/issues/detail?id=2739.
initial.commit09911bf2008-07-26 23:55:291876 RecordHistogram(**it);
1877 }
1878}
1879
1880void MetricsService::RecordHistogram(const Histogram& histogram) {
1881 // Get up-to-date snapshot of sample stats.
1882 Histogram::SampleSet snapshot;
1883 histogram.SnapshotSample(&snapshot);
1884
1885 const std::string& histogram_name = histogram.histogram_name();
1886
1887 // Find the already sent stats, or create an empty set.
1888 LoggedSampleMap::iterator it = logged_samples_.find(histogram_name);
1889 Histogram::SampleSet* already_logged;
1890 if (logged_samples_.end() == it) {
1891 // Add new entry
1892 already_logged = &logged_samples_[histogram.histogram_name()];
1893 already_logged->Resize(histogram); // Complete initialization.
1894 } else {
1895 already_logged = &(it->second);
1896 // Deduct any stats we've already logged from our snapshot.
1897 snapshot.Subtract(*already_logged);
1898 }
1899
1900 // snapshot now contains only a delta to what we've already_logged.
1901
1902 if (snapshot.TotalCount() > 0) {
1903 current_log_->RecordHistogramDelta(histogram, snapshot);
1904 // Add new data into our running total.
1905 already_logged->Add(snapshot);
1906 }
1907}
1908
1909void MetricsService::AddProfileMetric(Profile* profile,
1910 const std::wstring& key,
1911 int value) {
1912 // Restriction of types is needed for writing values. See
1913 // MetricsLog::WriteProfileMetrics.
1914 DCHECK(profile && !key.empty());
1915 PrefService* prefs = g_browser_process->local_state();
1916 DCHECK(prefs);
1917
1918 // Key is stored in prefs, which interpret '.'s as paths. As such, key
1919 // shouldn't have any '.'s in it.
1920 DCHECK(key.find(L'.') == std::wstring::npos);
1921 // The id is most likely an email address. We shouldn't send it to the server.
1922 const std::wstring id_hash =
1923 UTF8ToWide(MetricsLog::CreateBase64Hash(WideToUTF8(profile->GetID())));
1924 DCHECK(id_hash.find('.') == std::string::npos);
1925
1926 DictionaryValue* prof_prefs = prefs->GetMutableDictionary(
1927 prefs::kProfileMetrics);
1928 DCHECK(prof_prefs);
1929 const std::wstring pref_key = std::wstring(prefs::kProfilePrefix) + id_hash +
1930 L"." + key;
[email protected]8e50b602009-03-03 22:59:431931 prof_prefs->SetInteger(pref_key.c_str(), value);
initial.commit09911bf2008-07-26 23:55:291932}
1933
1934static bool IsSingleThreaded() {
[email protected]dc6f4962009-02-13 01:25:501935 static PlatformThreadId thread_id = 0;
initial.commit09911bf2008-07-26 23:55:291936 if (!thread_id)
[email protected]dc6f4962009-02-13 01:25:501937 thread_id = PlatformThread::CurrentId();
1938 return PlatformThread::CurrentId() == thread_id;
initial.commit09911bf2008-07-26 23:55:291939}