blob: 7f654f481f66a06ecda78218251c38a63c916191 [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]690a99c2009-01-06 16:48:45171#include "base/file_path.h"
initial.commit09911bf2008-07-26 23:55:29172#include "base/histogram.h"
173#include "base/path_service.h"
[email protected]dc6f4962009-02-13 01:25:50174#include "base/platform_thread.h"
[email protected]06aaac22009-07-08 20:54:13175#include "base/rand_util.h"
initial.commit09911bf2008-07-26 23:55:29176#include "base/string_util.h"
177#include "base/task.h"
[email protected]d8e41ed2008-09-11 15:22:32178#include "chrome/browser/bookmarks/bookmark_model.h"
initial.commit09911bf2008-07-26 23:55:29179#include "chrome/browser/browser.h"
180#include "chrome/browser/browser_list.h"
181#include "chrome/browser/browser_process.h"
182#include "chrome/browser/load_notification_details.h"
183#include "chrome/browser/memory_details.h"
initial.commit09911bf2008-07-26 23:55:29184#include "chrome/browser/profile.h"
[email protected]8c8657d62009-01-16 18:31:26185#include "chrome/browser/renderer_host/render_process_host.h"
[email protected]d54e03a52009-01-16 00:31:04186#include "chrome/browser/search_engines/template_url.h"
187#include "chrome/browser/search_engines/template_url_model.h"
[email protected]a27a9382009-02-11 23:55:10188#include "chrome/common/child_process_info.h"
initial.commit09911bf2008-07-26 23:55:29189#include "chrome/common/chrome_paths.h"
[email protected]92745242009-06-12 16:52:21190#include "chrome/common/chrome_switches.h"
[email protected]c9a3ef82009-05-28 22:02:46191#include "chrome/common/histogram_synchronizer.h"
[email protected]252873ef2008-08-04 21:59:45192#include "chrome/common/libxml_utils.h"
[email protected]bfd04a62009-02-01 18:16:56193#include "chrome/common/notification_service.h"
initial.commit09911bf2008-07-26 23:55:29194#include "chrome/common/pref_names.h"
195#include "chrome/common/pref_service.h"
[email protected]e09ba552009-02-05 03:26:29196#include "chrome/common/render_messages.h"
initial.commit09911bf2008-07-26 23:55:29197#include "googleurl/src/gurl.h"
198#include "net/base/load_flags.h"
[email protected]35fa6a22009-08-15 00:04:01199#include "webkit/glue/plugins/plugin_list.h"
initial.commit09911bf2008-07-26 23:55:29200
[email protected]dc6f4962009-02-13 01:25:50201#if defined(OS_POSIX)
202// TODO(port): Move these headers above as they are ported.
203#include "chrome/common/temp_scaffolding_stubs.h"
204#else
[email protected]79bf0b72009-04-27 21:30:55205#include "chrome/installer/util/browser_distribution.h"
[email protected]dc6f4962009-02-13 01:25:50206#include "chrome/installer/util/google_update_settings.h"
207#endif
208
[email protected]e1acf6f2008-10-27 20:43:33209using base::Time;
210using base::TimeDelta;
211
initial.commit09911bf2008-07-26 23:55:29212// Check to see that we're being called on only one thread.
213static bool IsSingleThreaded();
214
initial.commit09911bf2008-07-26 23:55:29215static const char kMetricsType[] = "application/vnd.mozilla.metrics.bz2";
216
217// The delay, in seconds, after startup before sending the first log message.
[email protected]252873ef2008-08-04 21:59:45218static const int kInitialInterlogDuration = 60; // one minute
219
[email protected]c9a3ef82009-05-28 22:02:46220// This specifies the amount of time to wait for all renderers to send their
221// data.
222static const int kMaxHistogramGatheringWaitDuration = 60000; // 60 seconds.
223
[email protected]252873ef2008-08-04 21:59:45224// The default maximum number of events in a log uploaded to the UMA server.
[email protected]0b33f80b2008-12-17 21:34:36225static const int kInitialEventLimit = 2400;
[email protected]68475e602008-08-22 03:21:15226
227// If an upload fails, and the transmission was over this byte count, then we
228// will discard the log, and not try to retransmit it. We also don't persist
229// the log to the prefs for transmission during the next chrome session if this
230// limit is exceeded.
231static const int kUploadLogAvoidRetransmitSize = 50000;
initial.commit09911bf2008-07-26 23:55:29232
233// When we have logs from previous Chrome sessions to send, how long should we
234// delay (in seconds) between each log transmission.
235static const int kUnsentLogDelay = 15; // 15 seconds
236
237// Minimum time a log typically exists before sending, in seconds.
238// This number is supplied by the server, but until we parse it out of a server
239// response, we use this duration to specify how long we should wait before
240// sending the next log. If the channel is busy, such as when there is a
241// failure during an attempt to transmit a previous log, then a log may wait
242// (and continue to accrue now log entries) for a much greater period of time.
[email protected]0eb34fee2009-01-21 08:04:38243static const int kMinSecondsPerLog = 20 * 60; // Twenty minutes.
initial.commit09911bf2008-07-26 23:55:29244
initial.commit09911bf2008-07-26 23:55:29245// When we don't succeed at transmitting a log to a server, we progressively
246// wait longer and longer before sending the next log. This backoff process
247// help reduce load on the server, and makes the amount of backoff vary between
248// clients so that a collision (server overload?) on retransmit is less likely.
249// The following is the constant we use to expand that inter-log duration.
250static const double kBackoff = 1.1;
251// We limit the maximum backoff to be no greater than some multiple of the
252// default kMinSecondsPerLog. The following is that maximum ratio.
253static const int kMaxBackoff = 10;
254
255// Interval, in seconds, between state saves.
256static const int kSaveStateInterval = 5 * 60; // five minutes
257
258// The number of "initial" logs we're willing to save, and hope to send during
259// a future Chrome session. Initial logs contain crash stats, and are pretty
260// small.
261static const size_t kMaxInitialLogsPersisted = 20;
262
263// The number of ongoing logs we're willing to save persistently, and hope to
[email protected]281d2882009-01-20 20:32:42264// send during a this or future sessions. Note that each log may be pretty
initial.commit09911bf2008-07-26 23:55:29265// large, as presumably the related "initial" log wasn't sent (probably nothing
266// was, as the user was probably off-line). As a result, the log probably kept
267// accumulating while the "initial" log was stalled (pending_), and couldn't be
268// sent. As a result, we don't want to save too many of these mega-logs.
269// A "standard shutdown" will create a small log, including just the data that
270// was not yet been transmitted, and that is normal (to have exactly one
271// ongoing_log_ at startup).
[email protected]281d2882009-01-20 20:32:42272static const size_t kMaxOngoingLogsPersisted = 8;
initial.commit09911bf2008-07-26 23:55:29273
274
275// Handles asynchronous fetching of memory details.
276// Will run the provided task after finished.
277class MetricsMemoryDetails : public MemoryDetails {
278 public:
279 explicit MetricsMemoryDetails(Task* completion) : completion_(completion) {}
280
281 virtual void OnDetailsAvailable() {
282 MessageLoop::current()->PostTask(FROM_HERE, completion_);
283 }
284
285 private:
286 Task* completion_;
287 DISALLOW_EVIL_CONSTRUCTORS(MetricsMemoryDetails);
288};
289
290class MetricsService::GetPluginListTaskComplete : public Task {
[email protected]35fa6a22009-08-15 00:04:01291 public:
292 explicit GetPluginListTaskComplete(
293 const std::vector<WebPluginInfo>& plugins) : plugins_(plugins) { }
initial.commit09911bf2008-07-26 23:55:29294 virtual void Run() {
[email protected]35fa6a22009-08-15 00:04:01295 g_browser_process->metrics_service()->OnGetPluginListTaskComplete(plugins_);
initial.commit09911bf2008-07-26 23:55:29296 }
[email protected]35fa6a22009-08-15 00:04:01297
298 private:
299 std::vector<WebPluginInfo> plugins_;
initial.commit09911bf2008-07-26 23:55:29300};
301
302class MetricsService::GetPluginListTask : public Task {
303 public:
304 explicit GetPluginListTask(MessageLoop* callback_loop)
305 : callback_loop_(callback_loop) {}
306
307 virtual void Run() {
308 std::vector<WebPluginInfo> plugins;
[email protected]35fa6a22009-08-15 00:04:01309 NPAPI::PluginList::Singleton()->GetPlugins(false, &plugins);
initial.commit09911bf2008-07-26 23:55:29310
[email protected]35fa6a22009-08-15 00:04:01311 callback_loop_->PostTask(
312 FROM_HERE, new GetPluginListTaskComplete(plugins));
initial.commit09911bf2008-07-26 23:55:29313 }
314
315 private:
316 MessageLoop* callback_loop_;
317};
318
319// static
320void MetricsService::RegisterPrefs(PrefService* local_state) {
321 DCHECK(IsSingleThreaded());
322 local_state->RegisterStringPref(prefs::kMetricsClientID, L"");
[email protected]0bb1a622009-03-04 03:22:32323 local_state->RegisterInt64Pref(prefs::kMetricsClientIDTimestamp, 0);
324 local_state->RegisterInt64Pref(prefs::kStabilityLaunchTimeSec, 0);
325 local_state->RegisterInt64Pref(prefs::kStabilityLastTimestampSec, 0);
326 local_state->RegisterInt64Pref(prefs::kStabilityUptimeSec, 0);
[email protected]541f77922009-02-23 21:14:38327 local_state->RegisterStringPref(prefs::kStabilityStatsVersion, L"");
initial.commit09911bf2008-07-26 23:55:29328 local_state->RegisterBooleanPref(prefs::kStabilityExitedCleanly, true);
329 local_state->RegisterBooleanPref(prefs::kStabilitySessionEndCompleted, true);
330 local_state->RegisterIntegerPref(prefs::kMetricsSessionID, -1);
331 local_state->RegisterIntegerPref(prefs::kStabilityLaunchCount, 0);
332 local_state->RegisterIntegerPref(prefs::kStabilityCrashCount, 0);
333 local_state->RegisterIntegerPref(prefs::kStabilityIncompleteSessionEndCount,
334 0);
335 local_state->RegisterIntegerPref(prefs::kStabilityPageLoadCount, 0);
336 local_state->RegisterIntegerPref(prefs::kSecurityRendererOnSboxDesktop, 0);
337 local_state->RegisterIntegerPref(prefs::kSecurityRendererOnDefaultDesktop, 0);
338 local_state->RegisterIntegerPref(prefs::kStabilityRendererCrashCount, 0);
339 local_state->RegisterIntegerPref(prefs::kStabilityRendererHangCount, 0);
[email protected]e73c01972008-08-13 00:18:24340 local_state->RegisterIntegerPref(prefs::kStabilityBreakpadRegistrationFail,
341 0);
342 local_state->RegisterIntegerPref(prefs::kStabilityBreakpadRegistrationSuccess,
343 0);
344 local_state->RegisterIntegerPref(prefs::kStabilityDebuggerPresent, 0);
345 local_state->RegisterIntegerPref(prefs::kStabilityDebuggerNotPresent, 0);
346
initial.commit09911bf2008-07-26 23:55:29347 local_state->RegisterDictionaryPref(prefs::kProfileMetrics);
348 local_state->RegisterIntegerPref(prefs::kNumBookmarksOnBookmarkBar, 0);
349 local_state->RegisterIntegerPref(prefs::kNumFoldersOnBookmarkBar, 0);
350 local_state->RegisterIntegerPref(prefs::kNumBookmarksInOtherBookmarkFolder,
351 0);
352 local_state->RegisterIntegerPref(prefs::kNumFoldersInOtherBookmarkFolder, 0);
353 local_state->RegisterIntegerPref(prefs::kNumKeywords, 0);
354 local_state->RegisterListPref(prefs::kMetricsInitialLogs);
355 local_state->RegisterListPref(prefs::kMetricsOngoingLogs);
[email protected]0bb1a622009-03-04 03:22:32356
357 local_state->RegisterInt64Pref(prefs::kUninstallMetricsPageLoadCount, 0);
358 local_state->RegisterInt64Pref(prefs::kUninstallLaunchCount, 0);
[email protected]6b5f21d2009-04-13 17:01:35359 local_state->RegisterInt64Pref(prefs::kUninstallMetricsInstallDate, 0);
[email protected]0bb1a622009-03-04 03:22:32360 local_state->RegisterInt64Pref(prefs::kUninstallMetricsUptimeSec, 0);
361 local_state->RegisterInt64Pref(prefs::kUninstallLastLaunchTimeSec, 0);
362 local_state->RegisterInt64Pref(prefs::kUninstallLastObservedRunTimeSec, 0);
initial.commit09911bf2008-07-26 23:55:29363}
364
[email protected]541f77922009-02-23 21:14:38365// static
366void MetricsService::DiscardOldStabilityStats(PrefService* local_state) {
367 local_state->SetBoolean(prefs::kStabilityExitedCleanly, true);
[email protected]c9abf242009-07-18 06:00:38368 local_state->SetBoolean(prefs::kStabilitySessionEndCompleted, true);
[email protected]541f77922009-02-23 21:14:38369
370 local_state->SetInteger(prefs::kStabilityIncompleteSessionEndCount, 0);
371 local_state->SetInteger(prefs::kStabilityBreakpadRegistrationSuccess, 0);
372 local_state->SetInteger(prefs::kStabilityBreakpadRegistrationFail, 0);
373 local_state->SetInteger(prefs::kStabilityDebuggerPresent, 0);
374 local_state->SetInteger(prefs::kStabilityDebuggerNotPresent, 0);
375
376 local_state->SetInteger(prefs::kStabilityLaunchCount, 0);
377 local_state->SetInteger(prefs::kStabilityCrashCount, 0);
378
379 local_state->SetInteger(prefs::kStabilityPageLoadCount, 0);
380 local_state->SetInteger(prefs::kStabilityRendererCrashCount, 0);
381 local_state->SetInteger(prefs::kStabilityRendererHangCount, 0);
382
383 local_state->SetInteger(prefs::kSecurityRendererOnSboxDesktop, 0);
384 local_state->SetInteger(prefs::kSecurityRendererOnDefaultDesktop, 0);
385
[email protected]c9abf242009-07-18 06:00:38386 local_state->SetString(prefs::kStabilityLaunchTimeSec, L"0");
387 local_state->SetString(prefs::kStabilityLastTimestampSec, L"0");
[email protected]541f77922009-02-23 21:14:38388 local_state->SetString(prefs::kStabilityUptimeSec, L"0");
389
390 local_state->ClearPref(prefs::kStabilityPluginStats);
[email protected]ae155cb92009-06-19 06:10:37391
392 ListValue* unsent_initial_logs = local_state->GetMutableList(
393 prefs::kMetricsInitialLogs);
394 unsent_initial_logs->Clear();
395
396 ListValue* unsent_ongoing_logs = local_state->GetMutableList(
397 prefs::kMetricsOngoingLogs);
398 unsent_ongoing_logs->Clear();
[email protected]541f77922009-02-23 21:14:38399}
400
initial.commit09911bf2008-07-26 23:55:29401MetricsService::MetricsService()
[email protected]d01b8732008-10-16 02:18:07402 : recording_active_(false),
403 reporting_active_(false),
404 user_permits_upload_(false),
405 server_permits_upload_(true),
406 state_(INITIALIZED),
initial.commit09911bf2008-07-26 23:55:29407 pending_log_(NULL),
[email protected]9ffcccf42009-09-15 22:19:18408 pending_log_text_(),
initial.commit09911bf2008-07-26 23:55:29409 current_fetch_(NULL),
410 current_log_(NULL),
[email protected]d01b8732008-10-16 02:18:07411 idle_since_last_transmission_(false),
initial.commit09911bf2008-07-26 23:55:29412 next_window_id_(0),
[email protected]40bcc302009-03-02 20:50:39413 ALLOW_THIS_IN_INITIALIZER_LIST(log_sender_factory_(this)),
414 ALLOW_THIS_IN_INITIALIZER_LIST(state_saver_factory_(this)),
initial.commit09911bf2008-07-26 23:55:29415 logged_samples_(),
[email protected]252873ef2008-08-04 21:59:45416 interlog_duration_(TimeDelta::FromSeconds(kInitialInterlogDuration)),
[email protected]d01b8732008-10-16 02:18:07417 log_event_limit_(kInitialEventLimit),
initial.commit09911bf2008-07-26 23:55:29418 timer_pending_(false) {
419 DCHECK(IsSingleThreaded());
420 InitializeMetricsState();
421}
422
423MetricsService::~MetricsService() {
424 SetRecording(false);
[email protected]d8bc79bf2009-01-28 01:17:58425 if (pending_log_) {
426 delete pending_log_;
427 pending_log_ = NULL;
428 }
429 if (current_log_) {
430 delete current_log_;
431 current_log_ = NULL;
432 }
initial.commit09911bf2008-07-26 23:55:29433}
434
[email protected]d01b8732008-10-16 02:18:07435void MetricsService::SetUserPermitsUpload(bool enabled) {
436 HandleIdleSinceLastTransmission(false);
437 user_permits_upload_ = enabled;
438}
439
440void MetricsService::Start() {
441 SetRecording(true);
442 SetReporting(true);
443}
444
445void MetricsService::StartRecordingOnly() {
446 SetRecording(true);
447 SetReporting(false);
448}
449
450void MetricsService::Stop() {
451 SetReporting(false);
452 SetRecording(false);
453}
454
initial.commit09911bf2008-07-26 23:55:29455void MetricsService::SetRecording(bool enabled) {
456 DCHECK(IsSingleThreaded());
457
[email protected]d01b8732008-10-16 02:18:07458 if (enabled == recording_active_)
initial.commit09911bf2008-07-26 23:55:29459 return;
460
461 if (enabled) {
[email protected]b0c819f2009-03-08 04:52:15462 if (client_id_.empty()) {
463 PrefService* pref = g_browser_process->local_state();
464 DCHECK(pref);
465 client_id_ = WideToUTF8(pref->GetString(prefs::kMetricsClientID));
466 if (client_id_.empty()) {
467 client_id_ = GenerateClientID();
468 pref->SetString(prefs::kMetricsClientID, UTF8ToWide(client_id_));
469
470 // Might as well make a note of how long this ID has existed
471 pref->SetString(prefs::kMetricsClientIDTimestamp,
472 Int64ToWString(Time::Now().ToTimeT()));
473 }
474 }
initial.commit09911bf2008-07-26 23:55:29475 StartRecording();
[email protected]005ef3e2009-05-22 20:55:46476
477 registrar_.Add(this, NotificationType::BROWSER_OPENED,
478 NotificationService::AllSources());
479 registrar_.Add(this, NotificationType::BROWSER_CLOSED,
480 NotificationService::AllSources());
481 registrar_.Add(this, NotificationType::USER_ACTION,
482 NotificationService::AllSources());
483 registrar_.Add(this, NotificationType::TAB_PARENTED,
484 NotificationService::AllSources());
485 registrar_.Add(this, NotificationType::TAB_CLOSING,
486 NotificationService::AllSources());
487 registrar_.Add(this, NotificationType::LOAD_START,
488 NotificationService::AllSources());
489 registrar_.Add(this, NotificationType::LOAD_STOP,
490 NotificationService::AllSources());
491 registrar_.Add(this, NotificationType::RENDERER_PROCESS_IN_SBOX,
492 NotificationService::AllSources());
493 registrar_.Add(this, NotificationType::RENDERER_PROCESS_CLOSED,
494 NotificationService::AllSources());
495 registrar_.Add(this, NotificationType::RENDERER_PROCESS_HANG,
496 NotificationService::AllSources());
497 registrar_.Add(this, NotificationType::CHILD_PROCESS_HOST_CONNECTED,
498 NotificationService::AllSources());
499 registrar_.Add(this, NotificationType::CHILD_INSTANCE_CREATED,
500 NotificationService::AllSources());
501 registrar_.Add(this, NotificationType::CHILD_PROCESS_CRASHED,
502 NotificationService::AllSources());
503 registrar_.Add(this, NotificationType::TEMPLATE_URL_MODEL_LOADED,
504 NotificationService::AllSources());
505 registrar_.Add(this, NotificationType::OMNIBOX_OPENED_URL,
506 NotificationService::AllSources());
507 registrar_.Add(this, NotificationType::BOOKMARK_MODEL_LOADED,
508 NotificationService::AllSources());
initial.commit09911bf2008-07-26 23:55:29509 } else {
[email protected]005ef3e2009-05-22 20:55:46510 registrar_.RemoveAll();
initial.commit09911bf2008-07-26 23:55:29511 PushPendingLogsToUnsentLists();
512 DCHECK(!pending_log());
513 if (state_ > INITIAL_LOG_READY && unsent_logs())
514 state_ = SEND_OLD_INITIAL_LOGS;
515 }
[email protected]d01b8732008-10-16 02:18:07516 recording_active_ = enabled;
initial.commit09911bf2008-07-26 23:55:29517}
518
[email protected]d01b8732008-10-16 02:18:07519bool MetricsService::recording_active() const {
initial.commit09911bf2008-07-26 23:55:29520 DCHECK(IsSingleThreaded());
[email protected]d01b8732008-10-16 02:18:07521 return recording_active_;
initial.commit09911bf2008-07-26 23:55:29522}
523
[email protected]d01b8732008-10-16 02:18:07524void MetricsService::SetReporting(bool enable) {
525 if (reporting_active_ != enable) {
526 reporting_active_ = enable;
527 if (reporting_active_)
initial.commit09911bf2008-07-26 23:55:29528 StartLogTransmissionTimer();
529 }
[email protected]d01b8732008-10-16 02:18:07530}
531
532bool MetricsService::reporting_active() const {
533 DCHECK(IsSingleThreaded());
534 return reporting_active_;
initial.commit09911bf2008-07-26 23:55:29535}
536
537void MetricsService::Observe(NotificationType type,
538 const NotificationSource& source,
539 const NotificationDetails& details) {
540 DCHECK(current_log_);
541 DCHECK(IsSingleThreaded());
542
543 if (!CanLogNotification(type, source, details))
544 return;
545
[email protected]bfd04a62009-02-01 18:16:56546 switch (type.value) {
547 case NotificationType::USER_ACTION:
initial.commit09911bf2008-07-26 23:55:29548 current_log_->RecordUserAction(*Details<const wchar_t*>(details).ptr());
549 break;
550
[email protected]bfd04a62009-02-01 18:16:56551 case NotificationType::BROWSER_OPENED:
552 case NotificationType::BROWSER_CLOSED:
initial.commit09911bf2008-07-26 23:55:29553 LogWindowChange(type, source, details);
554 break;
555
[email protected]bfd04a62009-02-01 18:16:56556 case NotificationType::TAB_PARENTED:
557 case NotificationType::TAB_CLOSING:
initial.commit09911bf2008-07-26 23:55:29558 LogWindowChange(type, source, details);
559 break;
560
[email protected]bfd04a62009-02-01 18:16:56561 case NotificationType::LOAD_STOP:
initial.commit09911bf2008-07-26 23:55:29562 LogLoadComplete(type, source, details);
563 break;
564
[email protected]bfd04a62009-02-01 18:16:56565 case NotificationType::LOAD_START:
initial.commit09911bf2008-07-26 23:55:29566 LogLoadStarted();
567 break;
568
[email protected]6ba2ec22009-05-05 00:50:53569 case NotificationType::RENDERER_PROCESS_CLOSED:
570 if (*Details<bool>(details).ptr())
571 LogRendererCrash();
initial.commit09911bf2008-07-26 23:55:29572 break;
573
[email protected]bfd04a62009-02-01 18:16:56574 case NotificationType::RENDERER_PROCESS_HANG:
initial.commit09911bf2008-07-26 23:55:29575 LogRendererHang();
576 break;
577
[email protected]bfd04a62009-02-01 18:16:56578 case NotificationType::RENDERER_PROCESS_IN_SBOX:
initial.commit09911bf2008-07-26 23:55:29579 LogRendererInSandbox(*Details<bool>(details).ptr());
580 break;
581
[email protected]a27a9382009-02-11 23:55:10582 case NotificationType::CHILD_PROCESS_HOST_CONNECTED:
583 case NotificationType::CHILD_PROCESS_CRASHED:
584 case NotificationType::CHILD_INSTANCE_CREATED:
585 LogChildProcessChange(type, source, details);
initial.commit09911bf2008-07-26 23:55:29586 break;
587
[email protected]bfd04a62009-02-01 18:16:56588 case NotificationType::TEMPLATE_URL_MODEL_LOADED:
initial.commit09911bf2008-07-26 23:55:29589 LogKeywords(Source<TemplateURLModel>(source).ptr());
590 break;
591
[email protected]bfd04a62009-02-01 18:16:56592 case NotificationType::OMNIBOX_OPENED_URL:
initial.commit09911bf2008-07-26 23:55:29593 current_log_->RecordOmniboxOpenedURL(
594 *Details<AutocompleteLog>(details).ptr());
595 break;
596
[email protected]b61236c62009-04-09 22:43:55597 case NotificationType::BOOKMARK_MODEL_LOADED: {
598 Profile* p = Source<Profile>(source).ptr();
599 if (p)
600 LogBookmarks(p->GetBookmarkModel());
initial.commit09911bf2008-07-26 23:55:29601 break;
[email protected]b61236c62009-04-09 22:43:55602 }
initial.commit09911bf2008-07-26 23:55:29603 default:
604 NOTREACHED();
605 break;
606 }
[email protected]d01b8732008-10-16 02:18:07607
608 HandleIdleSinceLastTransmission(false);
609
610 if (current_log_)
[email protected]281d2882009-01-20 20:32:42611 DLOG(INFO) << "METRICS: NUMBER OF EVENTS = " << current_log_->num_events();
[email protected]d01b8732008-10-16 02:18:07612}
613
614void MetricsService::HandleIdleSinceLastTransmission(bool in_idle) {
615 // If there wasn't a lot of action, maybe the computer was asleep, in which
616 // case, the log transmissions should have stopped. Here we start them up
617 // again.
[email protected]cac78842008-11-27 01:02:20618 if (!in_idle && idle_since_last_transmission_)
619 StartLogTransmissionTimer();
620 idle_since_last_transmission_ = in_idle;
initial.commit09911bf2008-07-26 23:55:29621}
622
623void MetricsService::RecordCleanShutdown() {
624 RecordBooleanPrefValue(prefs::kStabilityExitedCleanly, true);
625}
626
627void MetricsService::RecordStartOfSessionEnd() {
628 RecordBooleanPrefValue(prefs::kStabilitySessionEndCompleted, false);
629}
630
631void MetricsService::RecordCompletedSessionEnd() {
632 RecordBooleanPrefValue(prefs::kStabilitySessionEndCompleted, true);
633}
634
[email protected]e73c01972008-08-13 00:18:24635void MetricsService:: RecordBreakpadRegistration(bool success) {
[email protected]68475e602008-08-22 03:21:15636 if (!success)
[email protected]e73c01972008-08-13 00:18:24637 IncrementPrefValue(prefs::kStabilityBreakpadRegistrationFail);
638 else
639 IncrementPrefValue(prefs::kStabilityBreakpadRegistrationSuccess);
640}
641
642void MetricsService::RecordBreakpadHasDebugger(bool has_debugger) {
643 if (!has_debugger)
644 IncrementPrefValue(prefs::kStabilityDebuggerNotPresent);
645 else
[email protected]68475e602008-08-22 03:21:15646 IncrementPrefValue(prefs::kStabilityDebuggerPresent);
[email protected]e73c01972008-08-13 00:18:24647}
648
initial.commit09911bf2008-07-26 23:55:29649//------------------------------------------------------------------------------
650// private methods
651//------------------------------------------------------------------------------
652
653
654//------------------------------------------------------------------------------
655// Initialization methods
656
657void MetricsService::InitializeMetricsState() {
[email protected]79bf0b72009-04-27 21:30:55658#if defined(OS_POSIX)
659 server_url_ = L"https://clients4.google.com/firefox/metrics/collect";
660#else
661 BrowserDistribution* dist = BrowserDistribution::GetDistribution();
662 server_url_ = dist->GetStatsServerURL();
663#endif
664
initial.commit09911bf2008-07-26 23:55:29665 PrefService* pref = g_browser_process->local_state();
666 DCHECK(pref);
667
[email protected]541f77922009-02-23 21:14:38668 if (WideToUTF8(pref->GetString(prefs::kStabilityStatsVersion)) !=
669 MetricsLog::GetVersionString()) {
670 // This is a new version, so we don't want to confuse the stats about the
671 // old version with info that we upload.
672 DiscardOldStabilityStats(pref);
673 pref->SetString(prefs::kStabilityStatsVersion,
674 UTF8ToWide(MetricsLog::GetVersionString()));
675 }
676
initial.commit09911bf2008-07-26 23:55:29677 // Update session ID
678 session_id_ = pref->GetInteger(prefs::kMetricsSessionID);
679 ++session_id_;
680 pref->SetInteger(prefs::kMetricsSessionID, session_id_);
681
initial.commit09911bf2008-07-26 23:55:29682 // Stability bookkeeping
[email protected]e73c01972008-08-13 00:18:24683 IncrementPrefValue(prefs::kStabilityLaunchCount);
initial.commit09911bf2008-07-26 23:55:29684
[email protected]e73c01972008-08-13 00:18:24685 if (!pref->GetBoolean(prefs::kStabilityExitedCleanly)) {
686 IncrementPrefValue(prefs::kStabilityCrashCount);
initial.commit09911bf2008-07-26 23:55:29687 }
[email protected]e73c01972008-08-13 00:18:24688
689 // This will be set to 'true' if we exit cleanly.
initial.commit09911bf2008-07-26 23:55:29690 pref->SetBoolean(prefs::kStabilityExitedCleanly, false);
691
[email protected]e73c01972008-08-13 00:18:24692 if (!pref->GetBoolean(prefs::kStabilitySessionEndCompleted)) {
693 IncrementPrefValue(prefs::kStabilityIncompleteSessionEndCount);
[email protected]c9abf242009-07-18 06:00:38694 // This is marked false when we get a WM_ENDSESSION.
695 pref->SetBoolean(prefs::kStabilitySessionEndCompleted, true);
initial.commit09911bf2008-07-26 23:55:29696 }
initial.commit09911bf2008-07-26 23:55:29697
[email protected]0bb1a622009-03-04 03:22:32698 int64 last_start_time = pref->GetInt64(prefs::kStabilityLaunchTimeSec);
699 int64 last_end_time = pref->GetInt64(prefs::kStabilityLastTimestampSec);
700 int64 uptime = pref->GetInt64(prefs::kStabilityUptimeSec);
701
702 // Same idea as uptime, except this one never gets reset and is used at
703 // uninstallation.
704 int64 uninstall_metrics_uptime =
705 pref->GetInt64(prefs::kUninstallMetricsUptimeSec);
initial.commit09911bf2008-07-26 23:55:29706
707 if (last_start_time && last_end_time) {
708 // TODO(JAR): Exclude sleep time. ... which must be gathered in UI loop.
[email protected]0bb1a622009-03-04 03:22:32709 int64 uptime_increment = last_end_time - last_start_time;
710 uptime += uptime_increment;
711 pref->SetInt64(prefs::kStabilityUptimeSec, uptime);
712
713 uninstall_metrics_uptime += uptime_increment;
714 pref->SetInt64(prefs::kUninstallMetricsUptimeSec,
715 uninstall_metrics_uptime);
initial.commit09911bf2008-07-26 23:55:29716 }
[email protected]0bb1a622009-03-04 03:22:32717 pref->SetInt64(prefs::kStabilityLaunchTimeSec, Time::Now().ToTimeT());
718
719 // Bookkeeping for the uninstall metrics.
720 IncrementLongPrefsValue(prefs::kUninstallLaunchCount);
initial.commit09911bf2008-07-26 23:55:29721
722 // Save profile metrics.
723 PrefService* prefs = g_browser_process->local_state();
724 if (prefs) {
725 // Remove the current dictionary and store it for use when sending data to
726 // server. By removing the value we prune potentially dead profiles
727 // (and keys). All valid values are added back once services startup.
728 const DictionaryValue* profile_dictionary =
729 prefs->GetDictionary(prefs::kProfileMetrics);
730 if (profile_dictionary) {
731 // Do a deep copy of profile_dictionary since ClearPref will delete it.
732 profile_dictionary_.reset(static_cast<DictionaryValue*>(
733 profile_dictionary->DeepCopy()));
734 prefs->ClearPref(prefs::kProfileMetrics);
735 }
736 }
737
[email protected]92745242009-06-12 16:52:21738 // Get stats on use of command line.
739 const CommandLine* command_line(CommandLine::ForCurrentProcess());
740 size_t common_commands = 0;
741 if (command_line->HasSwitch(switches::kUserDataDir)) {
742 ++common_commands;
743 UMA_HISTOGRAM_COUNTS_100("Chrome.CommandLineDatDirCount", 1);
744 }
745
746 if (command_line->HasSwitch(switches::kApp)) {
747 ++common_commands;
748 UMA_HISTOGRAM_COUNTS_100("Chrome.CommandLineAppModeCount", 1);
749 }
750
751 UMA_HISTOGRAM_COUNTS_100("Chrome.CommandLineFlagCount",
752 command_line->GetSwitchCount());
753 UMA_HISTOGRAM_COUNTS_100("Chrome.CommandLineUncommonFlagCount",
754 command_line->GetSwitchCount() - common_commands);
755
initial.commit09911bf2008-07-26 23:55:29756 // Kick off the process of saving the state (so the uptime numbers keep
757 // getting updated) every n minutes.
758 ScheduleNextStateSave();
759}
760
[email protected]35fa6a22009-08-15 00:04:01761void MetricsService::OnGetPluginListTaskComplete(
762 const std::vector<WebPluginInfo>& plugins) {
initial.commit09911bf2008-07-26 23:55:29763 DCHECK(state_ == PLUGIN_LIST_REQUESTED);
[email protected]35fa6a22009-08-15 00:04:01764 plugins_ = plugins;
initial.commit09911bf2008-07-26 23:55:29765 if (state_ == PLUGIN_LIST_REQUESTED)
766 state_ = PLUGIN_LIST_ARRIVED;
767}
768
769std::string MetricsService::GenerateClientID() {
[email protected]dc6f4962009-02-13 01:25:50770#if defined(OS_WIN)
initial.commit09911bf2008-07-26 23:55:29771 const int kGUIDSize = 39;
772
773 GUID guid;
774 HRESULT guid_result = CoCreateGuid(&guid);
775 DCHECK(SUCCEEDED(guid_result));
776
777 std::wstring guid_string;
778 int result = StringFromGUID2(guid,
779 WriteInto(&guid_string, kGUIDSize), kGUIDSize);
780 DCHECK(result == kGUIDSize);
781
782 return WideToUTF8(guid_string.substr(1, guid_string.length() - 2));
[email protected]271b24f2009-07-28 16:05:51783#else
[email protected]06aaac22009-07-08 20:54:13784 uint64 sixteen_bytes[2] = { base::RandUint64(), base::RandUint64() };
785 return RandomBytesToGUIDString(sixteen_bytes);
[email protected]dc6f4962009-02-13 01:25:50786#endif
initial.commit09911bf2008-07-26 23:55:29787}
788
[email protected]06aaac22009-07-08 20:54:13789#if defined(OS_POSIX)
790// TODO(cmasone): Once we're comfortable this works, migrate Windows code to
791// use this as well.
792std::string MetricsService::RandomBytesToGUIDString(const uint64 bytes[2]) {
793 return StringPrintf("%08llX-%04llX-%04llX-%04llX-%012llX",
794 bytes[0] >> 32,
795 (bytes[0] >> 16) & 0x0000ffff,
796 bytes[0] & 0x0000ffff,
797 bytes[1] >> 48,
798 bytes[1] & 0x0000ffffffffffffULL);
799}
800#endif
initial.commit09911bf2008-07-26 23:55:29801
802//------------------------------------------------------------------------------
803// State save methods
804
805void MetricsService::ScheduleNextStateSave() {
806 state_saver_factory_.RevokeAll();
807
808 MessageLoop::current()->PostDelayedTask(FROM_HERE,
809 state_saver_factory_.NewRunnableMethod(&MetricsService::SaveLocalState),
810 kSaveStateInterval * 1000);
811}
812
813void MetricsService::SaveLocalState() {
814 PrefService* pref = g_browser_process->local_state();
815 if (!pref) {
816 NOTREACHED();
817 return;
818 }
819
820 RecordCurrentState(pref);
[email protected]6faa0e0d2009-04-28 06:50:36821 pref->ScheduleSavePersistentPrefs();
initial.commit09911bf2008-07-26 23:55:29822
[email protected]281d2882009-01-20 20:32:42823 // TODO(jar): Does this run down the batteries????
initial.commit09911bf2008-07-26 23:55:29824 ScheduleNextStateSave();
825}
826
827
828//------------------------------------------------------------------------------
829// Recording control methods
830
831void MetricsService::StartRecording() {
832 if (current_log_)
833 return;
834
835 current_log_ = new MetricsLog(client_id_, session_id_);
836 if (state_ == INITIALIZED) {
837 // We only need to schedule that run once.
838 state_ = PLUGIN_LIST_REQUESTED;
839
840 // Make sure the plugin list is loaded before the inital log is sent, so
841 // that the main thread isn't blocked generating the list.
842 g_browser_process->file_thread()->message_loop()->PostDelayedTask(FROM_HERE,
843 new GetPluginListTask(MessageLoop::current()),
[email protected]252873ef2008-08-04 21:59:45844 kInitialInterlogDuration * 1000 / 2);
initial.commit09911bf2008-07-26 23:55:29845 }
846}
847
848void MetricsService::StopRecording(MetricsLog** log) {
849 if (!current_log_)
850 return;
851
[email protected]68475e602008-08-22 03:21:15852 // TODO(jar): Integrate bounds on log recording more consistently, so that we
853 // can stop recording logs that are too big much sooner.
[email protected]d01b8732008-10-16 02:18:07854 if (current_log_->num_events() > log_event_limit_) {
[email protected]553dba62009-02-24 19:08:23855 UMA_HISTOGRAM_COUNTS("UMA.Discarded Log Events",
[email protected]68475e602008-08-22 03:21:15856 current_log_->num_events());
857 current_log_->CloseLog();
858 delete current_log_;
[email protected]294638782008-09-24 00:22:41859 current_log_ = NULL;
[email protected]68475e602008-08-22 03:21:15860 StartRecording(); // Start trivial log to hold our histograms.
861 }
862
[email protected]0b33f80b2008-12-17 21:34:36863 // Put incremental data (histogram deltas, and realtime stats deltas) at the
[email protected]147bbc0b2009-01-06 19:37:40864 // end of all log transmissions (initial log handles this separately).
initial.commit09911bf2008-07-26 23:55:29865 // Don't bother if we're going to discard current_log_.
[email protected]0b33f80b2008-12-17 21:34:36866 if (log) {
[email protected]c96d53092009-02-24 01:25:06867 current_log_->RecordIncrementalStabilityElements();
initial.commit09911bf2008-07-26 23:55:29868 RecordCurrentHistograms();
[email protected]0b33f80b2008-12-17 21:34:36869 }
initial.commit09911bf2008-07-26 23:55:29870
871 current_log_->CloseLog();
[email protected]cac78842008-11-27 01:02:20872 if (log)
initial.commit09911bf2008-07-26 23:55:29873 *log = current_log_;
[email protected]cac78842008-11-27 01:02:20874 else
initial.commit09911bf2008-07-26 23:55:29875 delete current_log_;
initial.commit09911bf2008-07-26 23:55:29876 current_log_ = NULL;
877}
878
initial.commit09911bf2008-07-26 23:55:29879void MetricsService::PushPendingLogsToUnsentLists() {
880 if (state_ < INITIAL_LOG_READY)
[email protected]28ab7f92009-01-06 21:39:04881 return; // We didn't and still don't have time to get plugin list etc.
initial.commit09911bf2008-07-26 23:55:29882
883 if (pending_log()) {
884 PreparePendingLogText();
885 if (state_ == INITIAL_LOG_READY) {
886 // We may race here, and send second copy of initial log later.
887 unsent_initial_logs_.push_back(pending_log_text_);
[email protected]d01b8732008-10-16 02:18:07888 state_ = SEND_OLD_INITIAL_LOGS;
initial.commit09911bf2008-07-26 23:55:29889 } else {
[email protected]281d2882009-01-20 20:32:42890 // TODO(jar): Verify correctness in other states, including sending unsent
[email protected]541f77922009-02-23 21:14:38891 // initial logs.
[email protected]68475e602008-08-22 03:21:15892 PushPendingLogTextToUnsentOngoingLogs();
initial.commit09911bf2008-07-26 23:55:29893 }
894 DiscardPendingLog();
895 }
896 DCHECK(!pending_log());
897 StopRecording(&pending_log_);
898 PreparePendingLogText();
[email protected]68475e602008-08-22 03:21:15899 PushPendingLogTextToUnsentOngoingLogs();
initial.commit09911bf2008-07-26 23:55:29900 DiscardPendingLog();
901 StoreUnsentLogs();
902}
903
[email protected]68475e602008-08-22 03:21:15904void MetricsService::PushPendingLogTextToUnsentOngoingLogs() {
[email protected]d01b8732008-10-16 02:18:07905 // If UMA response told us not to upload, there's no need to save the pending
906 // log. It wasn't supposed to be uploaded anyway.
907 if (!server_permits_upload_)
908 return;
909
[email protected]dc6f4962009-02-13 01:25:50910 if (pending_log_text_.length() >
911 static_cast<size_t>(kUploadLogAvoidRetransmitSize)) {
[email protected]553dba62009-02-24 19:08:23912 UMA_HISTOGRAM_COUNTS("UMA.Large Accumulated Log Not Persisted",
[email protected]68475e602008-08-22 03:21:15913 static_cast<int>(pending_log_text_.length()));
914 return;
915 }
916 unsent_ongoing_logs_.push_back(pending_log_text_);
917}
918
initial.commit09911bf2008-07-26 23:55:29919//------------------------------------------------------------------------------
920// Transmission of logs methods
921
922void MetricsService::StartLogTransmissionTimer() {
[email protected]d01b8732008-10-16 02:18:07923 // If we're not reporting, there's no point in starting a log transmission
924 // timer.
925 if (!reporting_active())
926 return;
927
initial.commit09911bf2008-07-26 23:55:29928 if (!current_log_)
929 return; // Recorder is shutdown.
[email protected]d01b8732008-10-16 02:18:07930
931 // If there is already a timer running, we leave it running.
932 // If timer_pending is true because the fetch is waiting for a response,
933 // we return for now and let the response handler start the timer.
934 if (timer_pending_)
initial.commit09911bf2008-07-26 23:55:29935 return;
[email protected]d01b8732008-10-16 02:18:07936
[email protected]d01b8732008-10-16 02:18:07937 // Before starting the timer, set timer_pending_ to true.
initial.commit09911bf2008-07-26 23:55:29938 timer_pending_ = true;
[email protected]d01b8732008-10-16 02:18:07939
940 // Right before the UMA transmission gets started, there's one more thing we'd
941 // like to record: the histogram of memory usage, so we spawn a task to
[email protected]c9a3ef82009-05-28 22:02:46942 // collect the memory details and when that task is finished, it will call
943 // OnMemoryDetailCollectionDone, which will call HistogramSynchronization to
944 // collect histograms from all renderers and then we will call
945 // OnHistogramSynchronizationDone to continue processing.
initial.commit09911bf2008-07-26 23:55:29946 MessageLoop::current()->PostDelayedTask(FROM_HERE,
947 log_sender_factory_.
[email protected]c9a3ef82009-05-28 22:02:46948 NewRunnableMethod(&MetricsService::LogTransmissionTimerDone),
[email protected]743ace42009-06-17 17:23:51949 interlog_duration_.InMilliseconds());
initial.commit09911bf2008-07-26 23:55:29950}
951
[email protected]c9a3ef82009-05-28 22:02:46952void MetricsService::LogTransmissionTimerDone() {
953 Task* task = log_sender_factory_.
954 NewRunnableMethod(&MetricsService::OnMemoryDetailCollectionDone);
955
956 MetricsMemoryDetails* details = new MetricsMemoryDetails(task);
957 details->StartFetch();
958
959 // Collect WebCore cache information to put into a histogram.
[email protected]019191a2009-10-02 20:37:27960 for (RenderProcessHost::iterator i(RenderProcessHost::AllHostsIterator());
961 !i.IsAtEnd(); i.Advance())
962 i.GetCurrentValue()->Send(new ViewMsg_GetCacheResourceStats());
[email protected]c9a3ef82009-05-28 22:02:46963}
964
965void MetricsService::OnMemoryDetailCollectionDone() {
966 DCHECK(IsSingleThreaded());
967
968 // HistogramSynchronizer will Collect histograms from all renderers and it
969 // will call OnHistogramSynchronizationDone (if wait time elapses before it
970 // heard from all renderers, then also it will call
971 // OnHistogramSynchronizationDone).
972
973 // Create a callback_task for OnHistogramSynchronizationDone.
974 Task* callback_task = log_sender_factory_.NewRunnableMethod(
975 &MetricsService::OnHistogramSynchronizationDone);
976
977 // Set up the callback to task to call after we receive histograms from all
978 // renderer processes. Wait time specifies how long to wait before absolutely
979 // calling us back on the task.
980 HistogramSynchronizer::FetchRendererHistogramsAsynchronously(
981 MessageLoop::current(), callback_task,
982 kMaxHistogramGatheringWaitDuration);
983}
984
985void MetricsService::OnHistogramSynchronizationDone() {
initial.commit09911bf2008-07-26 23:55:29986 DCHECK(IsSingleThreaded());
987
[email protected]d01b8732008-10-16 02:18:07988 // This function should only be called via timer, so timer_pending_
989 // should be true.
990 DCHECK(timer_pending_);
991 timer_pending_ = false;
initial.commit09911bf2008-07-26 23:55:29992
993 DCHECK(!current_fetch_.get());
initial.commit09911bf2008-07-26 23:55:29994
[email protected]d01b8732008-10-16 02:18:07995 // If we're getting no notifications, then the log won't have much in it, and
996 // it's possible the computer is about to go to sleep, so don't upload and
997 // don't restart the transmission timer.
998 if (idle_since_last_transmission_)
999 return;
1000
1001 // If somehow there is a fetch in progress, we return setting timer_pending_
1002 // to true and hope things work out.
1003 if (current_fetch_.get()) {
1004 timer_pending_ = true;
1005 return;
1006 }
1007
1008 // If uploads are forbidden by UMA response, there's no point in keeping
1009 // the current_log_, and the more often we delete it, the less likely it is
1010 // to expand forever.
1011 if (!server_permits_upload_ && current_log_) {
1012 StopRecording(NULL);
1013 StartRecording();
1014 }
initial.commit09911bf2008-07-26 23:55:291015
1016 if (!current_log_)
1017 return; // Logging was disabled.
[email protected]d01b8732008-10-16 02:18:071018 if (!reporting_active())
initial.commit09911bf2008-07-26 23:55:291019 return; // Don't do work if we're not going to send anything now.
1020
[email protected]d01b8732008-10-16 02:18:071021 MakePendingLog();
initial.commit09911bf2008-07-26 23:55:291022
[email protected]d01b8732008-10-16 02:18:071023 // MakePendingLog should have put something in the pending log, if it didn't,
1024 // we start the timer again, return and hope things work out.
1025 if (!pending_log()) {
1026 StartLogTransmissionTimer();
1027 return;
1028 }
initial.commit09911bf2008-07-26 23:55:291029
[email protected]d01b8732008-10-16 02:18:071030 // If we're not supposed to upload any UMA data because the response or the
1031 // user said so, cancel the upload at this point, but start the timer.
1032 if (!TransmissionPermitted()) {
1033 DiscardPendingLog();
1034 StartLogTransmissionTimer();
1035 return;
1036 }
initial.commit09911bf2008-07-26 23:55:291037
[email protected]d01b8732008-10-16 02:18:071038 PrepareFetchWithPendingLog();
1039
1040 if (!current_fetch_.get()) {
1041 // Compression failed, and log discarded :-/.
1042 DiscardPendingLog();
1043 StartLogTransmissionTimer(); // Maybe we'll do better next time
1044 // TODO(jar): If compression failed, we should have created a tiny log and
1045 // compressed that, so that we can signal that we're losing logs.
1046 return;
1047 }
1048
1049 DCHECK(!timer_pending_);
1050
1051 // The URL fetch is a like timer in that after a while we get called back
1052 // so we set timer_pending_ true just as we start the url fetch.
1053 timer_pending_ = true;
1054 current_fetch_->Start();
1055
1056 HandleIdleSinceLastTransmission(true);
1057}
1058
1059
1060void MetricsService::MakePendingLog() {
1061 if (pending_log())
1062 return;
1063
1064 switch (state_) {
1065 case INITIALIZED:
1066 case PLUGIN_LIST_REQUESTED: // We should be further along by now.
1067 DCHECK(false);
1068 return;
1069
1070 case PLUGIN_LIST_ARRIVED:
1071 // We need to wait for the initial log to be ready before sending
1072 // anything, because the server will tell us whether it wants to hear
1073 // from us.
1074 PrepareInitialLog();
1075 DCHECK(state_ == PLUGIN_LIST_ARRIVED);
1076 RecallUnsentLogs();
1077 state_ = INITIAL_LOG_READY;
1078 break;
1079
1080 case SEND_OLD_INITIAL_LOGS:
[email protected]cac78842008-11-27 01:02:201081 if (!unsent_initial_logs_.empty()) {
1082 pending_log_text_ = unsent_initial_logs_.back();
1083 break;
1084 }
[email protected]d01b8732008-10-16 02:18:071085 state_ = SENDING_OLD_LOGS;
1086 // Fall through.
initial.commit09911bf2008-07-26 23:55:291087
[email protected]d01b8732008-10-16 02:18:071088 case SENDING_OLD_LOGS:
1089 if (!unsent_ongoing_logs_.empty()) {
1090 pending_log_text_ = unsent_ongoing_logs_.back();
1091 break;
1092 }
1093 state_ = SENDING_CURRENT_LOGS;
1094 // Fall through.
1095
1096 case SENDING_CURRENT_LOGS:
1097 StopRecording(&pending_log_);
1098 StartRecording();
1099 break;
1100
1101 default:
1102 DCHECK(false);
1103 return;
1104 }
1105
1106 DCHECK(pending_log());
1107}
1108
1109bool MetricsService::TransmissionPermitted() const {
1110 // If the user forbids uploading that's they're business, and we don't upload
1111 // anything. If the server forbids uploading, that's our business, so we take
1112 // that to mean it forbids current logs, but we still send up the inital logs
1113 // and any old logs.
[email protected]d01b8732008-10-16 02:18:071114 if (!user_permits_upload_)
1115 return false;
[email protected]cac78842008-11-27 01:02:201116 if (server_permits_upload_)
[email protected]d01b8732008-10-16 02:18:071117 return true;
initial.commit09911bf2008-07-26 23:55:291118
[email protected]cac78842008-11-27 01:02:201119 switch (state_) {
1120 case INITIAL_LOG_READY:
1121 case SEND_OLD_INITIAL_LOGS:
1122 case SENDING_OLD_LOGS:
1123 return true;
1124
1125 case SENDING_CURRENT_LOGS:
1126 default:
1127 return false;
[email protected]8c8824b2008-09-20 01:55:501128 }
initial.commit09911bf2008-07-26 23:55:291129}
1130
initial.commit09911bf2008-07-26 23:55:291131void MetricsService::PrepareInitialLog() {
1132 DCHECK(state_ == PLUGIN_LIST_ARRIVED);
initial.commit09911bf2008-07-26 23:55:291133
1134 MetricsLog* log = new MetricsLog(client_id_, session_id_);
[email protected]35fa6a22009-08-15 00:04:011135 log->RecordEnvironment(plugins_, profile_dictionary_.get());
initial.commit09911bf2008-07-26 23:55:291136
1137 // Histograms only get written to current_log_, so setup for the write.
1138 MetricsLog* save_log = current_log_;
1139 current_log_ = log;
1140 RecordCurrentHistograms(); // Into current_log_... which is really log.
1141 current_log_ = save_log;
1142
1143 log->CloseLog();
1144 DCHECK(!pending_log());
1145 pending_log_ = log;
1146}
1147
1148void MetricsService::RecallUnsentLogs() {
1149 DCHECK(unsent_initial_logs_.empty());
1150 DCHECK(unsent_ongoing_logs_.empty());
1151
1152 PrefService* local_state = g_browser_process->local_state();
1153 DCHECK(local_state);
1154
1155 ListValue* unsent_initial_logs = local_state->GetMutableList(
1156 prefs::kMetricsInitialLogs);
1157 for (ListValue::iterator it = unsent_initial_logs->begin();
1158 it != unsent_initial_logs->end(); ++it) {
[email protected]5e324b72008-12-18 00:07:591159 std::string log;
1160 (*it)->GetAsString(&log);
1161 unsent_initial_logs_.push_back(log);
initial.commit09911bf2008-07-26 23:55:291162 }
1163
1164 ListValue* unsent_ongoing_logs = local_state->GetMutableList(
1165 prefs::kMetricsOngoingLogs);
1166 for (ListValue::iterator it = unsent_ongoing_logs->begin();
1167 it != unsent_ongoing_logs->end(); ++it) {
[email protected]5e324b72008-12-18 00:07:591168 std::string log;
1169 (*it)->GetAsString(&log);
1170 unsent_ongoing_logs_.push_back(log);
initial.commit09911bf2008-07-26 23:55:291171 }
1172}
1173
1174void MetricsService::StoreUnsentLogs() {
1175 if (state_ < INITIAL_LOG_READY)
1176 return; // We never Recalled the prior unsent logs.
1177
1178 PrefService* local_state = g_browser_process->local_state();
1179 DCHECK(local_state);
1180
1181 ListValue* unsent_initial_logs = local_state->GetMutableList(
1182 prefs::kMetricsInitialLogs);
1183 unsent_initial_logs->Clear();
1184 size_t start = 0;
1185 if (unsent_initial_logs_.size() > kMaxInitialLogsPersisted)
1186 start = unsent_initial_logs_.size() - kMaxInitialLogsPersisted;
1187 for (size_t i = start; i < unsent_initial_logs_.size(); ++i)
1188 unsent_initial_logs->Append(
[email protected]5e324b72008-12-18 00:07:591189 Value::CreateStringValue(unsent_initial_logs_[i]));
initial.commit09911bf2008-07-26 23:55:291190
1191 ListValue* unsent_ongoing_logs = local_state->GetMutableList(
1192 prefs::kMetricsOngoingLogs);
1193 unsent_ongoing_logs->Clear();
1194 start = 0;
1195 if (unsent_ongoing_logs_.size() > kMaxOngoingLogsPersisted)
1196 start = unsent_ongoing_logs_.size() - kMaxOngoingLogsPersisted;
1197 for (size_t i = start; i < unsent_ongoing_logs_.size(); ++i)
1198 unsent_ongoing_logs->Append(
[email protected]5e324b72008-12-18 00:07:591199 Value::CreateStringValue(unsent_ongoing_logs_[i]));
initial.commit09911bf2008-07-26 23:55:291200}
1201
1202void MetricsService::PreparePendingLogText() {
1203 DCHECK(pending_log());
1204 if (!pending_log_text_.empty())
1205 return;
[email protected]9ffcccf42009-09-15 22:19:181206 int text_size = pending_log_->GetEncodedLogSize();
1207
1208 // Leave room for the NUL terminator.
1209 pending_log_->GetEncodedLog(WriteInto(&pending_log_text_, text_size + 1),
1210 text_size);
initial.commit09911bf2008-07-26 23:55:291211}
1212
[email protected]d01b8732008-10-16 02:18:071213void MetricsService::PrepareFetchWithPendingLog() {
initial.commit09911bf2008-07-26 23:55:291214 DCHECK(pending_log());
1215 DCHECK(!current_fetch_.get());
1216 PreparePendingLogText();
1217 DCHECK(!pending_log_text_.empty());
1218
1219 // Allow security conscious users to see all metrics logs that we send.
1220 LOG(INFO) << "METRICS LOG: " << pending_log_text_;
1221
1222 std::string compressed_log;
[email protected]cac78842008-11-27 01:02:201223 if (!Bzip2Compress(pending_log_text_, &compressed_log)) {
initial.commit09911bf2008-07-26 23:55:291224 NOTREACHED() << "Failed to compress log for transmission.";
1225 DiscardPendingLog();
1226 StartLogTransmissionTimer(); // Maybe we'll do better on next log :-/.
1227 return;
1228 }
[email protected]cac78842008-11-27 01:02:201229
[email protected]79bf0b72009-04-27 21:30:551230 current_fetch_.reset(new URLFetcher(GURL(WideToUTF16(server_url_)),
1231 URLFetcher::POST,
initial.commit09911bf2008-07-26 23:55:291232 this));
1233 current_fetch_->set_request_context(Profile::GetDefaultRequestContext());
1234 current_fetch_->set_upload_data(kMetricsType, compressed_log);
initial.commit09911bf2008-07-26 23:55:291235}
1236
1237void MetricsService::DiscardPendingLog() {
1238 if (pending_log_) { // Shutdown might have deleted it!
1239 delete pending_log_;
1240 pending_log_ = NULL;
1241 }
1242 pending_log_text_.clear();
1243}
1244
1245// This implementation is based on the Firefox MetricsService implementation.
1246bool MetricsService::Bzip2Compress(const std::string& input,
1247 std::string* output) {
1248 bz_stream stream = {0};
1249 // As long as our input is smaller than the bzip2 block size, we should get
1250 // the best compression. For example, if your input was 250k, using a block
1251 // size of 300k or 500k should result in the same compression ratio. Since
1252 // our data should be under 100k, using the minimum block size of 100k should
1253 // allocate less temporary memory, but result in the same compression ratio.
1254 int result = BZ2_bzCompressInit(&stream,
1255 1, // 100k (min) block size
1256 0, // quiet
1257 0); // default "work factor"
1258 if (result != BZ_OK) { // out of memory?
1259 return false;
1260 }
1261
1262 output->clear();
1263
1264 stream.next_in = const_cast<char*>(input.data());
1265 stream.avail_in = static_cast<int>(input.size());
1266 // NOTE: we don't need a BZ_RUN phase since our input buffer contains
1267 // the entire input
1268 do {
1269 output->resize(output->size() + 1024);
1270 stream.next_out = &((*output)[stream.total_out_lo32]);
1271 stream.avail_out = static_cast<int>(output->size()) - stream.total_out_lo32;
1272 result = BZ2_bzCompress(&stream, BZ_FINISH);
1273 } while (result == BZ_FINISH_OK);
1274 if (result != BZ_STREAM_END) // unknown failure?
1275 return false;
1276 result = BZ2_bzCompressEnd(&stream);
1277 DCHECK(result == BZ_OK);
1278
1279 output->resize(stream.total_out_lo32);
1280
1281 return true;
1282}
1283
1284static const char* StatusToString(const URLRequestStatus& status) {
1285 switch (status.status()) {
1286 case URLRequestStatus::SUCCESS:
1287 return "SUCCESS";
1288
1289 case URLRequestStatus::IO_PENDING:
1290 return "IO_PENDING";
1291
1292 case URLRequestStatus::HANDLED_EXTERNALLY:
1293 return "HANDLED_EXTERNALLY";
1294
1295 case URLRequestStatus::CANCELED:
1296 return "CANCELED";
1297
1298 case URLRequestStatus::FAILED:
1299 return "FAILED";
1300
1301 default:
1302 NOTREACHED();
1303 return "Unknown";
1304 }
1305}
1306
1307void MetricsService::OnURLFetchComplete(const URLFetcher* source,
1308 const GURL& url,
1309 const URLRequestStatus& status,
1310 int response_code,
1311 const ResponseCookies& cookies,
1312 const std::string& data) {
1313 DCHECK(timer_pending_);
1314 timer_pending_ = false;
1315 DCHECK(current_fetch_.get());
1316 current_fetch_.reset(NULL); // We're not allowed to re-use it.
1317
1318 // Confirm send so that we can move on.
[email protected]281d2882009-01-20 20:32:421319 LOG(INFO) << "METRICS RESPONSE CODE: " << response_code << " status=" <<
[email protected]cac78842008-11-27 01:02:201320 StatusToString(status);
[email protected]252873ef2008-08-04 21:59:451321
[email protected]0eb34fee2009-01-21 08:04:381322 // Provide boolean for error recovery (allow us to ignore response_code).
[email protected]dc6f4962009-02-13 01:25:501323 bool discard_log = false;
[email protected]0eb34fee2009-01-21 08:04:381324
[email protected]68475e602008-08-22 03:21:151325 if (response_code != 200 &&
[email protected]dc6f4962009-02-13 01:25:501326 pending_log_text_.length() >
1327 static_cast<size_t>(kUploadLogAvoidRetransmitSize)) {
[email protected]553dba62009-02-24 19:08:231328 UMA_HISTOGRAM_COUNTS("UMA.Large Rejected Log was Discarded",
[email protected]68475e602008-08-22 03:21:151329 static_cast<int>(pending_log_text_.length()));
[email protected]0eb34fee2009-01-21 08:04:381330 discard_log = true;
1331 } else if (response_code == 400) {
1332 // Bad syntax. Retransmission won't work.
[email protected]553dba62009-02-24 19:08:231333 UMA_HISTOGRAM_COUNTS("UMA.Unacceptable_Log_Discarded", state_);
[email protected]0eb34fee2009-01-21 08:04:381334 discard_log = true;
[email protected]68475e602008-08-22 03:21:151335 }
1336
[email protected]0eb34fee2009-01-21 08:04:381337 if (response_code != 200 && !discard_log) {
[email protected]281d2882009-01-20 20:32:421338 LOG(INFO) << "METRICS: transmission attempt returned a failure code: "
1339 << response_code << ". Verify network connectivity";
[email protected]252873ef2008-08-04 21:59:451340 HandleBadResponseCode();
[email protected]0eb34fee2009-01-21 08:04:381341 } else { // Successful receipt (or we are discarding log).
[email protected]281d2882009-01-20 20:32:421342 LOG(INFO) << "METRICS RESPONSE DATA: " << data;
initial.commit09911bf2008-07-26 23:55:291343 switch (state_) {
1344 case INITIAL_LOG_READY:
1345 state_ = SEND_OLD_INITIAL_LOGS;
1346 break;
1347
1348 case SEND_OLD_INITIAL_LOGS:
1349 DCHECK(!unsent_initial_logs_.empty());
1350 unsent_initial_logs_.pop_back();
1351 StoreUnsentLogs();
1352 break;
1353
1354 case SENDING_OLD_LOGS:
1355 DCHECK(!unsent_ongoing_logs_.empty());
1356 unsent_ongoing_logs_.pop_back();
1357 StoreUnsentLogs();
1358 break;
1359
1360 case SENDING_CURRENT_LOGS:
1361 break;
1362
1363 default:
1364 DCHECK(false);
1365 break;
1366 }
[email protected]d01b8732008-10-16 02:18:071367
initial.commit09911bf2008-07-26 23:55:291368 DiscardPendingLog();
[email protected]29be92552008-08-07 22:49:271369 // Since we sent a log, make sure our in-memory state is recorded to disk.
1370 PrefService* local_state = g_browser_process->local_state();
1371 DCHECK(local_state);
1372 if (local_state)
[email protected]6faa0e0d2009-04-28 06:50:361373 local_state->ScheduleSavePersistentPrefs();
[email protected]252873ef2008-08-04 21:59:451374
[email protected]147bbc0b2009-01-06 19:37:401375 // Provide a default (free of exponetial backoff, other varances) in case
1376 // the server does not specify a value.
1377 interlog_duration_ = TimeDelta::FromSeconds(kMinSecondsPerLog);
1378
[email protected]252873ef2008-08-04 21:59:451379 GetSettingsFromResponseData(data);
[email protected]252873ef2008-08-04 21:59:451380 // Override server specified interlog delay if there are unsent logs to
[email protected]29be92552008-08-07 22:49:271381 // transmit.
initial.commit09911bf2008-07-26 23:55:291382 if (unsent_logs()) {
1383 DCHECK(state_ < SENDING_CURRENT_LOGS);
1384 interlog_duration_ = TimeDelta::FromSeconds(kUnsentLogDelay);
initial.commit09911bf2008-07-26 23:55:291385 }
1386 }
[email protected]252873ef2008-08-04 21:59:451387
initial.commit09911bf2008-07-26 23:55:291388 StartLogTransmissionTimer();
1389}
1390
[email protected]252873ef2008-08-04 21:59:451391void MetricsService::HandleBadResponseCode() {
[email protected]281d2882009-01-20 20:32:421392 LOG(INFO) << "Verify your metrics logs are formatted correctly. "
[email protected]79bf0b72009-04-27 21:30:551393 "Verify server is active at " << server_url_;
[email protected]252873ef2008-08-04 21:59:451394 if (!pending_log()) {
[email protected]281d2882009-01-20 20:32:421395 LOG(INFO) << "METRICS: Recorder shutdown during log transmission.";
[email protected]252873ef2008-08-04 21:59:451396 } else {
1397 // Send progressively less frequently.
1398 DCHECK(kBackoff > 1.0);
1399 interlog_duration_ = TimeDelta::FromMicroseconds(
1400 static_cast<int64>(kBackoff * interlog_duration_.InMicroseconds()));
1401
1402 if (kMaxBackoff * TimeDelta::FromSeconds(kMinSecondsPerLog) <
[email protected]cac78842008-11-27 01:02:201403 interlog_duration_) {
[email protected]252873ef2008-08-04 21:59:451404 interlog_duration_ = kMaxBackoff *
1405 TimeDelta::FromSeconds(kMinSecondsPerLog);
[email protected]cac78842008-11-27 01:02:201406 }
[email protected]252873ef2008-08-04 21:59:451407
[email protected]281d2882009-01-20 20:32:421408 LOG(INFO) << "METRICS: transmission retry being scheduled in " <<
[email protected]252873ef2008-08-04 21:59:451409 interlog_duration_.InSeconds() << " seconds for " <<
1410 pending_log_text_;
initial.commit09911bf2008-07-26 23:55:291411 }
initial.commit09911bf2008-07-26 23:55:291412}
1413
[email protected]252873ef2008-08-04 21:59:451414void MetricsService::GetSettingsFromResponseData(const std::string& data) {
1415 // We assume that the file is structured as a block opened by <response>
[email protected]d01b8732008-10-16 02:18:071416 // and that inside response, there is a block opened by tag <chrome_config>
1417 // other tags are ignored for now except the content of <chrome_config>.
[email protected]281d2882009-01-20 20:32:421418 LOG(INFO) << "METRICS: getting settings from response data: " << data;
[email protected]d01b8732008-10-16 02:18:071419
[email protected]252873ef2008-08-04 21:59:451420 int data_size = static_cast<int>(data.size());
1421 if (data_size < 0) {
[email protected]281d2882009-01-20 20:32:421422 LOG(INFO) << "METRICS: server response data bad size: " << data_size <<
[email protected]cac78842008-11-27 01:02:201423 "; aborting extraction of settings";
[email protected]252873ef2008-08-04 21:59:451424 return;
1425 }
[email protected]cac78842008-11-27 01:02:201426 xmlDocPtr doc = xmlReadMemory(data.c_str(), data_size, "", NULL, 0);
[email protected]252873ef2008-08-04 21:59:451427 DCHECK(doc);
[email protected]d01b8732008-10-16 02:18:071428 // If the document is malformed, we just use the settings that were there.
1429 if (!doc) {
[email protected]281d2882009-01-20 20:32:421430 LOG(INFO) << "METRICS: reading xml from server response data failed";
[email protected]252873ef2008-08-04 21:59:451431 return;
[email protected]d01b8732008-10-16 02:18:071432 }
[email protected]252873ef2008-08-04 21:59:451433
[email protected]d01b8732008-10-16 02:18:071434 xmlNodePtr top_node = xmlDocGetRootElement(doc), chrome_config_node = NULL;
1435 // Here, we find the chrome_config node by name.
[email protected]252873ef2008-08-04 21:59:451436 for (xmlNodePtr p = top_node->children; p; p = p->next) {
[email protected]d01b8732008-10-16 02:18:071437 if (xmlStrEqual(p->name, BAD_CAST "chrome_config")) {
1438 chrome_config_node = p;
[email protected]252873ef2008-08-04 21:59:451439 break;
1440 }
1441 }
1442 // If the server data is formatted wrong and there is no
1443 // config node where we expect, we just drop out.
[email protected]d01b8732008-10-16 02:18:071444 if (chrome_config_node != NULL)
1445 GetSettingsFromChromeConfigNode(chrome_config_node);
[email protected]252873ef2008-08-04 21:59:451446 xmlFreeDoc(doc);
1447}
1448
[email protected]d01b8732008-10-16 02:18:071449void MetricsService::GetSettingsFromChromeConfigNode(
1450 xmlNodePtr chrome_config_node) {
1451 // Iterate through all children of the config node.
1452 for (xmlNodePtr current_node = chrome_config_node->children;
1453 current_node;
1454 current_node = current_node->next) {
1455 // If we find the upload tag, we appeal to another function
1456 // GetSettingsFromUploadNode to read all the data in it.
[email protected]252873ef2008-08-04 21:59:451457 if (xmlStrEqual(current_node->name, BAD_CAST "upload")) {
[email protected]d01b8732008-10-16 02:18:071458 GetSettingsFromUploadNode(current_node);
[email protected]252873ef2008-08-04 21:59:451459 continue;
1460 }
1461 }
1462}
initial.commit09911bf2008-07-26 23:55:291463
[email protected]d01b8732008-10-16 02:18:071464void MetricsService::InheritedProperties::OverwriteWhereNeeded(
1465 xmlNodePtr node) {
1466 xmlChar* salt_value = xmlGetProp(node, BAD_CAST "salt");
1467 if (salt_value) // If the property isn't there, xmlGetProp returns NULL.
1468 salt = atoi(reinterpret_cast<char*>(salt_value));
1469 // If the property isn't there, we keep the value the property had before
1470
1471 xmlChar* denominator_value = xmlGetProp(node, BAD_CAST "denominator");
1472 if (denominator_value)
1473 denominator = atoi(reinterpret_cast<char*>(denominator_value));
1474}
1475
1476void MetricsService::GetSettingsFromUploadNode(xmlNodePtr upload_node) {
1477 InheritedProperties props;
1478 GetSettingsFromUploadNodeRecursive(upload_node, props, "", true);
1479}
1480
[email protected]cac78842008-11-27 01:02:201481void MetricsService::GetSettingsFromUploadNodeRecursive(
1482 xmlNodePtr node,
1483 InheritedProperties props,
1484 std::string path_prefix,
1485 bool uploadOn) {
[email protected]d01b8732008-10-16 02:18:071486 props.OverwriteWhereNeeded(node);
1487
1488 // The bool uploadOn is set to true if the data represented by current
1489 // node should be uploaded. This gets inherited in the tree; the children
1490 // of a node that has already been rejected for upload get rejected for
1491 // upload.
1492 uploadOn = uploadOn && NodeProbabilityTest(node, props);
1493
1494 // The path is a / separated list of the node names ancestral to the current
1495 // one. So, if you want to check if the current node has a certain name,
1496 // compare to name. If you want to check if it is a certan tag at a certain
1497 // place in the tree, compare to the whole path.
1498 std::string name = std::string(reinterpret_cast<const char*>(node->name));
1499 std::string path = path_prefix + "/" + name;
1500
1501 if (path == "/upload") {
1502 xmlChar* upload_interval_val = xmlGetProp(node, BAD_CAST "interval");
1503 if (upload_interval_val) {
1504 interlog_duration_ = TimeDelta::FromSeconds(
1505 atoi(reinterpret_cast<char*>(upload_interval_val)));
1506 }
1507
1508 server_permits_upload_ = uploadOn;
1509 }
1510 if (path == "/upload/logs") {
1511 xmlChar* log_event_limit_val = xmlGetProp(node, BAD_CAST "event_limit");
1512 if (log_event_limit_val)
1513 log_event_limit_ = atoi(reinterpret_cast<char*>(log_event_limit_val));
1514 }
1515 if (name == "histogram") {
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 histograms_to_upload_.insert(type);
1521 else
1522 histograms_to_omit_.insert(type);
1523 }
1524 }
1525 if (name == "log") {
1526 xmlChar* type_value = xmlGetProp(node, BAD_CAST "type");
1527 if (type_value) {
1528 std::string type = (reinterpret_cast<char*>(type_value));
1529 if (uploadOn)
1530 logs_to_upload_.insert(type);
1531 else
1532 logs_to_omit_.insert(type);
1533 }
1534 }
1535
1536 // Recursive call. If the node is a leaf i.e. if it ends in a "/>", then it
1537 // doesn't have children, so node->children is NULL, and this loop doesn't
1538 // call (that's how the recursion ends).
1539 for (xmlNodePtr child_node = node->children;
[email protected]cac78842008-11-27 01:02:201540 child_node;
1541 child_node = child_node->next) {
[email protected]d01b8732008-10-16 02:18:071542 GetSettingsFromUploadNodeRecursive(child_node, props, path, uploadOn);
1543 }
1544}
1545
1546bool MetricsService::NodeProbabilityTest(xmlNodePtr node,
[email protected]cac78842008-11-27 01:02:201547 InheritedProperties props) const {
[email protected]d01b8732008-10-16 02:18:071548 // Default value of probability on any node is 1, but recall that
1549 // its parents can already have been rejected for upload.
1550 double probability = 1;
1551
1552 // If a probability is specified in the node, we use it instead.
1553 xmlChar* probability_value = xmlGetProp(node, BAD_CAST "probability");
1554 if (probability_value)
[email protected]0b33f80b2008-12-17 21:34:361555 probability = atoi(reinterpret_cast<char*>(probability_value));
[email protected]d01b8732008-10-16 02:18:071556
1557 return ProbabilityTest(probability, props.salt, props.denominator);
1558}
1559
1560bool MetricsService::ProbabilityTest(double probability,
1561 int salt,
1562 int denominator) const {
1563 // Okay, first we figure out how many of the digits of the
1564 // client_id_ we need in order to make a nice pseudorandomish
1565 // number in the range [0,denominator). Too many digits is
1566 // fine.
[email protected]d01b8732008-10-16 02:18:071567
1568 // n is the length of the client_id_ string
1569 size_t n = client_id_.size();
1570
1571 // idnumber is a positive integer generated from the client_id_.
1572 // It plus salt is going to give us our pseudorandom number.
1573 int idnumber = 0;
1574 const char* client_id_c_str = client_id_.c_str();
1575
1576 // Here we hash the relevant digits of the client_id_
1577 // string somehow to get a big integer idnumber (could be negative
1578 // from wraparound)
1579 int big = 1;
[email protected]5ed73342009-03-18 17:39:431580 int last_pos = n - 1;
1581 for (size_t j = 0; j < n; ++j) {
1582 idnumber += static_cast<int>(client_id_c_str[last_pos - j]) * big;
[email protected]d01b8732008-10-16 02:18:071583 big *= 10;
1584 }
1585
1586 // Mod id number by denominator making sure to get a non-negative
1587 // answer.
[email protected]cac78842008-11-27 01:02:201588 idnumber = ((idnumber % denominator) + denominator) % denominator;
[email protected]d01b8732008-10-16 02:18:071589
[email protected]cac78842008-11-27 01:02:201590 // ((idnumber + salt) % denominator) / denominator is in the range [0,1]
[email protected]d01b8732008-10-16 02:18:071591 // if it's less than probability we call that an affirmative coin
1592 // toss.
[email protected]cac78842008-11-27 01:02:201593 return static_cast<double>((idnumber + salt) % denominator) <
1594 probability * denominator;
[email protected]d01b8732008-10-16 02:18:071595}
1596
initial.commit09911bf2008-07-26 23:55:291597void MetricsService::LogWindowChange(NotificationType type,
1598 const NotificationSource& source,
1599 const NotificationDetails& details) {
[email protected]534e54b2008-08-13 15:40:091600 int controller_id = -1;
1601 uintptr_t window_or_tab = source.map_key();
initial.commit09911bf2008-07-26 23:55:291602 MetricsLog::WindowEventType window_type;
1603
1604 // Note: since we stop all logging when a single OTR session is active, it is
1605 // possible that we start getting notifications about a window that we don't
1606 // know about.
[email protected]534e54b2008-08-13 15:40:091607 if (window_map_.find(window_or_tab) == window_map_.end()) {
1608 controller_id = next_window_id_++;
1609 window_map_[window_or_tab] = controller_id;
initial.commit09911bf2008-07-26 23:55:291610 } else {
[email protected]534e54b2008-08-13 15:40:091611 controller_id = window_map_[window_or_tab];
initial.commit09911bf2008-07-26 23:55:291612 }
[email protected]92745242009-06-12 16:52:211613 DCHECK_NE(controller_id, -1);
initial.commit09911bf2008-07-26 23:55:291614
[email protected]bfd04a62009-02-01 18:16:561615 switch (type.value) {
1616 case NotificationType::TAB_PARENTED:
1617 case NotificationType::BROWSER_OPENED:
initial.commit09911bf2008-07-26 23:55:291618 window_type = MetricsLog::WINDOW_CREATE;
1619 break;
1620
[email protected]bfd04a62009-02-01 18:16:561621 case NotificationType::TAB_CLOSING:
1622 case NotificationType::BROWSER_CLOSED:
[email protected]534e54b2008-08-13 15:40:091623 window_map_.erase(window_map_.find(window_or_tab));
initial.commit09911bf2008-07-26 23:55:291624 window_type = MetricsLog::WINDOW_DESTROY;
1625 break;
1626
1627 default:
1628 NOTREACHED();
[email protected]68d74f02009-02-13 01:36:501629 return;
initial.commit09911bf2008-07-26 23:55:291630 }
1631
[email protected]534e54b2008-08-13 15:40:091632 // TODO(brettw) we should have some kind of ID for the parent.
1633 current_log_->RecordWindowEvent(window_type, controller_id, 0);
initial.commit09911bf2008-07-26 23:55:291634}
1635
1636void MetricsService::LogLoadComplete(NotificationType type,
1637 const NotificationSource& source,
1638 const NotificationDetails& details) {
1639 if (details == NotificationService::NoDetails())
1640 return;
1641
[email protected]68475e602008-08-22 03:21:151642 // TODO(jar): There is a bug causing this to be called too many times, and
1643 // the log overflows. For now, we won't record these events.
[email protected]553dba62009-02-24 19:08:231644 UMA_HISTOGRAM_COUNTS("UMA.LogLoadComplete called", 1);
[email protected]68475e602008-08-22 03:21:151645 return;
1646
initial.commit09911bf2008-07-26 23:55:291647 const Details<LoadNotificationDetails> load_details(details);
[email protected]534e54b2008-08-13 15:40:091648 int controller_id = window_map_[details.map_key()];
1649 current_log_->RecordLoadEvent(controller_id,
initial.commit09911bf2008-07-26 23:55:291650 load_details->url(),
1651 load_details->origin(),
1652 load_details->session_index(),
1653 load_details->load_time());
1654}
1655
[email protected]e73c01972008-08-13 00:18:241656void MetricsService::IncrementPrefValue(const wchar_t* path) {
1657 PrefService* pref = g_browser_process->local_state();
1658 DCHECK(pref);
1659 int value = pref->GetInteger(path);
1660 pref->SetInteger(path, value + 1);
1661}
1662
[email protected]0bb1a622009-03-04 03:22:321663void MetricsService::IncrementLongPrefsValue(const wchar_t* path) {
1664 PrefService* pref = g_browser_process->local_state();
1665 DCHECK(pref);
1666 int64 value = pref->GetInt64(path);
1667 pref->SetInt64(path, value+1);
1668}
1669
initial.commit09911bf2008-07-26 23:55:291670void MetricsService::LogLoadStarted() {
[email protected]e73c01972008-08-13 00:18:241671 IncrementPrefValue(prefs::kStabilityPageLoadCount);
[email protected]0bb1a622009-03-04 03:22:321672 IncrementLongPrefsValue(prefs::kUninstallMetricsPageLoadCount);
[email protected]0b33f80b2008-12-17 21:34:361673 // We need to save the prefs, as page load count is a critical stat, and it
1674 // might be lost due to a crash :-(.
initial.commit09911bf2008-07-26 23:55:291675}
1676
1677void MetricsService::LogRendererInSandbox(bool on_sandbox_desktop) {
1678 PrefService* prefs = g_browser_process->local_state();
1679 DCHECK(prefs);
[email protected]e73c01972008-08-13 00:18:241680 if (on_sandbox_desktop)
1681 IncrementPrefValue(prefs::kSecurityRendererOnSboxDesktop);
1682 else
1683 IncrementPrefValue(prefs::kSecurityRendererOnDefaultDesktop);
initial.commit09911bf2008-07-26 23:55:291684}
1685
1686void MetricsService::LogRendererCrash() {
[email protected]e73c01972008-08-13 00:18:241687 IncrementPrefValue(prefs::kStabilityRendererCrashCount);
initial.commit09911bf2008-07-26 23:55:291688}
1689
1690void MetricsService::LogRendererHang() {
[email protected]e73c01972008-08-13 00:18:241691 IncrementPrefValue(prefs::kStabilityRendererHangCount);
initial.commit09911bf2008-07-26 23:55:291692}
1693
[email protected]a27a9382009-02-11 23:55:101694void MetricsService::LogChildProcessChange(
1695 NotificationType type,
1696 const NotificationSource& source,
1697 const NotificationDetails& details) {
1698 const std::wstring& child_name =
1699 Details<ChildProcessInfo>(details)->name();
initial.commit09911bf2008-07-26 23:55:291700
[email protected]a27a9382009-02-11 23:55:101701 if (child_process_stats_buffer_.find(child_name) ==
1702 child_process_stats_buffer_.end()) {
1703 child_process_stats_buffer_[child_name] = ChildProcessStats();
initial.commit09911bf2008-07-26 23:55:291704 }
1705
[email protected]a27a9382009-02-11 23:55:101706 ChildProcessStats& stats = child_process_stats_buffer_[child_name];
[email protected]bfd04a62009-02-01 18:16:561707 switch (type.value) {
[email protected]a27a9382009-02-11 23:55:101708 case NotificationType::CHILD_PROCESS_HOST_CONNECTED:
initial.commit09911bf2008-07-26 23:55:291709 stats.process_launches++;
1710 break;
1711
[email protected]a27a9382009-02-11 23:55:101712 case NotificationType::CHILD_INSTANCE_CREATED:
initial.commit09911bf2008-07-26 23:55:291713 stats.instances++;
1714 break;
1715
[email protected]a27a9382009-02-11 23:55:101716 case NotificationType::CHILD_PROCESS_CRASHED:
initial.commit09911bf2008-07-26 23:55:291717 stats.process_crashes++;
1718 break;
1719
1720 default:
[email protected]bfd04a62009-02-01 18:16:561721 NOTREACHED() << "Unexpected notification type " << type.value;
initial.commit09911bf2008-07-26 23:55:291722 return;
1723 }
1724}
1725
1726// Recursively counts the number of bookmarks and folders in node.
[email protected]b3c33d462009-06-26 22:29:201727static void CountBookmarks(const BookmarkNode* node,
1728 int* bookmarks,
1729 int* folders) {
[email protected]bd1b96702009-07-08 21:54:141730 if (node->GetType() == BookmarkNode::URL)
initial.commit09911bf2008-07-26 23:55:291731 (*bookmarks)++;
1732 else
1733 (*folders)++;
1734 for (int i = 0; i < node->GetChildCount(); ++i)
1735 CountBookmarks(node->GetChild(i), bookmarks, folders);
1736}
1737
[email protected]b3c33d462009-06-26 22:29:201738void MetricsService::LogBookmarks(const BookmarkNode* node,
initial.commit09911bf2008-07-26 23:55:291739 const wchar_t* num_bookmarks_key,
1740 const wchar_t* num_folders_key) {
1741 DCHECK(node);
1742 int num_bookmarks = 0;
1743 int num_folders = 0;
1744 CountBookmarks(node, &num_bookmarks, &num_folders);
1745 num_folders--; // Don't include the root folder in the count.
1746
1747 PrefService* pref = g_browser_process->local_state();
1748 DCHECK(pref);
1749 pref->SetInteger(num_bookmarks_key, num_bookmarks);
1750 pref->SetInteger(num_folders_key, num_folders);
1751}
1752
[email protected]d8e41ed2008-09-11 15:22:321753void MetricsService::LogBookmarks(BookmarkModel* model) {
initial.commit09911bf2008-07-26 23:55:291754 DCHECK(model);
1755 LogBookmarks(model->GetBookmarkBarNode(),
1756 prefs::kNumBookmarksOnBookmarkBar,
1757 prefs::kNumFoldersOnBookmarkBar);
1758 LogBookmarks(model->other_node(),
1759 prefs::kNumBookmarksInOtherBookmarkFolder,
1760 prefs::kNumFoldersInOtherBookmarkFolder);
1761 ScheduleNextStateSave();
1762}
1763
1764void MetricsService::LogKeywords(const TemplateURLModel* url_model) {
1765 DCHECK(url_model);
1766
1767 PrefService* pref = g_browser_process->local_state();
1768 DCHECK(pref);
1769 pref->SetInteger(prefs::kNumKeywords,
1770 static_cast<int>(url_model->GetTemplateURLs().size()));
1771 ScheduleNextStateSave();
1772}
1773
1774void MetricsService::RecordPluginChanges(PrefService* pref) {
1775 ListValue* plugins = pref->GetMutableList(prefs::kStabilityPluginStats);
1776 DCHECK(plugins);
1777
1778 for (ListValue::iterator value_iter = plugins->begin();
1779 value_iter != plugins->end(); ++value_iter) {
1780 if (!(*value_iter)->IsType(Value::TYPE_DICTIONARY)) {
1781 NOTREACHED();
1782 continue;
1783 }
1784
1785 DictionaryValue* plugin_dict = static_cast<DictionaryValue*>(*value_iter);
[email protected]8e50b602009-03-03 22:59:431786 std::wstring plugin_name;
1787 plugin_dict->GetString(prefs::kStabilityPluginName, &plugin_name);
[email protected]6470ee8f2009-03-03 20:46:401788 if (plugin_name.empty()) {
initial.commit09911bf2008-07-26 23:55:291789 NOTREACHED();
1790 continue;
1791 }
1792
[email protected]8e50b602009-03-03 22:59:431793 if (child_process_stats_buffer_.find(plugin_name) ==
[email protected]a27a9382009-02-11 23:55:101794 child_process_stats_buffer_.end())
initial.commit09911bf2008-07-26 23:55:291795 continue;
1796
[email protected]8e50b602009-03-03 22:59:431797 ChildProcessStats stats = child_process_stats_buffer_[plugin_name];
initial.commit09911bf2008-07-26 23:55:291798 if (stats.process_launches) {
1799 int launches = 0;
[email protected]8e50b602009-03-03 22:59:431800 plugin_dict->GetInteger(prefs::kStabilityPluginLaunches, &launches);
initial.commit09911bf2008-07-26 23:55:291801 launches += stats.process_launches;
[email protected]8e50b602009-03-03 22:59:431802 plugin_dict->SetInteger(prefs::kStabilityPluginLaunches, launches);
initial.commit09911bf2008-07-26 23:55:291803 }
1804 if (stats.process_crashes) {
1805 int crashes = 0;
[email protected]8e50b602009-03-03 22:59:431806 plugin_dict->GetInteger(prefs::kStabilityPluginCrashes, &crashes);
initial.commit09911bf2008-07-26 23:55:291807 crashes += stats.process_crashes;
[email protected]8e50b602009-03-03 22:59:431808 plugin_dict->SetInteger(prefs::kStabilityPluginCrashes, crashes);
initial.commit09911bf2008-07-26 23:55:291809 }
1810 if (stats.instances) {
1811 int instances = 0;
[email protected]8e50b602009-03-03 22:59:431812 plugin_dict->GetInteger(prefs::kStabilityPluginInstances, &instances);
initial.commit09911bf2008-07-26 23:55:291813 instances += stats.instances;
[email protected]8e50b602009-03-03 22:59:431814 plugin_dict->SetInteger(prefs::kStabilityPluginInstances, instances);
initial.commit09911bf2008-07-26 23:55:291815 }
1816
[email protected]8e50b602009-03-03 22:59:431817 child_process_stats_buffer_.erase(plugin_name);
initial.commit09911bf2008-07-26 23:55:291818 }
1819
1820 // Now go through and add dictionaries for plugins that didn't already have
1821 // reports in Local State.
[email protected]a27a9382009-02-11 23:55:101822 for (std::map<std::wstring, ChildProcessStats>::iterator cache_iter =
1823 child_process_stats_buffer_.begin();
1824 cache_iter != child_process_stats_buffer_.end(); ++cache_iter) {
1825 std::wstring plugin_name = cache_iter->first;
1826 ChildProcessStats stats = cache_iter->second;
initial.commit09911bf2008-07-26 23:55:291827 DictionaryValue* plugin_dict = new DictionaryValue;
1828
[email protected]8e50b602009-03-03 22:59:431829 plugin_dict->SetString(prefs::kStabilityPluginName, plugin_name);
1830 plugin_dict->SetInteger(prefs::kStabilityPluginLaunches,
initial.commit09911bf2008-07-26 23:55:291831 stats.process_launches);
[email protected]8e50b602009-03-03 22:59:431832 plugin_dict->SetInteger(prefs::kStabilityPluginCrashes,
initial.commit09911bf2008-07-26 23:55:291833 stats.process_crashes);
[email protected]8e50b602009-03-03 22:59:431834 plugin_dict->SetInteger(prefs::kStabilityPluginInstances,
initial.commit09911bf2008-07-26 23:55:291835 stats.instances);
1836 plugins->Append(plugin_dict);
1837 }
[email protected]a27a9382009-02-11 23:55:101838 child_process_stats_buffer_.clear();
initial.commit09911bf2008-07-26 23:55:291839}
1840
1841bool MetricsService::CanLogNotification(NotificationType type,
1842 const NotificationSource& source,
1843 const NotificationDetails& details) {
1844 // We simply don't log anything to UMA if there is a single off the record
1845 // session visible. The problem is that we always notify using the orginal
1846 // profile in order to simplify notification processing.
1847 return !BrowserList::IsOffTheRecordSessionActive();
1848}
1849
1850void MetricsService::RecordBooleanPrefValue(const wchar_t* path, bool value) {
1851 DCHECK(IsSingleThreaded());
1852
1853 PrefService* pref = g_browser_process->local_state();
1854 DCHECK(pref);
1855
1856 pref->SetBoolean(path, value);
1857 RecordCurrentState(pref);
1858}
1859
1860void MetricsService::RecordCurrentState(PrefService* pref) {
[email protected]0bb1a622009-03-04 03:22:321861 pref->SetInt64(prefs::kStabilityLastTimestampSec, Time::Now().ToTimeT());
initial.commit09911bf2008-07-26 23:55:291862
1863 RecordPluginChanges(pref);
1864}
1865
1866void MetricsService::RecordCurrentHistograms() {
1867 DCHECK(current_log_);
1868
1869 StatisticsRecorder::Histograms histograms;
1870 StatisticsRecorder::GetHistograms(&histograms);
1871 for (StatisticsRecorder::Histograms::iterator it = histograms.begin();
1872 histograms.end() != it;
[email protected]cac78842008-11-27 01:02:201873 ++it) {
initial.commit09911bf2008-07-26 23:55:291874 if ((*it)->flags() & kUmaTargetedHistogramFlag)
[email protected]0b33f80b2008-12-17 21:34:361875 // TODO(petersont): Only record historgrams if they are not precluded by
1876 // the UMA response data.
[email protected]d01b8732008-10-16 02:18:071877 // Bug http://code.google.com/p/chromium/issues/detail?id=2739.
initial.commit09911bf2008-07-26 23:55:291878 RecordHistogram(**it);
1879 }
1880}
1881
1882void MetricsService::RecordHistogram(const Histogram& histogram) {
1883 // Get up-to-date snapshot of sample stats.
1884 Histogram::SampleSet snapshot;
1885 histogram.SnapshotSample(&snapshot);
1886
1887 const std::string& histogram_name = histogram.histogram_name();
1888
1889 // Find the already sent stats, or create an empty set.
1890 LoggedSampleMap::iterator it = logged_samples_.find(histogram_name);
1891 Histogram::SampleSet* already_logged;
1892 if (logged_samples_.end() == it) {
1893 // Add new entry
1894 already_logged = &logged_samples_[histogram.histogram_name()];
1895 already_logged->Resize(histogram); // Complete initialization.
1896 } else {
1897 already_logged = &(it->second);
1898 // Deduct any stats we've already logged from our snapshot.
1899 snapshot.Subtract(*already_logged);
1900 }
1901
1902 // snapshot now contains only a delta to what we've already_logged.
1903
1904 if (snapshot.TotalCount() > 0) {
1905 current_log_->RecordHistogramDelta(histogram, snapshot);
1906 // Add new data into our running total.
1907 already_logged->Add(snapshot);
1908 }
1909}
1910
1911void MetricsService::AddProfileMetric(Profile* profile,
1912 const std::wstring& key,
1913 int value) {
1914 // Restriction of types is needed for writing values. See
1915 // MetricsLog::WriteProfileMetrics.
1916 DCHECK(profile && !key.empty());
1917 PrefService* prefs = g_browser_process->local_state();
1918 DCHECK(prefs);
1919
1920 // Key is stored in prefs, which interpret '.'s as paths. As such, key
1921 // shouldn't have any '.'s in it.
1922 DCHECK(key.find(L'.') == std::wstring::npos);
1923 // The id is most likely an email address. We shouldn't send it to the server.
1924 const std::wstring id_hash =
1925 UTF8ToWide(MetricsLog::CreateBase64Hash(WideToUTF8(profile->GetID())));
1926 DCHECK(id_hash.find('.') == std::string::npos);
1927
1928 DictionaryValue* prof_prefs = prefs->GetMutableDictionary(
1929 prefs::kProfileMetrics);
1930 DCHECK(prof_prefs);
1931 const std::wstring pref_key = std::wstring(prefs::kProfilePrefix) + id_hash +
1932 L"." + key;
[email protected]8e50b602009-03-03 22:59:431933 prof_prefs->SetInteger(pref_key.c_str(), value);
initial.commit09911bf2008-07-26 23:55:291934}
1935
1936static bool IsSingleThreaded() {
[email protected]dc6f4962009-02-13 01:25:501937 static PlatformThreadId thread_id = 0;
initial.commit09911bf2008-07-26 23:55:291938 if (!thread_id)
[email protected]dc6f4962009-02-13 01:25:501939 thread_id = PlatformThread::CurrentId();
1940 return PlatformThread::CurrentId() == thread_id;
initial.commit09911bf2008-07-26 23:55:291941}