blob: 858032afbc11bb290af4f207335067d019e0049d [file] [log] [blame]
license.botbf09a502008-08-24 00:55:551// Copyright (c) 2006-2008 The Chromium Authors. All rights reserved.
2// Use of this source code is governed by a BSD-style license that can be
3// found in the LICENSE file.
initial.commit09911bf2008-07-26 23:55:294
5
6
7//------------------------------------------------------------------------------
8// Description of the life cycle of a instance of MetricsService.
9//
10// OVERVIEW
11//
12// A MetricsService instance is typically created at application startup. It
13// is the central controller for the acquisition of log data, and the automatic
14// transmission of that log data to an external server. Its major job is to
15// manage logs, grouping them for transmission, and transmitting them. As part
16// of its grouping, MS finalizes logs by including some just-in-time gathered
17// memory statistics, snapshotting the current stats of numerous histograms,
18// closing the logs, translating to XML text, and compressing the results for
19// transmission. Transmission includes submitting a compressed log as data in a
[email protected]281d2882009-01-20 20:32:4220// URL-post, and retransmitting (or retaining at process termination) if the
initial.commit09911bf2008-07-26 23:55:2921// attempted transmission failed. Retention across process terminations is done
22// using the the PrefServices facilities. The format for the retained
23// logs (ones that never got transmitted) is always the uncompressed textual
24// representation.
25//
[email protected]281d2882009-01-20 20:32:4226// Logs fall into one of two categories: "initial logs," and "ongoing logs."
27// There is at most one initial log sent for each complete run of the chromium
initial.commit09911bf2008-07-26 23:55:2928// product (from startup, to browser shutdown). An initial log is generally
29// transmitted some short time (1 minute?) after startup, and includes stats
30// such as recent crash info, the number and types of plugins, etc. The
[email protected]281d2882009-01-20 20:32:4231// external server's response to the initial log conceptually tells this MS if
32// it should continue transmitting logs (during this session). The server
33// response can actually be much more detailed, and always includes (at a
34// minimum) how often additional ongoing logs should be sent.
initial.commit09911bf2008-07-26 23:55:2935//
36// After the above initial log, a series of ongoing logs will be transmitted.
37// The first ongoing log actually begins to accumulate information stating when
38// the MS was first constructed. Note that even though the initial log is
39// commonly sent a full minute after startup, the initial log does not include
40// much in the way of user stats. The most common interlog period (delay)
[email protected]0b33f80b2008-12-17 21:34:3641// is 20 minutes. That time period starts when the first user action causes a
initial.commit09911bf2008-07-26 23:55:2942// logging event. This means that if there is no user action, there may be long
[email protected]281d2882009-01-20 20:32:4243// periods without any (ongoing) log transmissions. Ongoing logs typically
initial.commit09911bf2008-07-26 23:55:2944// contain very detailed records of user activities (ex: opened tab, closed
45// tab, fetched URL, maximized window, etc.) In addition, just before an
46// ongoing log is closed out, a call is made to gather memory statistics. Those
47// memory statistics are deposited into a histogram, and the log finalization
48// code is then called. In the finalization, a call to a Histogram server
49// acquires a list of all local histograms that have been flagged for upload
[email protected]281d2882009-01-20 20:32:4250// to the UMA server. The finalization also acquires a the most recent number
51// of page loads, along with any counts of renderer or plugin crashes.
initial.commit09911bf2008-07-26 23:55:2952//
53// When the browser shuts down, there will typically be a fragment of an ongoing
54// log that has not yet been transmitted. At shutdown time, that fragment
55// is closed (including snapshotting histograms), and converted to text. Note
56// that memory stats are not gathered during shutdown, as gathering *might* be
57// too time consuming. The textual representation of the fragment of the
58// ongoing log is then stored persistently as a string in the PrefServices, for
59// potential transmission during a future run of the product.
60//
61// There are two slightly abnormal shutdown conditions. There is a
62// "disconnected scenario," and a "really fast startup and shutdown" scenario.
63// In the "never connected" situation, the user has (during the running of the
64// process) never established an internet connection. As a result, attempts to
65// transmit the initial log have failed, and a lot(?) of data has accumulated in
66// the ongoing log (which didn't yet get closed, because there was never even a
67// contemplation of sending it). There is also a kindred "lost connection"
68// situation, where a loss of connection prevented an ongoing log from being
69// transmitted, and a (still open) log was stuck accumulating a lot(?) of data,
70// while the earlier log retried its transmission. In both of these
71// disconnected situations, two logs need to be, and are, persistently stored
72// for future transmission.
73//
74// The other unusual shutdown condition, termed "really fast startup and
75// shutdown," involves the deliberate user termination of the process before
76// the initial log is even formed or transmitted. In that situation, no logging
77// is done, but the historical crash statistics remain (unlogged) for inclusion
78// in a future run's initial log. (i.e., we don't lose crash stats).
79//
80// With the above overview, we can now describe the state machine's various
81// stats, based on the State enum specified in the state_ member. Those states
82// are:
83//
84// INITIALIZED, // Constructor was called.
[email protected]28ab7f92009-01-06 21:39:0485// PLUGIN_LIST_REQUESTED, // Waiting for plugin list to be loaded.
initial.commit09911bf2008-07-26 23:55:2986// PLUGIN_LIST_ARRIVED, // Waiting for timer to send initial log.
87// INITIAL_LOG_READY, // Initial log generated, and waiting for reply.
88// SEND_OLD_INITIAL_LOGS, // Sending unsent logs from previous session.
89// SENDING_OLD_LOGS, // Sending unsent logs from previous session.
90// SENDING_CURRENT_LOGS, // Sending standard current logs as they accrue.
91//
92// In more detail, we have:
93//
94// INITIALIZED, // Constructor was called.
95// The MS has been constructed, but has taken no actions to compose the
96// initial log.
97//
[email protected]28ab7f92009-01-06 21:39:0498// PLUGIN_LIST_REQUESTED, // Waiting for plugin list to be loaded.
initial.commit09911bf2008-07-26 23:55:2999// Typically about 30 seconds after startup, a task is sent to a second thread
100// to get the list of plugins. That task will (when complete) make an async
101// callback (via a Task) to indicate the completion.
102//
103// PLUGIN_LIST_ARRIVED, // Waiting for timer to send initial log.
104// The callback has arrived, and it is now possible for an initial log to be
105// created. This callback typically arrives back less than one second after
106// the task is dispatched.
107//
108// INITIAL_LOG_READY, // Initial log generated, and waiting for reply.
109// This state is entered only after an initial log has been composed, and
110// prepared for transmission. It is also the case that any previously unsent
111// logs have been loaded into instance variables for possible transmission.
112//
113// SEND_OLD_INITIAL_LOGS, // Sending unsent logs from previous session.
114// This state indicates that the initial log for this session has been
115// successfully sent and it is now time to send any "initial logs" that were
116// saved from previous sessions. Most commonly, there are none, but all old
117// logs that were "initial logs" must be sent before this state is exited.
118//
119// SENDING_OLD_LOGS, // Sending unsent logs from previous session.
120// This state indicates that there are no more unsent initial logs, and now any
121// ongoing logs from previous sessions should be transmitted. All such logs
122// will be transmitted before exiting this state, and proceeding with ongoing
123// logs from the current session (see next state).
124//
125// SENDING_CURRENT_LOGS, // Sending standard current logs as they accrue.
[email protected]0b33f80b2008-12-17 21:34:36126// Current logs are being accumulated. Typically every 20 minutes a log is
initial.commit09911bf2008-07-26 23:55:29127// closed and finalized for transmission, at the same time as a new log is
128// started.
129//
130// The progression through the above states is simple, and sequential, in the
131// most common use cases. States proceed from INITIAL to SENDING_CURRENT_LOGS,
132// and remain in the latter until shutdown.
133//
134// The one unusual case is when the user asks that we stop logging. When that
135// happens, any pending (transmission in progress) log is pushed into the list
136// of old unsent logs (the appropriate list, depending on whether it is an
137// initial log, or an ongoing log). An addition, any log that is currently
138// accumulating is also finalized, and pushed into the unsent log list. With
[email protected]281d2882009-01-20 20:32:42139// those pushes performed, we regress back to the SEND_OLD_INITIAL_LOGS state in
initial.commit09911bf2008-07-26 23:55:29140// case the user enables log recording again during this session. This way
141// anything we have "pushed back" will be sent automatically if/when we progress
142// back to SENDING_CURRENT_LOG state.
143//
144// Also note that whenever the member variables containing unsent logs are
145// modified (i.e., when we send an old log), we mirror the list of logs into
146// the PrefServices. This ensures that IF we crash, we won't start up and
147// retransmit our old logs again.
148//
149// Due to race conditions, it is always possible that a log file could be sent
150// twice. For example, if a log file is sent, but not yet acknowledged by
151// the external server, and the user shuts down, then a copy of the log may be
152// saved for re-transmission. These duplicates could be filtered out server
[email protected]281d2882009-01-20 20:32:42153// side, but are not expected to be a significant problem.
initial.commit09911bf2008-07-26 23:55:29154//
155//
156//------------------------------------------------------------------------------
157
[email protected]40bcc302009-03-02 20:50:39158#include "chrome/browser/metrics/metrics_service.h"
159
[email protected]dc6f4962009-02-13 01:25:50160#if defined(OS_WIN)
initial.commit09911bf2008-07-26 23:55:29161#include <windows.h>
[email protected]40bcc302009-03-02 20:50:39162#include <objbase.h>
[email protected]dc6f4962009-02-13 01:25:50163#endif
initial.commit09911bf2008-07-26 23:55:29164
[email protected]690a99c2009-01-06 16:48:45165#include "base/file_path.h"
initial.commit09911bf2008-07-26 23:55:29166#include "base/histogram.h"
167#include "base/path_service.h"
[email protected]dc6f4962009-02-13 01:25:50168#include "base/platform_thread.h"
initial.commit09911bf2008-07-26 23:55:29169#include "base/string_util.h"
170#include "base/task.h"
[email protected]d8e41ed2008-09-11 15:22:32171#include "chrome/browser/bookmarks/bookmark_model.h"
initial.commit09911bf2008-07-26 23:55:29172#include "chrome/browser/browser.h"
173#include "chrome/browser/browser_list.h"
174#include "chrome/browser/browser_process.h"
175#include "chrome/browser/load_notification_details.h"
176#include "chrome/browser/memory_details.h"
[email protected]fd49e2d2009-02-20 17:21:30177#include "chrome/browser/plugin_service.h"
initial.commit09911bf2008-07-26 23:55:29178#include "chrome/browser/profile.h"
[email protected]8c8657d62009-01-16 18:31:26179#include "chrome/browser/renderer_host/render_process_host.h"
[email protected]d54e03a52009-01-16 00:31:04180#include "chrome/browser/search_engines/template_url.h"
181#include "chrome/browser/search_engines/template_url_model.h"
[email protected]a27a9382009-02-11 23:55:10182#include "chrome/common/child_process_info.h"
initial.commit09911bf2008-07-26 23:55:29183#include "chrome/common/chrome_paths.h"
[email protected]252873ef2008-08-04 21:59:45184#include "chrome/common/libxml_utils.h"
[email protected]bfd04a62009-02-01 18:16:56185#include "chrome/common/notification_service.h"
initial.commit09911bf2008-07-26 23:55:29186#include "chrome/common/pref_names.h"
187#include "chrome/common/pref_service.h"
[email protected]e09ba552009-02-05 03:26:29188#include "chrome/common/render_messages.h"
initial.commit09911bf2008-07-26 23:55:29189#include "googleurl/src/gurl.h"
190#include "net/base/load_flags.h"
191#include "third_party/bzip2/bzlib.h"
192
[email protected]dc6f4962009-02-13 01:25:50193#if defined(OS_POSIX)
194// TODO(port): Move these headers above as they are ported.
195#include "chrome/common/temp_scaffolding_stubs.h"
196#else
[email protected]dc6f4962009-02-13 01:25:50197#include "chrome/installer/util/google_update_settings.h"
198#endif
199
[email protected]e1acf6f2008-10-27 20:43:33200using base::Time;
201using base::TimeDelta;
202
initial.commit09911bf2008-07-26 23:55:29203// Check to see that we're being called on only one thread.
204static bool IsSingleThreaded();
205
206static const char kMetricsURL[] =
[email protected]0acdfc42009-01-30 01:13:22207 "https://clients4.google.com/firefox/metrics/collect";
initial.commit09911bf2008-07-26 23:55:29208
209static const char kMetricsType[] = "application/vnd.mozilla.metrics.bz2";
210
211// The delay, in seconds, after startup before sending the first log message.
[email protected]252873ef2008-08-04 21:59:45212static const int kInitialInterlogDuration = 60; // one minute
213
214// The default maximum number of events in a log uploaded to the UMA server.
[email protected]0b33f80b2008-12-17 21:34:36215static const int kInitialEventLimit = 2400;
[email protected]68475e602008-08-22 03:21:15216
217// If an upload fails, and the transmission was over this byte count, then we
218// will discard the log, and not try to retransmit it. We also don't persist
219// the log to the prefs for transmission during the next chrome session if this
220// limit is exceeded.
221static const int kUploadLogAvoidRetransmitSize = 50000;
initial.commit09911bf2008-07-26 23:55:29222
223// When we have logs from previous Chrome sessions to send, how long should we
224// delay (in seconds) between each log transmission.
225static const int kUnsentLogDelay = 15; // 15 seconds
226
227// Minimum time a log typically exists before sending, in seconds.
228// This number is supplied by the server, but until we parse it out of a server
229// response, we use this duration to specify how long we should wait before
230// sending the next log. If the channel is busy, such as when there is a
231// failure during an attempt to transmit a previous log, then a log may wait
232// (and continue to accrue now log entries) for a much greater period of time.
[email protected]0eb34fee2009-01-21 08:04:38233static const int kMinSecondsPerLog = 20 * 60; // Twenty minutes.
initial.commit09911bf2008-07-26 23:55:29234
initial.commit09911bf2008-07-26 23:55:29235// When we don't succeed at transmitting a log to a server, we progressively
236// wait longer and longer before sending the next log. This backoff process
237// help reduce load on the server, and makes the amount of backoff vary between
238// clients so that a collision (server overload?) on retransmit is less likely.
239// The following is the constant we use to expand that inter-log duration.
240static const double kBackoff = 1.1;
241// We limit the maximum backoff to be no greater than some multiple of the
242// default kMinSecondsPerLog. The following is that maximum ratio.
243static const int kMaxBackoff = 10;
244
245// Interval, in seconds, between state saves.
246static const int kSaveStateInterval = 5 * 60; // five minutes
247
248// The number of "initial" logs we're willing to save, and hope to send during
249// a future Chrome session. Initial logs contain crash stats, and are pretty
250// small.
251static const size_t kMaxInitialLogsPersisted = 20;
252
253// The number of ongoing logs we're willing to save persistently, and hope to
[email protected]281d2882009-01-20 20:32:42254// send during a this or future sessions. Note that each log may be pretty
initial.commit09911bf2008-07-26 23:55:29255// large, as presumably the related "initial" log wasn't sent (probably nothing
256// was, as the user was probably off-line). As a result, the log probably kept
257// accumulating while the "initial" log was stalled (pending_), and couldn't be
258// sent. As a result, we don't want to save too many of these mega-logs.
259// A "standard shutdown" will create a small log, including just the data that
260// was not yet been transmitted, and that is normal (to have exactly one
261// ongoing_log_ at startup).
[email protected]281d2882009-01-20 20:32:42262static const size_t kMaxOngoingLogsPersisted = 8;
initial.commit09911bf2008-07-26 23:55:29263
264
265// Handles asynchronous fetching of memory details.
266// Will run the provided task after finished.
267class MetricsMemoryDetails : public MemoryDetails {
268 public:
269 explicit MetricsMemoryDetails(Task* completion) : completion_(completion) {}
270
271 virtual void OnDetailsAvailable() {
272 MessageLoop::current()->PostTask(FROM_HERE, completion_);
273 }
274
275 private:
276 Task* completion_;
277 DISALLOW_EVIL_CONSTRUCTORS(MetricsMemoryDetails);
278};
279
280class MetricsService::GetPluginListTaskComplete : public Task {
281 virtual void Run() {
282 g_browser_process->metrics_service()->OnGetPluginListTaskComplete();
283 }
284};
285
286class MetricsService::GetPluginListTask : public Task {
287 public:
288 explicit GetPluginListTask(MessageLoop* callback_loop)
289 : callback_loop_(callback_loop) {}
290
291 virtual void Run() {
292 std::vector<WebPluginInfo> plugins;
293 PluginService::GetInstance()->GetPlugins(false, &plugins);
294
295 callback_loop_->PostTask(FROM_HERE, new GetPluginListTaskComplete());
296 }
297
298 private:
299 MessageLoop* callback_loop_;
300};
301
302// static
303void MetricsService::RegisterPrefs(PrefService* local_state) {
304 DCHECK(IsSingleThreaded());
305 local_state->RegisterStringPref(prefs::kMetricsClientID, L"");
[email protected]0bb1a622009-03-04 03:22:32306 local_state->RegisterInt64Pref(prefs::kMetricsClientIDTimestamp, 0);
307 local_state->RegisterInt64Pref(prefs::kStabilityLaunchTimeSec, 0);
308 local_state->RegisterInt64Pref(prefs::kStabilityLastTimestampSec, 0);
309 local_state->RegisterInt64Pref(prefs::kStabilityUptimeSec, 0);
[email protected]541f77922009-02-23 21:14:38310 local_state->RegisterStringPref(prefs::kStabilityStatsVersion, L"");
initial.commit09911bf2008-07-26 23:55:29311 local_state->RegisterBooleanPref(prefs::kStabilityExitedCleanly, true);
312 local_state->RegisterBooleanPref(prefs::kStabilitySessionEndCompleted, true);
313 local_state->RegisterIntegerPref(prefs::kMetricsSessionID, -1);
314 local_state->RegisterIntegerPref(prefs::kStabilityLaunchCount, 0);
315 local_state->RegisterIntegerPref(prefs::kStabilityCrashCount, 0);
316 local_state->RegisterIntegerPref(prefs::kStabilityIncompleteSessionEndCount,
317 0);
318 local_state->RegisterIntegerPref(prefs::kStabilityPageLoadCount, 0);
319 local_state->RegisterIntegerPref(prefs::kSecurityRendererOnSboxDesktop, 0);
320 local_state->RegisterIntegerPref(prefs::kSecurityRendererOnDefaultDesktop, 0);
321 local_state->RegisterIntegerPref(prefs::kStabilityRendererCrashCount, 0);
322 local_state->RegisterIntegerPref(prefs::kStabilityRendererHangCount, 0);
[email protected]e73c01972008-08-13 00:18:24323 local_state->RegisterIntegerPref(prefs::kStabilityBreakpadRegistrationFail,
324 0);
325 local_state->RegisterIntegerPref(prefs::kStabilityBreakpadRegistrationSuccess,
326 0);
327 local_state->RegisterIntegerPref(prefs::kStabilityDebuggerPresent, 0);
328 local_state->RegisterIntegerPref(prefs::kStabilityDebuggerNotPresent, 0);
329
initial.commit09911bf2008-07-26 23:55:29330 local_state->RegisterDictionaryPref(prefs::kProfileMetrics);
331 local_state->RegisterIntegerPref(prefs::kNumBookmarksOnBookmarkBar, 0);
332 local_state->RegisterIntegerPref(prefs::kNumFoldersOnBookmarkBar, 0);
333 local_state->RegisterIntegerPref(prefs::kNumBookmarksInOtherBookmarkFolder,
334 0);
335 local_state->RegisterIntegerPref(prefs::kNumFoldersInOtherBookmarkFolder, 0);
336 local_state->RegisterIntegerPref(prefs::kNumKeywords, 0);
337 local_state->RegisterListPref(prefs::kMetricsInitialLogs);
338 local_state->RegisterListPref(prefs::kMetricsOngoingLogs);
[email protected]0bb1a622009-03-04 03:22:32339
340 local_state->RegisterInt64Pref(prefs::kUninstallMetricsPageLoadCount, 0);
341 local_state->RegisterInt64Pref(prefs::kUninstallLaunchCount, 0);
342 local_state->RegisterInt64Pref(prefs::kUninstallMetricsUptimeSec, 0);
343 local_state->RegisterInt64Pref(prefs::kUninstallLastLaunchTimeSec, 0);
344 local_state->RegisterInt64Pref(prefs::kUninstallLastObservedRunTimeSec, 0);
initial.commit09911bf2008-07-26 23:55:29345}
346
[email protected]541f77922009-02-23 21:14:38347// static
348void MetricsService::DiscardOldStabilityStats(PrefService* local_state) {
349 local_state->SetBoolean(prefs::kStabilityExitedCleanly, true);
350
351 local_state->SetInteger(prefs::kStabilityIncompleteSessionEndCount, 0);
352 local_state->SetInteger(prefs::kStabilityBreakpadRegistrationSuccess, 0);
353 local_state->SetInteger(prefs::kStabilityBreakpadRegistrationFail, 0);
354 local_state->SetInteger(prefs::kStabilityDebuggerPresent, 0);
355 local_state->SetInteger(prefs::kStabilityDebuggerNotPresent, 0);
356
357 local_state->SetInteger(prefs::kStabilityLaunchCount, 0);
358 local_state->SetInteger(prefs::kStabilityCrashCount, 0);
359
360 local_state->SetInteger(prefs::kStabilityPageLoadCount, 0);
361 local_state->SetInteger(prefs::kStabilityRendererCrashCount, 0);
362 local_state->SetInteger(prefs::kStabilityRendererHangCount, 0);
363
364 local_state->SetInteger(prefs::kSecurityRendererOnSboxDesktop, 0);
365 local_state->SetInteger(prefs::kSecurityRendererOnDefaultDesktop, 0);
366
367 local_state->SetString(prefs::kStabilityUptimeSec, L"0");
368
369 local_state->ClearPref(prefs::kStabilityPluginStats);
370}
371
initial.commit09911bf2008-07-26 23:55:29372MetricsService::MetricsService()
[email protected]d01b8732008-10-16 02:18:07373 : recording_active_(false),
374 reporting_active_(false),
375 user_permits_upload_(false),
376 server_permits_upload_(true),
377 state_(INITIALIZED),
initial.commit09911bf2008-07-26 23:55:29378 pending_log_(NULL),
379 pending_log_text_(""),
380 current_fetch_(NULL),
381 current_log_(NULL),
[email protected]d01b8732008-10-16 02:18:07382 idle_since_last_transmission_(false),
initial.commit09911bf2008-07-26 23:55:29383 next_window_id_(0),
[email protected]40bcc302009-03-02 20:50:39384 ALLOW_THIS_IN_INITIALIZER_LIST(log_sender_factory_(this)),
385 ALLOW_THIS_IN_INITIALIZER_LIST(state_saver_factory_(this)),
initial.commit09911bf2008-07-26 23:55:29386 logged_samples_(),
[email protected]252873ef2008-08-04 21:59:45387 interlog_duration_(TimeDelta::FromSeconds(kInitialInterlogDuration)),
[email protected]d01b8732008-10-16 02:18:07388 log_event_limit_(kInitialEventLimit),
initial.commit09911bf2008-07-26 23:55:29389 timer_pending_(false) {
390 DCHECK(IsSingleThreaded());
391 InitializeMetricsState();
392}
393
394MetricsService::~MetricsService() {
395 SetRecording(false);
[email protected]d8bc79bf2009-01-28 01:17:58396 if (pending_log_) {
397 delete pending_log_;
398 pending_log_ = NULL;
399 }
400 if (current_log_) {
401 delete current_log_;
402 current_log_ = NULL;
403 }
initial.commit09911bf2008-07-26 23:55:29404}
405
[email protected]d01b8732008-10-16 02:18:07406void MetricsService::SetUserPermitsUpload(bool enabled) {
407 HandleIdleSinceLastTransmission(false);
408 user_permits_upload_ = enabled;
409}
410
411void MetricsService::Start() {
412 SetRecording(true);
413 SetReporting(true);
414}
415
416void MetricsService::StartRecordingOnly() {
417 SetRecording(true);
418 SetReporting(false);
419}
420
421void MetricsService::Stop() {
422 SetReporting(false);
423 SetRecording(false);
424}
425
initial.commit09911bf2008-07-26 23:55:29426void MetricsService::SetRecording(bool enabled) {
427 DCHECK(IsSingleThreaded());
428
[email protected]d01b8732008-10-16 02:18:07429 if (enabled == recording_active_)
initial.commit09911bf2008-07-26 23:55:29430 return;
431
432 if (enabled) {
[email protected]b0c819f2009-03-08 04:52:15433 if (client_id_.empty()) {
434 PrefService* pref = g_browser_process->local_state();
435 DCHECK(pref);
436 client_id_ = WideToUTF8(pref->GetString(prefs::kMetricsClientID));
437 if (client_id_.empty()) {
438 client_id_ = GenerateClientID();
439 pref->SetString(prefs::kMetricsClientID, UTF8ToWide(client_id_));
440
441 // Might as well make a note of how long this ID has existed
442 pref->SetString(prefs::kMetricsClientIDTimestamp,
443 Int64ToWString(Time::Now().ToTimeT()));
444 }
445 }
initial.commit09911bf2008-07-26 23:55:29446 StartRecording();
447 ListenerRegistration(true);
448 } else {
449 // Turn off all observers.
450 ListenerRegistration(false);
451 PushPendingLogsToUnsentLists();
452 DCHECK(!pending_log());
453 if (state_ > INITIAL_LOG_READY && unsent_logs())
454 state_ = SEND_OLD_INITIAL_LOGS;
455 }
[email protected]d01b8732008-10-16 02:18:07456 recording_active_ = enabled;
initial.commit09911bf2008-07-26 23:55:29457}
458
[email protected]d01b8732008-10-16 02:18:07459bool MetricsService::recording_active() const {
initial.commit09911bf2008-07-26 23:55:29460 DCHECK(IsSingleThreaded());
[email protected]d01b8732008-10-16 02:18:07461 return recording_active_;
initial.commit09911bf2008-07-26 23:55:29462}
463
[email protected]d01b8732008-10-16 02:18:07464void MetricsService::SetReporting(bool enable) {
465 if (reporting_active_ != enable) {
466 reporting_active_ = enable;
467 if (reporting_active_)
initial.commit09911bf2008-07-26 23:55:29468 StartLogTransmissionTimer();
469 }
[email protected]d01b8732008-10-16 02:18:07470}
471
472bool MetricsService::reporting_active() const {
473 DCHECK(IsSingleThreaded());
474 return reporting_active_;
initial.commit09911bf2008-07-26 23:55:29475}
476
477void MetricsService::Observe(NotificationType type,
478 const NotificationSource& source,
479 const NotificationDetails& details) {
480 DCHECK(current_log_);
481 DCHECK(IsSingleThreaded());
482
483 if (!CanLogNotification(type, source, details))
484 return;
485
[email protected]bfd04a62009-02-01 18:16:56486 switch (type.value) {
487 case NotificationType::USER_ACTION:
initial.commit09911bf2008-07-26 23:55:29488 current_log_->RecordUserAction(*Details<const wchar_t*>(details).ptr());
489 break;
490
[email protected]bfd04a62009-02-01 18:16:56491 case NotificationType::BROWSER_OPENED:
492 case NotificationType::BROWSER_CLOSED:
initial.commit09911bf2008-07-26 23:55:29493 LogWindowChange(type, source, details);
494 break;
495
[email protected]bfd04a62009-02-01 18:16:56496 case NotificationType::TAB_PARENTED:
497 case NotificationType::TAB_CLOSING:
initial.commit09911bf2008-07-26 23:55:29498 LogWindowChange(type, source, details);
499 break;
500
[email protected]bfd04a62009-02-01 18:16:56501 case NotificationType::LOAD_STOP:
initial.commit09911bf2008-07-26 23:55:29502 LogLoadComplete(type, source, details);
503 break;
504
[email protected]bfd04a62009-02-01 18:16:56505 case NotificationType::LOAD_START:
initial.commit09911bf2008-07-26 23:55:29506 LogLoadStarted();
507 break;
508
[email protected]bfd04a62009-02-01 18:16:56509 case NotificationType::RENDERER_PROCESS_TERMINATED:
initial.commit09911bf2008-07-26 23:55:29510 if (!*Details<bool>(details).ptr())
511 LogRendererCrash();
512 break;
513
[email protected]bfd04a62009-02-01 18:16:56514 case NotificationType::RENDERER_PROCESS_HANG:
initial.commit09911bf2008-07-26 23:55:29515 LogRendererHang();
516 break;
517
[email protected]bfd04a62009-02-01 18:16:56518 case NotificationType::RENDERER_PROCESS_IN_SBOX:
initial.commit09911bf2008-07-26 23:55:29519 LogRendererInSandbox(*Details<bool>(details).ptr());
520 break;
521
[email protected]a27a9382009-02-11 23:55:10522 case NotificationType::CHILD_PROCESS_HOST_CONNECTED:
523 case NotificationType::CHILD_PROCESS_CRASHED:
524 case NotificationType::CHILD_INSTANCE_CREATED:
525 LogChildProcessChange(type, source, details);
initial.commit09911bf2008-07-26 23:55:29526 break;
527
[email protected]bfd04a62009-02-01 18:16:56528 case NotificationType::TEMPLATE_URL_MODEL_LOADED:
initial.commit09911bf2008-07-26 23:55:29529 LogKeywords(Source<TemplateURLModel>(source).ptr());
530 break;
531
[email protected]bfd04a62009-02-01 18:16:56532 case NotificationType::OMNIBOX_OPENED_URL:
initial.commit09911bf2008-07-26 23:55:29533 current_log_->RecordOmniboxOpenedURL(
534 *Details<AutocompleteLog>(details).ptr());
535 break;
536
[email protected]bfd04a62009-02-01 18:16:56537 case NotificationType::BOOKMARK_MODEL_LOADED:
[email protected]d8e41ed2008-09-11 15:22:32538 LogBookmarks(Source<Profile>(source)->GetBookmarkModel());
initial.commit09911bf2008-07-26 23:55:29539 break;
540
541 default:
542 NOTREACHED();
543 break;
544 }
[email protected]d01b8732008-10-16 02:18:07545
546 HandleIdleSinceLastTransmission(false);
547
548 if (current_log_)
[email protected]281d2882009-01-20 20:32:42549 DLOG(INFO) << "METRICS: NUMBER OF EVENTS = " << current_log_->num_events();
[email protected]d01b8732008-10-16 02:18:07550}
551
552void MetricsService::HandleIdleSinceLastTransmission(bool in_idle) {
553 // If there wasn't a lot of action, maybe the computer was asleep, in which
554 // case, the log transmissions should have stopped. Here we start them up
555 // again.
[email protected]cac78842008-11-27 01:02:20556 if (!in_idle && idle_since_last_transmission_)
557 StartLogTransmissionTimer();
558 idle_since_last_transmission_ = in_idle;
initial.commit09911bf2008-07-26 23:55:29559}
560
561void MetricsService::RecordCleanShutdown() {
562 RecordBooleanPrefValue(prefs::kStabilityExitedCleanly, true);
563}
564
565void MetricsService::RecordStartOfSessionEnd() {
566 RecordBooleanPrefValue(prefs::kStabilitySessionEndCompleted, false);
567}
568
569void MetricsService::RecordCompletedSessionEnd() {
570 RecordBooleanPrefValue(prefs::kStabilitySessionEndCompleted, true);
571}
572
[email protected]e73c01972008-08-13 00:18:24573void MetricsService:: RecordBreakpadRegistration(bool success) {
[email protected]68475e602008-08-22 03:21:15574 if (!success)
[email protected]e73c01972008-08-13 00:18:24575 IncrementPrefValue(prefs::kStabilityBreakpadRegistrationFail);
576 else
577 IncrementPrefValue(prefs::kStabilityBreakpadRegistrationSuccess);
578}
579
580void MetricsService::RecordBreakpadHasDebugger(bool has_debugger) {
581 if (!has_debugger)
582 IncrementPrefValue(prefs::kStabilityDebuggerNotPresent);
583 else
[email protected]68475e602008-08-22 03:21:15584 IncrementPrefValue(prefs::kStabilityDebuggerPresent);
[email protected]e73c01972008-08-13 00:18:24585}
586
initial.commit09911bf2008-07-26 23:55:29587//------------------------------------------------------------------------------
588// private methods
589//------------------------------------------------------------------------------
590
591
592//------------------------------------------------------------------------------
593// Initialization methods
594
595void MetricsService::InitializeMetricsState() {
596 PrefService* pref = g_browser_process->local_state();
597 DCHECK(pref);
598
[email protected]541f77922009-02-23 21:14:38599 if (WideToUTF8(pref->GetString(prefs::kStabilityStatsVersion)) !=
600 MetricsLog::GetVersionString()) {
601 // This is a new version, so we don't want to confuse the stats about the
602 // old version with info that we upload.
603 DiscardOldStabilityStats(pref);
604 pref->SetString(prefs::kStabilityStatsVersion,
605 UTF8ToWide(MetricsLog::GetVersionString()));
606 }
607
initial.commit09911bf2008-07-26 23:55:29608 // Update session ID
609 session_id_ = pref->GetInteger(prefs::kMetricsSessionID);
610 ++session_id_;
611 pref->SetInteger(prefs::kMetricsSessionID, session_id_);
612
initial.commit09911bf2008-07-26 23:55:29613 // Stability bookkeeping
[email protected]e73c01972008-08-13 00:18:24614 IncrementPrefValue(prefs::kStabilityLaunchCount);
initial.commit09911bf2008-07-26 23:55:29615
[email protected]e73c01972008-08-13 00:18:24616 if (!pref->GetBoolean(prefs::kStabilityExitedCleanly)) {
617 IncrementPrefValue(prefs::kStabilityCrashCount);
initial.commit09911bf2008-07-26 23:55:29618 }
[email protected]e73c01972008-08-13 00:18:24619
620 // This will be set to 'true' if we exit cleanly.
initial.commit09911bf2008-07-26 23:55:29621 pref->SetBoolean(prefs::kStabilityExitedCleanly, false);
622
[email protected]e73c01972008-08-13 00:18:24623 if (!pref->GetBoolean(prefs::kStabilitySessionEndCompleted)) {
624 IncrementPrefValue(prefs::kStabilityIncompleteSessionEndCount);
initial.commit09911bf2008-07-26 23:55:29625 }
626 // This is marked false when we get a WM_ENDSESSION.
627 pref->SetBoolean(prefs::kStabilitySessionEndCompleted, true);
628
[email protected]0bb1a622009-03-04 03:22:32629 int64 last_start_time = pref->GetInt64(prefs::kStabilityLaunchTimeSec);
630 int64 last_end_time = pref->GetInt64(prefs::kStabilityLastTimestampSec);
631 int64 uptime = pref->GetInt64(prefs::kStabilityUptimeSec);
632
633 // Same idea as uptime, except this one never gets reset and is used at
634 // uninstallation.
635 int64 uninstall_metrics_uptime =
636 pref->GetInt64(prefs::kUninstallMetricsUptimeSec);
initial.commit09911bf2008-07-26 23:55:29637
638 if (last_start_time && last_end_time) {
639 // TODO(JAR): Exclude sleep time. ... which must be gathered in UI loop.
[email protected]0bb1a622009-03-04 03:22:32640 int64 uptime_increment = last_end_time - last_start_time;
641 uptime += uptime_increment;
642 pref->SetInt64(prefs::kStabilityUptimeSec, uptime);
643
644 uninstall_metrics_uptime += uptime_increment;
645 pref->SetInt64(prefs::kUninstallMetricsUptimeSec,
646 uninstall_metrics_uptime);
initial.commit09911bf2008-07-26 23:55:29647 }
[email protected]0bb1a622009-03-04 03:22:32648 pref->SetInt64(prefs::kStabilityLaunchTimeSec, Time::Now().ToTimeT());
649
650 // Bookkeeping for the uninstall metrics.
651 IncrementLongPrefsValue(prefs::kUninstallLaunchCount);
initial.commit09911bf2008-07-26 23:55:29652
653 // Save profile metrics.
654 PrefService* prefs = g_browser_process->local_state();
655 if (prefs) {
656 // Remove the current dictionary and store it for use when sending data to
657 // server. By removing the value we prune potentially dead profiles
658 // (and keys). All valid values are added back once services startup.
659 const DictionaryValue* profile_dictionary =
660 prefs->GetDictionary(prefs::kProfileMetrics);
661 if (profile_dictionary) {
662 // Do a deep copy of profile_dictionary since ClearPref will delete it.
663 profile_dictionary_.reset(static_cast<DictionaryValue*>(
664 profile_dictionary->DeepCopy()));
665 prefs->ClearPref(prefs::kProfileMetrics);
666 }
667 }
668
669 // Kick off the process of saving the state (so the uptime numbers keep
670 // getting updated) every n minutes.
671 ScheduleNextStateSave();
672}
673
674void MetricsService::OnGetPluginListTaskComplete() {
675 DCHECK(state_ == PLUGIN_LIST_REQUESTED);
676 if (state_ == PLUGIN_LIST_REQUESTED)
677 state_ = PLUGIN_LIST_ARRIVED;
678}
679
680std::string MetricsService::GenerateClientID() {
[email protected]dc6f4962009-02-13 01:25:50681#if defined(OS_WIN)
initial.commit09911bf2008-07-26 23:55:29682 const int kGUIDSize = 39;
683
684 GUID guid;
685 HRESULT guid_result = CoCreateGuid(&guid);
686 DCHECK(SUCCEEDED(guid_result));
687
688 std::wstring guid_string;
689 int result = StringFromGUID2(guid,
690 WriteInto(&guid_string, kGUIDSize), kGUIDSize);
691 DCHECK(result == kGUIDSize);
692
693 return WideToUTF8(guid_string.substr(1, guid_string.length() - 2));
[email protected]dc6f4962009-02-13 01:25:50694#else
695 // TODO(port): Implement for Mac and linux.
[email protected]f5d0e152009-02-19 21:54:37696 // Rather than actually implementing a random source, might this be a good
697 // time to implement http://code.google.com/p/chromium/issues/detail?id=2278
698 // ? I think so!
[email protected]dc6f4962009-02-13 01:25:50699 NOTIMPLEMENTED();
700 return std::string();
701#endif
initial.commit09911bf2008-07-26 23:55:29702}
703
704
705//------------------------------------------------------------------------------
706// State save methods
707
708void MetricsService::ScheduleNextStateSave() {
709 state_saver_factory_.RevokeAll();
710
711 MessageLoop::current()->PostDelayedTask(FROM_HERE,
712 state_saver_factory_.NewRunnableMethod(&MetricsService::SaveLocalState),
713 kSaveStateInterval * 1000);
714}
715
716void MetricsService::SaveLocalState() {
717 PrefService* pref = g_browser_process->local_state();
718 if (!pref) {
719 NOTREACHED();
720 return;
721 }
722
723 RecordCurrentState(pref);
724 pref->ScheduleSavePersistentPrefs(g_browser_process->file_thread());
725
[email protected]281d2882009-01-20 20:32:42726 // TODO(jar): Does this run down the batteries????
initial.commit09911bf2008-07-26 23:55:29727 ScheduleNextStateSave();
728}
729
730
731//------------------------------------------------------------------------------
732// Recording control methods
733
734void MetricsService::StartRecording() {
735 if (current_log_)
736 return;
737
738 current_log_ = new MetricsLog(client_id_, session_id_);
739 if (state_ == INITIALIZED) {
740 // We only need to schedule that run once.
741 state_ = PLUGIN_LIST_REQUESTED;
742
743 // Make sure the plugin list is loaded before the inital log is sent, so
744 // that the main thread isn't blocked generating the list.
745 g_browser_process->file_thread()->message_loop()->PostDelayedTask(FROM_HERE,
746 new GetPluginListTask(MessageLoop::current()),
[email protected]252873ef2008-08-04 21:59:45747 kInitialInterlogDuration * 1000 / 2);
initial.commit09911bf2008-07-26 23:55:29748 }
749}
750
751void MetricsService::StopRecording(MetricsLog** log) {
752 if (!current_log_)
753 return;
754
[email protected]68475e602008-08-22 03:21:15755 // TODO(jar): Integrate bounds on log recording more consistently, so that we
756 // can stop recording logs that are too big much sooner.
[email protected]d01b8732008-10-16 02:18:07757 if (current_log_->num_events() > log_event_limit_) {
[email protected]553dba62009-02-24 19:08:23758 UMA_HISTOGRAM_COUNTS("UMA.Discarded Log Events",
[email protected]68475e602008-08-22 03:21:15759 current_log_->num_events());
760 current_log_->CloseLog();
761 delete current_log_;
[email protected]294638782008-09-24 00:22:41762 current_log_ = NULL;
[email protected]68475e602008-08-22 03:21:15763 StartRecording(); // Start trivial log to hold our histograms.
764 }
765
[email protected]0b33f80b2008-12-17 21:34:36766 // Put incremental data (histogram deltas, and realtime stats deltas) at the
[email protected]147bbc0b2009-01-06 19:37:40767 // end of all log transmissions (initial log handles this separately).
initial.commit09911bf2008-07-26 23:55:29768 // Don't bother if we're going to discard current_log_.
[email protected]0b33f80b2008-12-17 21:34:36769 if (log) {
[email protected]c96d53092009-02-24 01:25:06770 current_log_->RecordIncrementalStabilityElements();
initial.commit09911bf2008-07-26 23:55:29771 RecordCurrentHistograms();
[email protected]0b33f80b2008-12-17 21:34:36772 }
initial.commit09911bf2008-07-26 23:55:29773
774 current_log_->CloseLog();
[email protected]cac78842008-11-27 01:02:20775 if (log)
initial.commit09911bf2008-07-26 23:55:29776 *log = current_log_;
[email protected]cac78842008-11-27 01:02:20777 else
initial.commit09911bf2008-07-26 23:55:29778 delete current_log_;
initial.commit09911bf2008-07-26 23:55:29779 current_log_ = NULL;
780}
781
782void MetricsService::ListenerRegistration(bool start_listening) {
[email protected]bfd04a62009-02-01 18:16:56783 AddOrRemoveObserver(this, NotificationType::BROWSER_OPENED, start_listening);
784 AddOrRemoveObserver(this, NotificationType::BROWSER_CLOSED, start_listening);
785 AddOrRemoveObserver(this, NotificationType::USER_ACTION, start_listening);
786 AddOrRemoveObserver(this, NotificationType::TAB_PARENTED, start_listening);
787 AddOrRemoveObserver(this, NotificationType::TAB_CLOSING, start_listening);
788 AddOrRemoveObserver(this, NotificationType::LOAD_START, start_listening);
789 AddOrRemoveObserver(this, NotificationType::LOAD_STOP, start_listening);
790 AddOrRemoveObserver(this, NotificationType::RENDERER_PROCESS_IN_SBOX,
initial.commit09911bf2008-07-26 23:55:29791 start_listening);
[email protected]bfd04a62009-02-01 18:16:56792 AddOrRemoveObserver(this, NotificationType::RENDERER_PROCESS_TERMINATED,
initial.commit09911bf2008-07-26 23:55:29793 start_listening);
[email protected]bfd04a62009-02-01 18:16:56794 AddOrRemoveObserver(this, NotificationType::RENDERER_PROCESS_HANG,
795 start_listening);
[email protected]a27a9382009-02-11 23:55:10796 AddOrRemoveObserver(this, NotificationType::CHILD_PROCESS_HOST_CONNECTED,
[email protected]bfd04a62009-02-01 18:16:56797 start_listening);
[email protected]a27a9382009-02-11 23:55:10798 AddOrRemoveObserver(this, NotificationType::CHILD_INSTANCE_CREATED,
[email protected]bfd04a62009-02-01 18:16:56799 start_listening);
[email protected]a27a9382009-02-11 23:55:10800 AddOrRemoveObserver(this, NotificationType::CHILD_PROCESS_CRASHED,
[email protected]bfd04a62009-02-01 18:16:56801 start_listening);
802 AddOrRemoveObserver(this, NotificationType::TEMPLATE_URL_MODEL_LOADED,
803 start_listening);
804 AddOrRemoveObserver(this, NotificationType::OMNIBOX_OPENED_URL,
805 start_listening);
806 AddOrRemoveObserver(this, NotificationType::BOOKMARK_MODEL_LOADED,
807 start_listening);
initial.commit09911bf2008-07-26 23:55:29808}
809
810// static
811void MetricsService::AddOrRemoveObserver(NotificationObserver* observer,
[email protected]cac78842008-11-27 01:02:20812 NotificationType type,
813 bool is_add) {
initial.commit09911bf2008-07-26 23:55:29814 NotificationService* service = NotificationService::current();
815
[email protected]cac78842008-11-27 01:02:20816 if (is_add)
initial.commit09911bf2008-07-26 23:55:29817 service->AddObserver(observer, type, NotificationService::AllSources());
[email protected]cac78842008-11-27 01:02:20818 else
initial.commit09911bf2008-07-26 23:55:29819 service->RemoveObserver(observer, type, NotificationService::AllSources());
initial.commit09911bf2008-07-26 23:55:29820}
821
822void MetricsService::PushPendingLogsToUnsentLists() {
823 if (state_ < INITIAL_LOG_READY)
[email protected]28ab7f92009-01-06 21:39:04824 return; // We didn't and still don't have time to get plugin list etc.
initial.commit09911bf2008-07-26 23:55:29825
826 if (pending_log()) {
827 PreparePendingLogText();
828 if (state_ == INITIAL_LOG_READY) {
829 // We may race here, and send second copy of initial log later.
830 unsent_initial_logs_.push_back(pending_log_text_);
[email protected]d01b8732008-10-16 02:18:07831 state_ = SEND_OLD_INITIAL_LOGS;
initial.commit09911bf2008-07-26 23:55:29832 } else {
[email protected]281d2882009-01-20 20:32:42833 // TODO(jar): Verify correctness in other states, including sending unsent
[email protected]541f77922009-02-23 21:14:38834 // initial logs.
[email protected]68475e602008-08-22 03:21:15835 PushPendingLogTextToUnsentOngoingLogs();
initial.commit09911bf2008-07-26 23:55:29836 }
837 DiscardPendingLog();
838 }
839 DCHECK(!pending_log());
840 StopRecording(&pending_log_);
841 PreparePendingLogText();
[email protected]68475e602008-08-22 03:21:15842 PushPendingLogTextToUnsentOngoingLogs();
initial.commit09911bf2008-07-26 23:55:29843 DiscardPendingLog();
844 StoreUnsentLogs();
845}
846
[email protected]68475e602008-08-22 03:21:15847void MetricsService::PushPendingLogTextToUnsentOngoingLogs() {
[email protected]d01b8732008-10-16 02:18:07848 // If UMA response told us not to upload, there's no need to save the pending
849 // log. It wasn't supposed to be uploaded anyway.
850 if (!server_permits_upload_)
851 return;
852
[email protected]dc6f4962009-02-13 01:25:50853 if (pending_log_text_.length() >
854 static_cast<size_t>(kUploadLogAvoidRetransmitSize)) {
[email protected]553dba62009-02-24 19:08:23855 UMA_HISTOGRAM_COUNTS("UMA.Large Accumulated Log Not Persisted",
[email protected]68475e602008-08-22 03:21:15856 static_cast<int>(pending_log_text_.length()));
857 return;
858 }
859 unsent_ongoing_logs_.push_back(pending_log_text_);
860}
861
initial.commit09911bf2008-07-26 23:55:29862//------------------------------------------------------------------------------
863// Transmission of logs methods
864
865void MetricsService::StartLogTransmissionTimer() {
[email protected]d01b8732008-10-16 02:18:07866 // If we're not reporting, there's no point in starting a log transmission
867 // timer.
868 if (!reporting_active())
869 return;
870
initial.commit09911bf2008-07-26 23:55:29871 if (!current_log_)
872 return; // Recorder is shutdown.
[email protected]d01b8732008-10-16 02:18:07873
874 // If there is already a timer running, we leave it running.
875 // If timer_pending is true because the fetch is waiting for a response,
876 // we return for now and let the response handler start the timer.
877 if (timer_pending_)
initial.commit09911bf2008-07-26 23:55:29878 return;
[email protected]d01b8732008-10-16 02:18:07879
[email protected]d01b8732008-10-16 02:18:07880 // Before starting the timer, set timer_pending_ to true.
initial.commit09911bf2008-07-26 23:55:29881 timer_pending_ = true;
[email protected]d01b8732008-10-16 02:18:07882
883 // Right before the UMA transmission gets started, there's one more thing we'd
884 // like to record: the histogram of memory usage, so we spawn a task to
885 // collect the memory details and when that task is finished, we arrange for
886 // TryToStartTransmission to take over.
initial.commit09911bf2008-07-26 23:55:29887 MessageLoop::current()->PostDelayedTask(FROM_HERE,
888 log_sender_factory_.
889 NewRunnableMethod(&MetricsService::CollectMemoryDetails),
890 static_cast<int>(interlog_duration_.InMilliseconds()));
891}
892
893void MetricsService::TryToStartTransmission() {
894 DCHECK(IsSingleThreaded());
895
[email protected]d01b8732008-10-16 02:18:07896 // This function should only be called via timer, so timer_pending_
897 // should be true.
898 DCHECK(timer_pending_);
899 timer_pending_ = false;
initial.commit09911bf2008-07-26 23:55:29900
901 DCHECK(!current_fetch_.get());
initial.commit09911bf2008-07-26 23:55:29902
[email protected]d01b8732008-10-16 02:18:07903 // If we're getting no notifications, then the log won't have much in it, and
904 // it's possible the computer is about to go to sleep, so don't upload and
905 // don't restart the transmission timer.
906 if (idle_since_last_transmission_)
907 return;
908
909 // If somehow there is a fetch in progress, we return setting timer_pending_
910 // to true and hope things work out.
911 if (current_fetch_.get()) {
912 timer_pending_ = true;
913 return;
914 }
915
916 // If uploads are forbidden by UMA response, there's no point in keeping
917 // the current_log_, and the more often we delete it, the less likely it is
918 // to expand forever.
919 if (!server_permits_upload_ && current_log_) {
920 StopRecording(NULL);
921 StartRecording();
922 }
initial.commit09911bf2008-07-26 23:55:29923
924 if (!current_log_)
925 return; // Logging was disabled.
[email protected]d01b8732008-10-16 02:18:07926 if (!reporting_active())
initial.commit09911bf2008-07-26 23:55:29927 return; // Don't do work if we're not going to send anything now.
928
[email protected]d01b8732008-10-16 02:18:07929 MakePendingLog();
initial.commit09911bf2008-07-26 23:55:29930
[email protected]d01b8732008-10-16 02:18:07931 // MakePendingLog should have put something in the pending log, if it didn't,
932 // we start the timer again, return and hope things work out.
933 if (!pending_log()) {
934 StartLogTransmissionTimer();
935 return;
936 }
initial.commit09911bf2008-07-26 23:55:29937
[email protected]d01b8732008-10-16 02:18:07938 // If we're not supposed to upload any UMA data because the response or the
939 // user said so, cancel the upload at this point, but start the timer.
940 if (!TransmissionPermitted()) {
941 DiscardPendingLog();
942 StartLogTransmissionTimer();
943 return;
944 }
initial.commit09911bf2008-07-26 23:55:29945
[email protected]d01b8732008-10-16 02:18:07946 PrepareFetchWithPendingLog();
947
948 if (!current_fetch_.get()) {
949 // Compression failed, and log discarded :-/.
950 DiscardPendingLog();
951 StartLogTransmissionTimer(); // Maybe we'll do better next time
952 // TODO(jar): If compression failed, we should have created a tiny log and
953 // compressed that, so that we can signal that we're losing logs.
954 return;
955 }
956
957 DCHECK(!timer_pending_);
958
959 // The URL fetch is a like timer in that after a while we get called back
960 // so we set timer_pending_ true just as we start the url fetch.
961 timer_pending_ = true;
962 current_fetch_->Start();
963
964 HandleIdleSinceLastTransmission(true);
965}
966
967
968void MetricsService::MakePendingLog() {
969 if (pending_log())
970 return;
971
972 switch (state_) {
973 case INITIALIZED:
974 case PLUGIN_LIST_REQUESTED: // We should be further along by now.
975 DCHECK(false);
976 return;
977
978 case PLUGIN_LIST_ARRIVED:
979 // We need to wait for the initial log to be ready before sending
980 // anything, because the server will tell us whether it wants to hear
981 // from us.
982 PrepareInitialLog();
983 DCHECK(state_ == PLUGIN_LIST_ARRIVED);
984 RecallUnsentLogs();
985 state_ = INITIAL_LOG_READY;
986 break;
987
988 case SEND_OLD_INITIAL_LOGS:
[email protected]cac78842008-11-27 01:02:20989 if (!unsent_initial_logs_.empty()) {
990 pending_log_text_ = unsent_initial_logs_.back();
991 break;
992 }
[email protected]d01b8732008-10-16 02:18:07993 state_ = SENDING_OLD_LOGS;
994 // Fall through.
initial.commit09911bf2008-07-26 23:55:29995
[email protected]d01b8732008-10-16 02:18:07996 case SENDING_OLD_LOGS:
997 if (!unsent_ongoing_logs_.empty()) {
998 pending_log_text_ = unsent_ongoing_logs_.back();
999 break;
1000 }
1001 state_ = SENDING_CURRENT_LOGS;
1002 // Fall through.
1003
1004 case SENDING_CURRENT_LOGS:
1005 StopRecording(&pending_log_);
1006 StartRecording();
1007 break;
1008
1009 default:
1010 DCHECK(false);
1011 return;
1012 }
1013
1014 DCHECK(pending_log());
1015}
1016
1017bool MetricsService::TransmissionPermitted() const {
1018 // If the user forbids uploading that's they're business, and we don't upload
1019 // anything. If the server forbids uploading, that's our business, so we take
1020 // that to mean it forbids current logs, but we still send up the inital logs
1021 // and any old logs.
[email protected]d01b8732008-10-16 02:18:071022 if (!user_permits_upload_)
1023 return false;
[email protected]cac78842008-11-27 01:02:201024 if (server_permits_upload_)
[email protected]d01b8732008-10-16 02:18:071025 return true;
initial.commit09911bf2008-07-26 23:55:291026
[email protected]cac78842008-11-27 01:02:201027 switch (state_) {
1028 case INITIAL_LOG_READY:
1029 case SEND_OLD_INITIAL_LOGS:
1030 case SENDING_OLD_LOGS:
1031 return true;
1032
1033 case SENDING_CURRENT_LOGS:
1034 default:
1035 return false;
[email protected]8c8824b2008-09-20 01:55:501036 }
initial.commit09911bf2008-07-26 23:55:291037}
1038
1039void MetricsService::CollectMemoryDetails() {
1040 Task* task = log_sender_factory_.
1041 NewRunnableMethod(&MetricsService::TryToStartTransmission);
1042 MetricsMemoryDetails* details = new MetricsMemoryDetails(task);
1043 details->StartFetch();
1044
1045 // Collect WebCore cache information to put into a histogram.
1046 for (RenderProcessHost::iterator it = RenderProcessHost::begin();
1047 it != RenderProcessHost::end(); ++it) {
1048 it->second->Send(new ViewMsg_GetCacheResourceStats());
1049 }
1050}
1051
1052void MetricsService::PrepareInitialLog() {
1053 DCHECK(state_ == PLUGIN_LIST_ARRIVED);
1054 std::vector<WebPluginInfo> plugins;
1055 PluginService::GetInstance()->GetPlugins(false, &plugins);
1056
1057 MetricsLog* log = new MetricsLog(client_id_, session_id_);
1058 log->RecordEnvironment(plugins, profile_dictionary_.get());
1059
1060 // Histograms only get written to current_log_, so setup for the write.
1061 MetricsLog* save_log = current_log_;
1062 current_log_ = log;
1063 RecordCurrentHistograms(); // Into current_log_... which is really log.
1064 current_log_ = save_log;
1065
1066 log->CloseLog();
1067 DCHECK(!pending_log());
1068 pending_log_ = log;
1069}
1070
1071void MetricsService::RecallUnsentLogs() {
1072 DCHECK(unsent_initial_logs_.empty());
1073 DCHECK(unsent_ongoing_logs_.empty());
1074
1075 PrefService* local_state = g_browser_process->local_state();
1076 DCHECK(local_state);
1077
1078 ListValue* unsent_initial_logs = local_state->GetMutableList(
1079 prefs::kMetricsInitialLogs);
1080 for (ListValue::iterator it = unsent_initial_logs->begin();
1081 it != unsent_initial_logs->end(); ++it) {
[email protected]5e324b72008-12-18 00:07:591082 std::string log;
1083 (*it)->GetAsString(&log);
1084 unsent_initial_logs_.push_back(log);
initial.commit09911bf2008-07-26 23:55:291085 }
1086
1087 ListValue* unsent_ongoing_logs = local_state->GetMutableList(
1088 prefs::kMetricsOngoingLogs);
1089 for (ListValue::iterator it = unsent_ongoing_logs->begin();
1090 it != unsent_ongoing_logs->end(); ++it) {
[email protected]5e324b72008-12-18 00:07:591091 std::string log;
1092 (*it)->GetAsString(&log);
1093 unsent_ongoing_logs_.push_back(log);
initial.commit09911bf2008-07-26 23:55:291094 }
1095}
1096
1097void MetricsService::StoreUnsentLogs() {
1098 if (state_ < INITIAL_LOG_READY)
1099 return; // We never Recalled the prior unsent logs.
1100
1101 PrefService* local_state = g_browser_process->local_state();
1102 DCHECK(local_state);
1103
1104 ListValue* unsent_initial_logs = local_state->GetMutableList(
1105 prefs::kMetricsInitialLogs);
1106 unsent_initial_logs->Clear();
1107 size_t start = 0;
1108 if (unsent_initial_logs_.size() > kMaxInitialLogsPersisted)
1109 start = unsent_initial_logs_.size() - kMaxInitialLogsPersisted;
1110 for (size_t i = start; i < unsent_initial_logs_.size(); ++i)
1111 unsent_initial_logs->Append(
[email protected]5e324b72008-12-18 00:07:591112 Value::CreateStringValue(unsent_initial_logs_[i]));
initial.commit09911bf2008-07-26 23:55:291113
1114 ListValue* unsent_ongoing_logs = local_state->GetMutableList(
1115 prefs::kMetricsOngoingLogs);
1116 unsent_ongoing_logs->Clear();
1117 start = 0;
1118 if (unsent_ongoing_logs_.size() > kMaxOngoingLogsPersisted)
1119 start = unsent_ongoing_logs_.size() - kMaxOngoingLogsPersisted;
1120 for (size_t i = start; i < unsent_ongoing_logs_.size(); ++i)
1121 unsent_ongoing_logs->Append(
[email protected]5e324b72008-12-18 00:07:591122 Value::CreateStringValue(unsent_ongoing_logs_[i]));
initial.commit09911bf2008-07-26 23:55:291123}
1124
1125void MetricsService::PreparePendingLogText() {
1126 DCHECK(pending_log());
1127 if (!pending_log_text_.empty())
1128 return;
1129 int original_size = pending_log_->GetEncodedLogSize();
1130 pending_log_->GetEncodedLog(WriteInto(&pending_log_text_, original_size),
1131 original_size);
1132}
1133
[email protected]d01b8732008-10-16 02:18:071134void MetricsService::PrepareFetchWithPendingLog() {
initial.commit09911bf2008-07-26 23:55:291135 DCHECK(pending_log());
1136 DCHECK(!current_fetch_.get());
1137 PreparePendingLogText();
1138 DCHECK(!pending_log_text_.empty());
1139
1140 // Allow security conscious users to see all metrics logs that we send.
1141 LOG(INFO) << "METRICS LOG: " << pending_log_text_;
1142
1143 std::string compressed_log;
[email protected]cac78842008-11-27 01:02:201144 if (!Bzip2Compress(pending_log_text_, &compressed_log)) {
initial.commit09911bf2008-07-26 23:55:291145 NOTREACHED() << "Failed to compress log for transmission.";
1146 DiscardPendingLog();
1147 StartLogTransmissionTimer(); // Maybe we'll do better on next log :-/.
1148 return;
1149 }
[email protected]cac78842008-11-27 01:02:201150
initial.commit09911bf2008-07-26 23:55:291151 current_fetch_.reset(new URLFetcher(GURL(kMetricsURL), URLFetcher::POST,
1152 this));
1153 current_fetch_->set_request_context(Profile::GetDefaultRequestContext());
1154 current_fetch_->set_upload_data(kMetricsType, compressed_log);
initial.commit09911bf2008-07-26 23:55:291155}
1156
1157void MetricsService::DiscardPendingLog() {
1158 if (pending_log_) { // Shutdown might have deleted it!
1159 delete pending_log_;
1160 pending_log_ = NULL;
1161 }
1162 pending_log_text_.clear();
1163}
1164
1165// This implementation is based on the Firefox MetricsService implementation.
1166bool MetricsService::Bzip2Compress(const std::string& input,
1167 std::string* output) {
1168 bz_stream stream = {0};
1169 // As long as our input is smaller than the bzip2 block size, we should get
1170 // the best compression. For example, if your input was 250k, using a block
1171 // size of 300k or 500k should result in the same compression ratio. Since
1172 // our data should be under 100k, using the minimum block size of 100k should
1173 // allocate less temporary memory, but result in the same compression ratio.
1174 int result = BZ2_bzCompressInit(&stream,
1175 1, // 100k (min) block size
1176 0, // quiet
1177 0); // default "work factor"
1178 if (result != BZ_OK) { // out of memory?
1179 return false;
1180 }
1181
1182 output->clear();
1183
1184 stream.next_in = const_cast<char*>(input.data());
1185 stream.avail_in = static_cast<int>(input.size());
1186 // NOTE: we don't need a BZ_RUN phase since our input buffer contains
1187 // the entire input
1188 do {
1189 output->resize(output->size() + 1024);
1190 stream.next_out = &((*output)[stream.total_out_lo32]);
1191 stream.avail_out = static_cast<int>(output->size()) - stream.total_out_lo32;
1192 result = BZ2_bzCompress(&stream, BZ_FINISH);
1193 } while (result == BZ_FINISH_OK);
1194 if (result != BZ_STREAM_END) // unknown failure?
1195 return false;
1196 result = BZ2_bzCompressEnd(&stream);
1197 DCHECK(result == BZ_OK);
1198
1199 output->resize(stream.total_out_lo32);
1200
1201 return true;
1202}
1203
1204static const char* StatusToString(const URLRequestStatus& status) {
1205 switch (status.status()) {
1206 case URLRequestStatus::SUCCESS:
1207 return "SUCCESS";
1208
1209 case URLRequestStatus::IO_PENDING:
1210 return "IO_PENDING";
1211
1212 case URLRequestStatus::HANDLED_EXTERNALLY:
1213 return "HANDLED_EXTERNALLY";
1214
1215 case URLRequestStatus::CANCELED:
1216 return "CANCELED";
1217
1218 case URLRequestStatus::FAILED:
1219 return "FAILED";
1220
1221 default:
1222 NOTREACHED();
1223 return "Unknown";
1224 }
1225}
1226
1227void MetricsService::OnURLFetchComplete(const URLFetcher* source,
1228 const GURL& url,
1229 const URLRequestStatus& status,
1230 int response_code,
1231 const ResponseCookies& cookies,
1232 const std::string& data) {
1233 DCHECK(timer_pending_);
1234 timer_pending_ = false;
1235 DCHECK(current_fetch_.get());
1236 current_fetch_.reset(NULL); // We're not allowed to re-use it.
1237
1238 // Confirm send so that we can move on.
[email protected]281d2882009-01-20 20:32:421239 LOG(INFO) << "METRICS RESPONSE CODE: " << response_code << " status=" <<
[email protected]cac78842008-11-27 01:02:201240 StatusToString(status);
[email protected]252873ef2008-08-04 21:59:451241
[email protected]0eb34fee2009-01-21 08:04:381242 // Provide boolean for error recovery (allow us to ignore response_code).
[email protected]dc6f4962009-02-13 01:25:501243 bool discard_log = false;
[email protected]0eb34fee2009-01-21 08:04:381244
[email protected]68475e602008-08-22 03:21:151245 if (response_code != 200 &&
[email protected]dc6f4962009-02-13 01:25:501246 pending_log_text_.length() >
1247 static_cast<size_t>(kUploadLogAvoidRetransmitSize)) {
[email protected]553dba62009-02-24 19:08:231248 UMA_HISTOGRAM_COUNTS("UMA.Large Rejected Log was Discarded",
[email protected]68475e602008-08-22 03:21:151249 static_cast<int>(pending_log_text_.length()));
[email protected]0eb34fee2009-01-21 08:04:381250 discard_log = true;
1251 } else if (response_code == 400) {
1252 // Bad syntax. Retransmission won't work.
[email protected]553dba62009-02-24 19:08:231253 UMA_HISTOGRAM_COUNTS("UMA.Unacceptable_Log_Discarded", state_);
[email protected]0eb34fee2009-01-21 08:04:381254 discard_log = true;
[email protected]68475e602008-08-22 03:21:151255 }
1256
[email protected]0eb34fee2009-01-21 08:04:381257 if (response_code != 200 && !discard_log) {
[email protected]281d2882009-01-20 20:32:421258 LOG(INFO) << "METRICS: transmission attempt returned a failure code: "
1259 << response_code << ". Verify network connectivity";
[email protected]252873ef2008-08-04 21:59:451260 HandleBadResponseCode();
[email protected]0eb34fee2009-01-21 08:04:381261 } else { // Successful receipt (or we are discarding log).
[email protected]281d2882009-01-20 20:32:421262 LOG(INFO) << "METRICS RESPONSE DATA: " << data;
initial.commit09911bf2008-07-26 23:55:291263 switch (state_) {
1264 case INITIAL_LOG_READY:
1265 state_ = SEND_OLD_INITIAL_LOGS;
1266 break;
1267
1268 case SEND_OLD_INITIAL_LOGS:
1269 DCHECK(!unsent_initial_logs_.empty());
1270 unsent_initial_logs_.pop_back();
1271 StoreUnsentLogs();
1272 break;
1273
1274 case SENDING_OLD_LOGS:
1275 DCHECK(!unsent_ongoing_logs_.empty());
1276 unsent_ongoing_logs_.pop_back();
1277 StoreUnsentLogs();
1278 break;
1279
1280 case SENDING_CURRENT_LOGS:
1281 break;
1282
1283 default:
1284 DCHECK(false);
1285 break;
1286 }
[email protected]d01b8732008-10-16 02:18:071287
initial.commit09911bf2008-07-26 23:55:291288 DiscardPendingLog();
[email protected]29be92552008-08-07 22:49:271289 // Since we sent a log, make sure our in-memory state is recorded to disk.
1290 PrefService* local_state = g_browser_process->local_state();
1291 DCHECK(local_state);
1292 if (local_state)
1293 local_state->ScheduleSavePersistentPrefs(
1294 g_browser_process->file_thread());
[email protected]252873ef2008-08-04 21:59:451295
[email protected]147bbc0b2009-01-06 19:37:401296 // Provide a default (free of exponetial backoff, other varances) in case
1297 // the server does not specify a value.
1298 interlog_duration_ = TimeDelta::FromSeconds(kMinSecondsPerLog);
1299
[email protected]252873ef2008-08-04 21:59:451300 GetSettingsFromResponseData(data);
[email protected]252873ef2008-08-04 21:59:451301 // Override server specified interlog delay if there are unsent logs to
[email protected]29be92552008-08-07 22:49:271302 // transmit.
initial.commit09911bf2008-07-26 23:55:291303 if (unsent_logs()) {
1304 DCHECK(state_ < SENDING_CURRENT_LOGS);
1305 interlog_duration_ = TimeDelta::FromSeconds(kUnsentLogDelay);
initial.commit09911bf2008-07-26 23:55:291306 }
1307 }
[email protected]252873ef2008-08-04 21:59:451308
initial.commit09911bf2008-07-26 23:55:291309 StartLogTransmissionTimer();
1310}
1311
[email protected]252873ef2008-08-04 21:59:451312void MetricsService::HandleBadResponseCode() {
[email protected]281d2882009-01-20 20:32:421313 LOG(INFO) << "Verify your metrics logs are formatted correctly. "
[email protected]cac78842008-11-27 01:02:201314 "Verify server is active at " << kMetricsURL;
[email protected]252873ef2008-08-04 21:59:451315 if (!pending_log()) {
[email protected]281d2882009-01-20 20:32:421316 LOG(INFO) << "METRICS: Recorder shutdown during log transmission.";
[email protected]252873ef2008-08-04 21:59:451317 } else {
1318 // Send progressively less frequently.
1319 DCHECK(kBackoff > 1.0);
1320 interlog_duration_ = TimeDelta::FromMicroseconds(
1321 static_cast<int64>(kBackoff * interlog_duration_.InMicroseconds()));
1322
1323 if (kMaxBackoff * TimeDelta::FromSeconds(kMinSecondsPerLog) <
[email protected]cac78842008-11-27 01:02:201324 interlog_duration_) {
[email protected]252873ef2008-08-04 21:59:451325 interlog_duration_ = kMaxBackoff *
1326 TimeDelta::FromSeconds(kMinSecondsPerLog);
[email protected]cac78842008-11-27 01:02:201327 }
[email protected]252873ef2008-08-04 21:59:451328
[email protected]281d2882009-01-20 20:32:421329 LOG(INFO) << "METRICS: transmission retry being scheduled in " <<
[email protected]252873ef2008-08-04 21:59:451330 interlog_duration_.InSeconds() << " seconds for " <<
1331 pending_log_text_;
initial.commit09911bf2008-07-26 23:55:291332 }
initial.commit09911bf2008-07-26 23:55:291333}
1334
[email protected]252873ef2008-08-04 21:59:451335void MetricsService::GetSettingsFromResponseData(const std::string& data) {
1336 // We assume that the file is structured as a block opened by <response>
[email protected]d01b8732008-10-16 02:18:071337 // and that inside response, there is a block opened by tag <chrome_config>
1338 // other tags are ignored for now except the content of <chrome_config>.
[email protected]281d2882009-01-20 20:32:421339 LOG(INFO) << "METRICS: getting settings from response data: " << data;
[email protected]d01b8732008-10-16 02:18:071340
[email protected]252873ef2008-08-04 21:59:451341 int data_size = static_cast<int>(data.size());
1342 if (data_size < 0) {
[email protected]281d2882009-01-20 20:32:421343 LOG(INFO) << "METRICS: server response data bad size: " << data_size <<
[email protected]cac78842008-11-27 01:02:201344 "; aborting extraction of settings";
[email protected]252873ef2008-08-04 21:59:451345 return;
1346 }
[email protected]cac78842008-11-27 01:02:201347 xmlDocPtr doc = xmlReadMemory(data.c_str(), data_size, "", NULL, 0);
[email protected]252873ef2008-08-04 21:59:451348 DCHECK(doc);
[email protected]d01b8732008-10-16 02:18:071349 // If the document is malformed, we just use the settings that were there.
1350 if (!doc) {
[email protected]281d2882009-01-20 20:32:421351 LOG(INFO) << "METRICS: reading xml from server response data failed";
[email protected]252873ef2008-08-04 21:59:451352 return;
[email protected]d01b8732008-10-16 02:18:071353 }
[email protected]252873ef2008-08-04 21:59:451354
[email protected]d01b8732008-10-16 02:18:071355 xmlNodePtr top_node = xmlDocGetRootElement(doc), chrome_config_node = NULL;
1356 // Here, we find the chrome_config node by name.
[email protected]252873ef2008-08-04 21:59:451357 for (xmlNodePtr p = top_node->children; p; p = p->next) {
[email protected]d01b8732008-10-16 02:18:071358 if (xmlStrEqual(p->name, BAD_CAST "chrome_config")) {
1359 chrome_config_node = p;
[email protected]252873ef2008-08-04 21:59:451360 break;
1361 }
1362 }
1363 // If the server data is formatted wrong and there is no
1364 // config node where we expect, we just drop out.
[email protected]d01b8732008-10-16 02:18:071365 if (chrome_config_node != NULL)
1366 GetSettingsFromChromeConfigNode(chrome_config_node);
[email protected]252873ef2008-08-04 21:59:451367 xmlFreeDoc(doc);
1368}
1369
[email protected]d01b8732008-10-16 02:18:071370void MetricsService::GetSettingsFromChromeConfigNode(
1371 xmlNodePtr chrome_config_node) {
1372 // Iterate through all children of the config node.
1373 for (xmlNodePtr current_node = chrome_config_node->children;
1374 current_node;
1375 current_node = current_node->next) {
1376 // If we find the upload tag, we appeal to another function
1377 // GetSettingsFromUploadNode to read all the data in it.
[email protected]252873ef2008-08-04 21:59:451378 if (xmlStrEqual(current_node->name, BAD_CAST "upload")) {
[email protected]d01b8732008-10-16 02:18:071379 GetSettingsFromUploadNode(current_node);
[email protected]252873ef2008-08-04 21:59:451380 continue;
1381 }
1382 }
1383}
initial.commit09911bf2008-07-26 23:55:291384
[email protected]d01b8732008-10-16 02:18:071385void MetricsService::InheritedProperties::OverwriteWhereNeeded(
1386 xmlNodePtr node) {
1387 xmlChar* salt_value = xmlGetProp(node, BAD_CAST "salt");
1388 if (salt_value) // If the property isn't there, xmlGetProp returns NULL.
1389 salt = atoi(reinterpret_cast<char*>(salt_value));
1390 // If the property isn't there, we keep the value the property had before
1391
1392 xmlChar* denominator_value = xmlGetProp(node, BAD_CAST "denominator");
1393 if (denominator_value)
1394 denominator = atoi(reinterpret_cast<char*>(denominator_value));
1395}
1396
1397void MetricsService::GetSettingsFromUploadNode(xmlNodePtr upload_node) {
1398 InheritedProperties props;
1399 GetSettingsFromUploadNodeRecursive(upload_node, props, "", true);
1400}
1401
[email protected]cac78842008-11-27 01:02:201402void MetricsService::GetSettingsFromUploadNodeRecursive(
1403 xmlNodePtr node,
1404 InheritedProperties props,
1405 std::string path_prefix,
1406 bool uploadOn) {
[email protected]d01b8732008-10-16 02:18:071407 props.OverwriteWhereNeeded(node);
1408
1409 // The bool uploadOn is set to true if the data represented by current
1410 // node should be uploaded. This gets inherited in the tree; the children
1411 // of a node that has already been rejected for upload get rejected for
1412 // upload.
1413 uploadOn = uploadOn && NodeProbabilityTest(node, props);
1414
1415 // The path is a / separated list of the node names ancestral to the current
1416 // one. So, if you want to check if the current node has a certain name,
1417 // compare to name. If you want to check if it is a certan tag at a certain
1418 // place in the tree, compare to the whole path.
1419 std::string name = std::string(reinterpret_cast<const char*>(node->name));
1420 std::string path = path_prefix + "/" + name;
1421
1422 if (path == "/upload") {
1423 xmlChar* upload_interval_val = xmlGetProp(node, BAD_CAST "interval");
1424 if (upload_interval_val) {
1425 interlog_duration_ = TimeDelta::FromSeconds(
1426 atoi(reinterpret_cast<char*>(upload_interval_val)));
1427 }
1428
1429 server_permits_upload_ = uploadOn;
1430 }
1431 if (path == "/upload/logs") {
1432 xmlChar* log_event_limit_val = xmlGetProp(node, BAD_CAST "event_limit");
1433 if (log_event_limit_val)
1434 log_event_limit_ = atoi(reinterpret_cast<char*>(log_event_limit_val));
1435 }
1436 if (name == "histogram") {
1437 xmlChar* type_value = xmlGetProp(node, BAD_CAST "type");
1438 if (type_value) {
1439 std::string type = (reinterpret_cast<char*>(type_value));
1440 if (uploadOn)
1441 histograms_to_upload_.insert(type);
1442 else
1443 histograms_to_omit_.insert(type);
1444 }
1445 }
1446 if (name == "log") {
1447 xmlChar* type_value = xmlGetProp(node, BAD_CAST "type");
1448 if (type_value) {
1449 std::string type = (reinterpret_cast<char*>(type_value));
1450 if (uploadOn)
1451 logs_to_upload_.insert(type);
1452 else
1453 logs_to_omit_.insert(type);
1454 }
1455 }
1456
1457 // Recursive call. If the node is a leaf i.e. if it ends in a "/>", then it
1458 // doesn't have children, so node->children is NULL, and this loop doesn't
1459 // call (that's how the recursion ends).
1460 for (xmlNodePtr child_node = node->children;
[email protected]cac78842008-11-27 01:02:201461 child_node;
1462 child_node = child_node->next) {
[email protected]d01b8732008-10-16 02:18:071463 GetSettingsFromUploadNodeRecursive(child_node, props, path, uploadOn);
1464 }
1465}
1466
1467bool MetricsService::NodeProbabilityTest(xmlNodePtr node,
[email protected]cac78842008-11-27 01:02:201468 InheritedProperties props) const {
[email protected]d01b8732008-10-16 02:18:071469 // Default value of probability on any node is 1, but recall that
1470 // its parents can already have been rejected for upload.
1471 double probability = 1;
1472
1473 // If a probability is specified in the node, we use it instead.
1474 xmlChar* probability_value = xmlGetProp(node, BAD_CAST "probability");
1475 if (probability_value)
[email protected]0b33f80b2008-12-17 21:34:361476 probability = atoi(reinterpret_cast<char*>(probability_value));
[email protected]d01b8732008-10-16 02:18:071477
1478 return ProbabilityTest(probability, props.salt, props.denominator);
1479}
1480
1481bool MetricsService::ProbabilityTest(double probability,
1482 int salt,
1483 int denominator) const {
1484 // Okay, first we figure out how many of the digits of the
1485 // client_id_ we need in order to make a nice pseudorandomish
1486 // number in the range [0,denominator). Too many digits is
1487 // fine.
[email protected]d01b8732008-10-16 02:18:071488
1489 // n is the length of the client_id_ string
1490 size_t n = client_id_.size();
1491
1492 // idnumber is a positive integer generated from the client_id_.
1493 // It plus salt is going to give us our pseudorandom number.
1494 int idnumber = 0;
1495 const char* client_id_c_str = client_id_.c_str();
1496
1497 // Here we hash the relevant digits of the client_id_
1498 // string somehow to get a big integer idnumber (could be negative
1499 // from wraparound)
1500 int big = 1;
[email protected]cac78842008-11-27 01:02:201501 for (size_t j = n - 1; j >= 0; --j) {
1502 idnumber += static_cast<int>(client_id_c_str[j]) * big;
[email protected]d01b8732008-10-16 02:18:071503 big *= 10;
1504 }
1505
1506 // Mod id number by denominator making sure to get a non-negative
1507 // answer.
[email protected]cac78842008-11-27 01:02:201508 idnumber = ((idnumber % denominator) + denominator) % denominator;
[email protected]d01b8732008-10-16 02:18:071509
[email protected]cac78842008-11-27 01:02:201510 // ((idnumber + salt) % denominator) / denominator is in the range [0,1]
[email protected]d01b8732008-10-16 02:18:071511 // if it's less than probability we call that an affirmative coin
1512 // toss.
[email protected]cac78842008-11-27 01:02:201513 return static_cast<double>((idnumber + salt) % denominator) <
1514 probability * denominator;
[email protected]d01b8732008-10-16 02:18:071515}
1516
initial.commit09911bf2008-07-26 23:55:291517void MetricsService::LogWindowChange(NotificationType type,
1518 const NotificationSource& source,
1519 const NotificationDetails& details) {
[email protected]534e54b2008-08-13 15:40:091520 int controller_id = -1;
1521 uintptr_t window_or_tab = source.map_key();
initial.commit09911bf2008-07-26 23:55:291522 MetricsLog::WindowEventType window_type;
1523
1524 // Note: since we stop all logging when a single OTR session is active, it is
1525 // possible that we start getting notifications about a window that we don't
1526 // know about.
[email protected]534e54b2008-08-13 15:40:091527 if (window_map_.find(window_or_tab) == window_map_.end()) {
1528 controller_id = next_window_id_++;
1529 window_map_[window_or_tab] = controller_id;
initial.commit09911bf2008-07-26 23:55:291530 } else {
[email protected]534e54b2008-08-13 15:40:091531 controller_id = window_map_[window_or_tab];
initial.commit09911bf2008-07-26 23:55:291532 }
[email protected]534e54b2008-08-13 15:40:091533 DCHECK(controller_id != -1);
initial.commit09911bf2008-07-26 23:55:291534
[email protected]bfd04a62009-02-01 18:16:561535 switch (type.value) {
1536 case NotificationType::TAB_PARENTED:
1537 case NotificationType::BROWSER_OPENED:
initial.commit09911bf2008-07-26 23:55:291538 window_type = MetricsLog::WINDOW_CREATE;
1539 break;
1540
[email protected]bfd04a62009-02-01 18:16:561541 case NotificationType::TAB_CLOSING:
1542 case NotificationType::BROWSER_CLOSED:
[email protected]534e54b2008-08-13 15:40:091543 window_map_.erase(window_map_.find(window_or_tab));
initial.commit09911bf2008-07-26 23:55:291544 window_type = MetricsLog::WINDOW_DESTROY;
1545 break;
1546
1547 default:
1548 NOTREACHED();
[email protected]68d74f02009-02-13 01:36:501549 return;
initial.commit09911bf2008-07-26 23:55:291550 }
1551
[email protected]534e54b2008-08-13 15:40:091552 // TODO(brettw) we should have some kind of ID for the parent.
1553 current_log_->RecordWindowEvent(window_type, controller_id, 0);
initial.commit09911bf2008-07-26 23:55:291554}
1555
1556void MetricsService::LogLoadComplete(NotificationType type,
1557 const NotificationSource& source,
1558 const NotificationDetails& details) {
1559 if (details == NotificationService::NoDetails())
1560 return;
1561
[email protected]68475e602008-08-22 03:21:151562 // TODO(jar): There is a bug causing this to be called too many times, and
1563 // the log overflows. For now, we won't record these events.
[email protected]553dba62009-02-24 19:08:231564 UMA_HISTOGRAM_COUNTS("UMA.LogLoadComplete called", 1);
[email protected]68475e602008-08-22 03:21:151565 return;
1566
initial.commit09911bf2008-07-26 23:55:291567 const Details<LoadNotificationDetails> load_details(details);
[email protected]534e54b2008-08-13 15:40:091568 int controller_id = window_map_[details.map_key()];
1569 current_log_->RecordLoadEvent(controller_id,
initial.commit09911bf2008-07-26 23:55:291570 load_details->url(),
1571 load_details->origin(),
1572 load_details->session_index(),
1573 load_details->load_time());
1574}
1575
[email protected]e73c01972008-08-13 00:18:241576void MetricsService::IncrementPrefValue(const wchar_t* path) {
1577 PrefService* pref = g_browser_process->local_state();
1578 DCHECK(pref);
1579 int value = pref->GetInteger(path);
1580 pref->SetInteger(path, value + 1);
1581}
1582
[email protected]0bb1a622009-03-04 03:22:321583void MetricsService::IncrementLongPrefsValue(const wchar_t* path) {
1584 PrefService* pref = g_browser_process->local_state();
1585 DCHECK(pref);
1586 int64 value = pref->GetInt64(path);
1587 pref->SetInt64(path, value+1);
1588}
1589
initial.commit09911bf2008-07-26 23:55:291590void MetricsService::LogLoadStarted() {
[email protected]e73c01972008-08-13 00:18:241591 IncrementPrefValue(prefs::kStabilityPageLoadCount);
[email protected]0bb1a622009-03-04 03:22:321592 IncrementLongPrefsValue(prefs::kUninstallMetricsPageLoadCount);
[email protected]0b33f80b2008-12-17 21:34:361593 // We need to save the prefs, as page load count is a critical stat, and it
1594 // might be lost due to a crash :-(.
initial.commit09911bf2008-07-26 23:55:291595}
1596
1597void MetricsService::LogRendererInSandbox(bool on_sandbox_desktop) {
1598 PrefService* prefs = g_browser_process->local_state();
1599 DCHECK(prefs);
[email protected]e73c01972008-08-13 00:18:241600 if (on_sandbox_desktop)
1601 IncrementPrefValue(prefs::kSecurityRendererOnSboxDesktop);
1602 else
1603 IncrementPrefValue(prefs::kSecurityRendererOnDefaultDesktop);
initial.commit09911bf2008-07-26 23:55:291604}
1605
1606void MetricsService::LogRendererCrash() {
[email protected]e73c01972008-08-13 00:18:241607 IncrementPrefValue(prefs::kStabilityRendererCrashCount);
initial.commit09911bf2008-07-26 23:55:291608}
1609
1610void MetricsService::LogRendererHang() {
[email protected]e73c01972008-08-13 00:18:241611 IncrementPrefValue(prefs::kStabilityRendererHangCount);
initial.commit09911bf2008-07-26 23:55:291612}
1613
[email protected]a27a9382009-02-11 23:55:101614void MetricsService::LogChildProcessChange(
1615 NotificationType type,
1616 const NotificationSource& source,
1617 const NotificationDetails& details) {
1618 const std::wstring& child_name =
1619 Details<ChildProcessInfo>(details)->name();
initial.commit09911bf2008-07-26 23:55:291620
[email protected]a27a9382009-02-11 23:55:101621 if (child_process_stats_buffer_.find(child_name) ==
1622 child_process_stats_buffer_.end()) {
1623 child_process_stats_buffer_[child_name] = ChildProcessStats();
initial.commit09911bf2008-07-26 23:55:291624 }
1625
[email protected]a27a9382009-02-11 23:55:101626 ChildProcessStats& stats = child_process_stats_buffer_[child_name];
[email protected]bfd04a62009-02-01 18:16:561627 switch (type.value) {
[email protected]a27a9382009-02-11 23:55:101628 case NotificationType::CHILD_PROCESS_HOST_CONNECTED:
initial.commit09911bf2008-07-26 23:55:291629 stats.process_launches++;
1630 break;
1631
[email protected]a27a9382009-02-11 23:55:101632 case NotificationType::CHILD_INSTANCE_CREATED:
initial.commit09911bf2008-07-26 23:55:291633 stats.instances++;
1634 break;
1635
[email protected]a27a9382009-02-11 23:55:101636 case NotificationType::CHILD_PROCESS_CRASHED:
initial.commit09911bf2008-07-26 23:55:291637 stats.process_crashes++;
1638 break;
1639
1640 default:
[email protected]bfd04a62009-02-01 18:16:561641 NOTREACHED() << "Unexpected notification type " << type.value;
initial.commit09911bf2008-07-26 23:55:291642 return;
1643 }
1644}
1645
1646// Recursively counts the number of bookmarks and folders in node.
[email protected]d8e41ed2008-09-11 15:22:321647static void CountBookmarks(BookmarkNode* node, int* bookmarks, int* folders) {
initial.commit09911bf2008-07-26 23:55:291648 if (node->GetType() == history::StarredEntry::URL)
1649 (*bookmarks)++;
1650 else
1651 (*folders)++;
1652 for (int i = 0; i < node->GetChildCount(); ++i)
1653 CountBookmarks(node->GetChild(i), bookmarks, folders);
1654}
1655
[email protected]d8e41ed2008-09-11 15:22:321656void MetricsService::LogBookmarks(BookmarkNode* node,
initial.commit09911bf2008-07-26 23:55:291657 const wchar_t* num_bookmarks_key,
1658 const wchar_t* num_folders_key) {
1659 DCHECK(node);
1660 int num_bookmarks = 0;
1661 int num_folders = 0;
1662 CountBookmarks(node, &num_bookmarks, &num_folders);
1663 num_folders--; // Don't include the root folder in the count.
1664
1665 PrefService* pref = g_browser_process->local_state();
1666 DCHECK(pref);
1667 pref->SetInteger(num_bookmarks_key, num_bookmarks);
1668 pref->SetInteger(num_folders_key, num_folders);
1669}
1670
[email protected]d8e41ed2008-09-11 15:22:321671void MetricsService::LogBookmarks(BookmarkModel* model) {
initial.commit09911bf2008-07-26 23:55:291672 DCHECK(model);
1673 LogBookmarks(model->GetBookmarkBarNode(),
1674 prefs::kNumBookmarksOnBookmarkBar,
1675 prefs::kNumFoldersOnBookmarkBar);
1676 LogBookmarks(model->other_node(),
1677 prefs::kNumBookmarksInOtherBookmarkFolder,
1678 prefs::kNumFoldersInOtherBookmarkFolder);
1679 ScheduleNextStateSave();
1680}
1681
1682void MetricsService::LogKeywords(const TemplateURLModel* url_model) {
1683 DCHECK(url_model);
1684
1685 PrefService* pref = g_browser_process->local_state();
1686 DCHECK(pref);
1687 pref->SetInteger(prefs::kNumKeywords,
1688 static_cast<int>(url_model->GetTemplateURLs().size()));
1689 ScheduleNextStateSave();
1690}
1691
1692void MetricsService::RecordPluginChanges(PrefService* pref) {
1693 ListValue* plugins = pref->GetMutableList(prefs::kStabilityPluginStats);
1694 DCHECK(plugins);
1695
1696 for (ListValue::iterator value_iter = plugins->begin();
1697 value_iter != plugins->end(); ++value_iter) {
1698 if (!(*value_iter)->IsType(Value::TYPE_DICTIONARY)) {
1699 NOTREACHED();
1700 continue;
1701 }
1702
1703 DictionaryValue* plugin_dict = static_cast<DictionaryValue*>(*value_iter);
[email protected]8e50b602009-03-03 22:59:431704 std::wstring plugin_name;
1705 plugin_dict->GetString(prefs::kStabilityPluginName, &plugin_name);
[email protected]6470ee8f2009-03-03 20:46:401706 if (plugin_name.empty()) {
initial.commit09911bf2008-07-26 23:55:291707 NOTREACHED();
1708 continue;
1709 }
1710
[email protected]8e50b602009-03-03 22:59:431711 if (child_process_stats_buffer_.find(plugin_name) ==
[email protected]a27a9382009-02-11 23:55:101712 child_process_stats_buffer_.end())
initial.commit09911bf2008-07-26 23:55:291713 continue;
1714
[email protected]8e50b602009-03-03 22:59:431715 ChildProcessStats stats = child_process_stats_buffer_[plugin_name];
initial.commit09911bf2008-07-26 23:55:291716 if (stats.process_launches) {
1717 int launches = 0;
[email protected]8e50b602009-03-03 22:59:431718 plugin_dict->GetInteger(prefs::kStabilityPluginLaunches, &launches);
initial.commit09911bf2008-07-26 23:55:291719 launches += stats.process_launches;
[email protected]8e50b602009-03-03 22:59:431720 plugin_dict->SetInteger(prefs::kStabilityPluginLaunches, launches);
initial.commit09911bf2008-07-26 23:55:291721 }
1722 if (stats.process_crashes) {
1723 int crashes = 0;
[email protected]8e50b602009-03-03 22:59:431724 plugin_dict->GetInteger(prefs::kStabilityPluginCrashes, &crashes);
initial.commit09911bf2008-07-26 23:55:291725 crashes += stats.process_crashes;
[email protected]8e50b602009-03-03 22:59:431726 plugin_dict->SetInteger(prefs::kStabilityPluginCrashes, crashes);
initial.commit09911bf2008-07-26 23:55:291727 }
1728 if (stats.instances) {
1729 int instances = 0;
[email protected]8e50b602009-03-03 22:59:431730 plugin_dict->GetInteger(prefs::kStabilityPluginInstances, &instances);
initial.commit09911bf2008-07-26 23:55:291731 instances += stats.instances;
[email protected]8e50b602009-03-03 22:59:431732 plugin_dict->SetInteger(prefs::kStabilityPluginInstances, instances);
initial.commit09911bf2008-07-26 23:55:291733 }
1734
[email protected]8e50b602009-03-03 22:59:431735 child_process_stats_buffer_.erase(plugin_name);
initial.commit09911bf2008-07-26 23:55:291736 }
1737
1738 // Now go through and add dictionaries for plugins that didn't already have
1739 // reports in Local State.
[email protected]a27a9382009-02-11 23:55:101740 for (std::map<std::wstring, ChildProcessStats>::iterator cache_iter =
1741 child_process_stats_buffer_.begin();
1742 cache_iter != child_process_stats_buffer_.end(); ++cache_iter) {
1743 std::wstring plugin_name = cache_iter->first;
1744 ChildProcessStats stats = cache_iter->second;
initial.commit09911bf2008-07-26 23:55:291745 DictionaryValue* plugin_dict = new DictionaryValue;
1746
[email protected]8e50b602009-03-03 22:59:431747 plugin_dict->SetString(prefs::kStabilityPluginName, plugin_name);
1748 plugin_dict->SetInteger(prefs::kStabilityPluginLaunches,
initial.commit09911bf2008-07-26 23:55:291749 stats.process_launches);
[email protected]8e50b602009-03-03 22:59:431750 plugin_dict->SetInteger(prefs::kStabilityPluginCrashes,
initial.commit09911bf2008-07-26 23:55:291751 stats.process_crashes);
[email protected]8e50b602009-03-03 22:59:431752 plugin_dict->SetInteger(prefs::kStabilityPluginInstances,
initial.commit09911bf2008-07-26 23:55:291753 stats.instances);
1754 plugins->Append(plugin_dict);
1755 }
[email protected]a27a9382009-02-11 23:55:101756 child_process_stats_buffer_.clear();
initial.commit09911bf2008-07-26 23:55:291757}
1758
1759bool MetricsService::CanLogNotification(NotificationType type,
1760 const NotificationSource& source,
1761 const NotificationDetails& details) {
1762 // We simply don't log anything to UMA if there is a single off the record
1763 // session visible. The problem is that we always notify using the orginal
1764 // profile in order to simplify notification processing.
1765 return !BrowserList::IsOffTheRecordSessionActive();
1766}
1767
1768void MetricsService::RecordBooleanPrefValue(const wchar_t* path, bool value) {
1769 DCHECK(IsSingleThreaded());
1770
1771 PrefService* pref = g_browser_process->local_state();
1772 DCHECK(pref);
1773
1774 pref->SetBoolean(path, value);
1775 RecordCurrentState(pref);
1776}
1777
1778void MetricsService::RecordCurrentState(PrefService* pref) {
[email protected]0bb1a622009-03-04 03:22:321779 pref->SetInt64(prefs::kStabilityLastTimestampSec, Time::Now().ToTimeT());
initial.commit09911bf2008-07-26 23:55:291780
1781 RecordPluginChanges(pref);
1782}
1783
[email protected]55e57d42009-02-25 06:10:171784void MetricsService::CollectRendererHistograms() {
1785 for (RenderProcessHost::iterator it = RenderProcessHost::begin();
1786 it != RenderProcessHost::end(); ++it) {
1787 it->second->Send(new ViewMsg_GetRendererHistograms());
1788 }
1789}
1790
initial.commit09911bf2008-07-26 23:55:291791void MetricsService::RecordCurrentHistograms() {
1792 DCHECK(current_log_);
1793
[email protected]55e57d42009-02-25 06:10:171794 CollectRendererHistograms();
1795
1796 // TODO(raman): Delay the metrics collection activities until we get all the
1797 // updates from the renderers, or we time out (1 second? 3 seconds?).
1798
initial.commit09911bf2008-07-26 23:55:291799 StatisticsRecorder::Histograms histograms;
1800 StatisticsRecorder::GetHistograms(&histograms);
1801 for (StatisticsRecorder::Histograms::iterator it = histograms.begin();
1802 histograms.end() != it;
[email protected]cac78842008-11-27 01:02:201803 ++it) {
initial.commit09911bf2008-07-26 23:55:291804 if ((*it)->flags() & kUmaTargetedHistogramFlag)
[email protected]0b33f80b2008-12-17 21:34:361805 // TODO(petersont): Only record historgrams if they are not precluded by
1806 // the UMA response data.
[email protected]d01b8732008-10-16 02:18:071807 // Bug http://code.google.com/p/chromium/issues/detail?id=2739.
initial.commit09911bf2008-07-26 23:55:291808 RecordHistogram(**it);
1809 }
1810}
1811
1812void MetricsService::RecordHistogram(const Histogram& histogram) {
1813 // Get up-to-date snapshot of sample stats.
1814 Histogram::SampleSet snapshot;
1815 histogram.SnapshotSample(&snapshot);
1816
1817 const std::string& histogram_name = histogram.histogram_name();
1818
1819 // Find the already sent stats, or create an empty set.
1820 LoggedSampleMap::iterator it = logged_samples_.find(histogram_name);
1821 Histogram::SampleSet* already_logged;
1822 if (logged_samples_.end() == it) {
1823 // Add new entry
1824 already_logged = &logged_samples_[histogram.histogram_name()];
1825 already_logged->Resize(histogram); // Complete initialization.
1826 } else {
1827 already_logged = &(it->second);
1828 // Deduct any stats we've already logged from our snapshot.
1829 snapshot.Subtract(*already_logged);
1830 }
1831
1832 // snapshot now contains only a delta to what we've already_logged.
1833
1834 if (snapshot.TotalCount() > 0) {
1835 current_log_->RecordHistogramDelta(histogram, snapshot);
1836 // Add new data into our running total.
1837 already_logged->Add(snapshot);
1838 }
1839}
1840
1841void MetricsService::AddProfileMetric(Profile* profile,
1842 const std::wstring& key,
1843 int value) {
1844 // Restriction of types is needed for writing values. See
1845 // MetricsLog::WriteProfileMetrics.
1846 DCHECK(profile && !key.empty());
1847 PrefService* prefs = g_browser_process->local_state();
1848 DCHECK(prefs);
1849
1850 // Key is stored in prefs, which interpret '.'s as paths. As such, key
1851 // shouldn't have any '.'s in it.
1852 DCHECK(key.find(L'.') == std::wstring::npos);
1853 // The id is most likely an email address. We shouldn't send it to the server.
1854 const std::wstring id_hash =
1855 UTF8ToWide(MetricsLog::CreateBase64Hash(WideToUTF8(profile->GetID())));
1856 DCHECK(id_hash.find('.') == std::string::npos);
1857
1858 DictionaryValue* prof_prefs = prefs->GetMutableDictionary(
1859 prefs::kProfileMetrics);
1860 DCHECK(prof_prefs);
1861 const std::wstring pref_key = std::wstring(prefs::kProfilePrefix) + id_hash +
1862 L"." + key;
[email protected]8e50b602009-03-03 22:59:431863 prof_prefs->SetInteger(pref_key.c_str(), value);
initial.commit09911bf2008-07-26 23:55:291864}
1865
1866static bool IsSingleThreaded() {
[email protected]dc6f4962009-02-13 01:25:501867 static PlatformThreadId thread_id = 0;
initial.commit09911bf2008-07-26 23:55:291868 if (!thread_id)
[email protected]dc6f4962009-02-13 01:25:501869 thread_id = PlatformThread::CurrentId();
1870 return PlatformThread::CurrentId() == thread_id;
initial.commit09911bf2008-07-26 23:55:291871}