Commit 69fc4705 authored by ananta@chromium.org's avatar ananta@chromium.org

Preparation CL for adding crash metrics UMA counters to ChromeFrame. Basically...

Preparation CL for adding crash metrics UMA counters to ChromeFrame. Basically this would mean that metrics reporting would be done directly
by ChromeFrame. Currently ChromeFrame uses Chrome to upload this data. 

Refactored the chrome metrics service and metrics logging functionality into base classes defined in chrome\common\metrics_helpers.cc/.h. While
this refactoring is by no means complete it is a first step to avoid needless code duplication between chrome and chrome frame.

Bug=46057

Review URL: http://codereview.chromium.org/2744003

git-svn-id: svn://svn.chromium.org/chrome/trunk/src@49354 0039d316-1c4b-4281-b951-d872f2087c98
parent 2145dc05
This diff is collapsed.
...@@ -8,14 +8,8 @@ ...@@ -8,14 +8,8 @@
#ifndef CHROME_BROWSER_METRICS_METRICS_LOG_H_ #ifndef CHROME_BROWSER_METRICS_METRICS_LOG_H_
#define CHROME_BROWSER_METRICS_METRICS_LOG_H_ #define CHROME_BROWSER_METRICS_METRICS_LOG_H_
#include <libxml/xmlwriter.h>
#include <string>
#include <vector>
#include "base/basictypes.h" #include "base/basictypes.h"
#include "base/histogram.h" #include "chrome/common/metrics_helpers.h"
#include "base/time.h"
#include "chrome/common/page_transition_types.h" #include "chrome/common/page_transition_types.h"
#include "webkit/glue/plugins/webplugininfo.h" #include "webkit/glue/plugins/webplugininfo.h"
...@@ -24,7 +18,7 @@ class DictionaryValue; ...@@ -24,7 +18,7 @@ class DictionaryValue;
class GURL; class GURL;
class PrefService; class PrefService;
class MetricsLog { class MetricsLog : public MetricsLogBase {
public: public:
// Creates a new metrics log // Creates a new metrics log
// client_id is the identifier for this profile on this installation // client_id is the identifier for this profile on this installation
...@@ -34,29 +28,6 @@ class MetricsLog { ...@@ -34,29 +28,6 @@ class MetricsLog {
static void RegisterPrefs(PrefService* prefs); static void RegisterPrefs(PrefService* prefs);
// Records a user-initiated action.
void RecordUserAction(const char* key);
enum WindowEventType {
WINDOW_CREATE = 0,
WINDOW_OPEN,
WINDOW_CLOSE,
WINDOW_DESTROY
};
void RecordWindowEvent(WindowEventType type, int window_id, int parent_id);
// Records a page load.
// window_id - the index of the tab in which the load took place
// url - which URL was loaded
// origin - what kind of action initiated the load
// load_time - how long it took to load the page
void RecordLoadEvent(int window_id,
const GURL& url,
PageTransition::Type origin,
int session_index,
base::TimeDelta load_time);
// Records the current operating environment. Takes the list of installed // Records the current operating environment. Takes the list of installed
// plugins as a parameter because that can't be obtained synchronously // plugins as a parameter because that can't be obtained synchronously
// from the UI thread. // from the UI thread.
...@@ -70,113 +41,33 @@ class MetricsLog { ...@@ -70,113 +41,33 @@ class MetricsLog {
// user uses the Omnibox to open a URL. // user uses the Omnibox to open a URL.
void RecordOmniboxOpenedURL(const AutocompleteLog& log); void RecordOmniboxOpenedURL(const AutocompleteLog& log);
// Record any changes in a given histogram for transmission.
void RecordHistogramDelta(const Histogram& histogram,
const Histogram::SampleSet& snapshot);
// Record recent delta for critical stability metrics. We can't wait for a // Record recent delta for critical stability metrics. We can't wait for a
// restart to gather these, as that delay biases our observation away from // restart to gather these, as that delay biases our observation away from
// users that run happily for a looooong time. We send increments with each // users that run happily for a looooong time. We send increments with each
// uma log upload, just as we send histogram data. // uma log upload, just as we send histogram data.
void RecordIncrementalStabilityElements(); void RecordIncrementalStabilityElements();
// Stop writing to this record and generate the encoded representation.
// None of the Record* methods can be called after this is called.
void CloseLog();
// These methods allow retrieval of the encoded representation of the
// record. They can only be called after CloseLog() has been called.
// GetEncodedLog returns false if buffer_size is less than
// GetEncodedLogSize();
int GetEncodedLogSize();
bool GetEncodedLog(char* buffer, int buffer_size);
// Returns the amount of time in seconds that this log has been in use.
int GetElapsedSeconds();
int num_events() { return num_events_; }
void set_hardware_class(const std::string& hardware_class) { void set_hardware_class(const std::string& hardware_class) {
hardware_class_ = hardware_class; hardware_class_ = hardware_class;
} }
// Creates an MD5 hash of the given value, and returns hash as a byte
// buffer encoded as a std::string.
static std::string CreateHash(const std::string& value);
// Return a base64-encoded MD5 hash of the given string.
static std::string CreateBase64Hash(const std::string& string);
// Get the current version of the application as a string.
static std::string GetVersionString();
// Get the GMT buildtime for the current binary, expressed in seconds since
// January 1, 1970 GMT.
// The value is used to identify when a new build is run, so that previous
// reliability stats, from other builds, can be abandoned.
static int64 GetBuildTime();
// Get the amount of uptime in seconds since this function was last called. // Get the amount of uptime in seconds since this function was last called.
// This updates the cumulative uptime metric for uninstall as a side effect. // This updates the cumulative uptime metric for uninstall as a side effect.
static int64 GetIncrementalUptime(PrefService* pref); static int64 GetIncrementalUptime(PrefService* pref);
// Use |extension| in all uploaded appversions in addition to the standard // Get the current version of the application as a string.
// version string. static std::string GetVersionString();
static void set_version_extension(const std::string& extension) {
version_extension_ = extension;
}
protected: virtual MetricsLog* AsMetricsLog() {
// Returns a string containing the current time. return this;
// Virtual so that it can be overridden for testing. }
virtual std::string GetCurrentTimeString();
private: private:
// Helper class that invokes StartElement from constructor, and EndElement
// from destructor.
//
// Use the macro OPEN_ELEMENT_FOR_SCOPE to help avoid usage problems.
class ScopedElement {
public:
ScopedElement(MetricsLog* log, const std::string& name) : log_(log) {
DCHECK(log);
log->StartElement(name.c_str());
}
ScopedElement(MetricsLog* log, const char* name) : log_(log) {
DCHECK(log);
log->StartElement(name);
}
~ScopedElement() {
log_->EndElement();
}
private:
MetricsLog* log_;
};
friend class ScopedElement;
static const char* WindowEventTypeToString(WindowEventType type);
// Frees the resources allocated by the XML document writer: the
// main writer object as well as the XML tree structure, if
// applicable.
void FreeDocWriter();
// Convenience versions of xmlWriter functions
void StartElement(const char* name);
void EndElement();
void WriteAttribute(const std::string& name, const std::string& value);
void WriteIntAttribute(const std::string& name, int value);
void WriteInt64Attribute(const std::string& name, int64 value);
// Write the attributes that are common to every metrics event type.
void WriteCommonEventAttributes();
// Returns the date at which the current metrics client ID was created as // Returns the date at which the current metrics client ID was created as
// a string containing milliseconds since the epoch, or "0" if none was found. // a string containing milliseconds since the epoch, or "0" if none was found.
std::string GetInstallDate() const; std::string GetInstallDate() const;
// Writes application stability metrics (as part of the profile log). // Writes application stability metrics (as part of the profile log).
// NOTE: Has the side-effect of clearing those counts. // NOTE: Has the side-effect of clearing those counts.
void WriteStabilityElement(); void WriteStabilityElement();
...@@ -208,26 +99,8 @@ class MetricsLog { ...@@ -208,26 +99,8 @@ class MetricsLog {
void WriteProfileMetrics(const std::wstring& key, void WriteProfileMetrics(const std::wstring& key,
const DictionaryValue& profile_metrics); const DictionaryValue& profile_metrics);
// An extension that is appended to the appversion in each log.
static std::string version_extension_;
base::Time start_time_;
base::Time end_time_;
std::string client_id_;
std::string session_id_;
std::string hardware_class_; std::string hardware_class_;
// locked_ is true when record has been packed up for sending, and should
// no longer be written to. It is only used for sanity checking and is
// not a real lock.
bool locked_;
xmlDocPtr doc_;
xmlBufferPtr buffer_;
xmlTextWriterPtr writer_;
int num_events_; // the number of events recorded in this log
DISALLOW_COPY_AND_ASSIGN(MetricsLog); DISALLOW_COPY_AND_ASSIGN(MetricsLog);
}; };
......
...@@ -408,15 +408,11 @@ MetricsService::MetricsService() ...@@ -408,15 +408,11 @@ MetricsService::MetricsService()
user_permits_upload_(false), user_permits_upload_(false),
server_permits_upload_(true), server_permits_upload_(true),
state_(INITIALIZED), state_(INITIALIZED),
pending_log_(NULL),
pending_log_text_(),
current_fetch_(NULL), current_fetch_(NULL),
current_log_(NULL),
idle_since_last_transmission_(false), idle_since_last_transmission_(false),
next_window_id_(0), next_window_id_(0),
ALLOW_THIS_IN_INITIALIZER_LIST(log_sender_factory_(this)), ALLOW_THIS_IN_INITIALIZER_LIST(log_sender_factory_(this)),
ALLOW_THIS_IN_INITIALIZER_LIST(state_saver_factory_(this)), ALLOW_THIS_IN_INITIALIZER_LIST(state_saver_factory_(this)),
logged_samples_(),
interlog_duration_(TimeDelta::FromSeconds(kInitialInterlogDuration)), interlog_duration_(TimeDelta::FromSeconds(kInitialInterlogDuration)),
log_event_limit_(kInitialEventLimit), log_event_limit_(kInitialEventLimit),
timer_pending_(false) { timer_pending_(false) {
...@@ -426,14 +422,6 @@ MetricsService::MetricsService() ...@@ -426,14 +422,6 @@ MetricsService::MetricsService()
MetricsService::~MetricsService() { MetricsService::~MetricsService() {
SetRecording(false); SetRecording(false);
if (pending_log_) {
delete pending_log_;
pending_log_ = NULL;
}
if (current_log_) {
delete current_log_;
current_log_ = NULL;
}
} }
void MetricsService::SetUserPermitsUpload(bool enabled) { void MetricsService::SetUserPermitsUpload(bool enabled) {
...@@ -597,10 +585,13 @@ void MetricsService::Observe(NotificationType type, ...@@ -597,10 +585,13 @@ void MetricsService::Observe(NotificationType type,
LogKeywords(Source<TemplateURLModel>(source).ptr()); LogKeywords(Source<TemplateURLModel>(source).ptr());
break; break;
case NotificationType::OMNIBOX_OPENED_URL: case NotificationType::OMNIBOX_OPENED_URL: {
current_log_->RecordOmniboxOpenedURL( MetricsLog* current_log = current_log_->AsMetricsLog();
DCHECK(current_log);
current_log->RecordOmniboxOpenedURL(
*Details<AutocompleteLog>(details).ptr()); *Details<AutocompleteLog>(details).ptr());
break; break;
}
case NotificationType::BOOKMARK_MODEL_LOADED: { case NotificationType::BOOKMARK_MODEL_LOADED: {
Profile* p = Source<Profile>(source).ptr(); Profile* p = Source<Profile>(source).ptr();
...@@ -848,11 +839,13 @@ void MetricsService::StartRecording() { ...@@ -848,11 +839,13 @@ void MetricsService::StartRecording() {
} }
} }
void MetricsService::StopRecording(MetricsLog** log) { void MetricsService::StopRecording(MetricsLogBase** log) {
if (!current_log_) if (!current_log_)
return; return;
current_log_->set_hardware_class(hardware_class_); // Adds to ongoing logs. MetricsLog* current_log = current_log_->AsMetricsLog();
DCHECK(current_log);
current_log->set_hardware_class(hardware_class_); // Adds to ongoing logs.
// TODO(jar): Integrate bounds on log recording more consistently, so that we // TODO(jar): Integrate bounds on log recording more consistently, so that we
// can stop recording logs that are too big much sooner. // can stop recording logs that are too big much sooner.
...@@ -869,13 +862,13 @@ void MetricsService::StopRecording(MetricsLog** log) { ...@@ -869,13 +862,13 @@ void MetricsService::StopRecording(MetricsLog** log) {
// end of all log transmissions (initial log handles this separately). // end of all log transmissions (initial log handles this separately).
// Don't bother if we're going to discard current_log_. // Don't bother if we're going to discard current_log_.
if (log) { if (log) {
current_log_->RecordIncrementalStabilityElements(); current_log->RecordIncrementalStabilityElements();
RecordCurrentHistograms(); RecordCurrentHistograms();
} }
current_log_->CloseLog(); current_log_->CloseLog();
if (log) if (log)
*log = current_log_; *log = current_log;
else else
delete current_log_; delete current_log_;
current_log_ = NULL; current_log_ = NULL;
...@@ -1141,7 +1134,7 @@ void MetricsService::PrepareInitialLog() { ...@@ -1141,7 +1134,7 @@ void MetricsService::PrepareInitialLog() {
log->RecordEnvironment(plugins_, profile_dictionary_.get()); log->RecordEnvironment(plugins_, profile_dictionary_.get());
// Histograms only get written to current_log_, so setup for the write. // Histograms only get written to current_log_, so setup for the write.
MetricsLog* save_log = current_log_; MetricsLogBase* save_log = current_log_;
current_log_ = log; current_log_ = log;
RecordCurrentHistograms(); // Into current_log_... which is really log. RecordCurrentHistograms(); // Into current_log_... which is really log.
current_log_ = save_log; current_log_ = save_log;
...@@ -1240,53 +1233,6 @@ void MetricsService::PrepareFetchWithPendingLog() { ...@@ -1240,53 +1233,6 @@ void MetricsService::PrepareFetchWithPendingLog() {
current_fetch_->set_upload_data(kMetricsType, compressed_log); current_fetch_->set_upload_data(kMetricsType, compressed_log);
} }
void MetricsService::DiscardPendingLog() {
if (pending_log_) { // Shutdown might have deleted it!
delete pending_log_;
pending_log_ = NULL;
}
pending_log_text_.clear();
}
// This implementation is based on the Firefox MetricsService implementation.
bool MetricsService::Bzip2Compress(const std::string& input,
std::string* output) {
bz_stream stream = {0};
// As long as our input is smaller than the bzip2 block size, we should get
// the best compression. For example, if your input was 250k, using a block
// size of 300k or 500k should result in the same compression ratio. Since
// our data should be under 100k, using the minimum block size of 100k should
// allocate less temporary memory, but result in the same compression ratio.
int result = BZ2_bzCompressInit(&stream,
1, // 100k (min) block size
0, // quiet
0); // default "work factor"
if (result != BZ_OK) { // out of memory?
return false;
}
output->clear();
stream.next_in = const_cast<char*>(input.data());
stream.avail_in = static_cast<int>(input.size());
// NOTE: we don't need a BZ_RUN phase since our input buffer contains
// the entire input
do {
output->resize(output->size() + 1024);
stream.next_out = &((*output)[stream.total_out_lo32]);
stream.avail_out = static_cast<int>(output->size()) - stream.total_out_lo32;
result = BZ2_bzCompress(&stream, BZ_FINISH);
} while (result == BZ_FINISH_OK);
if (result != BZ_STREAM_END) // unknown failure?
return false;
result = BZ2_bzCompressEnd(&stream);
DCHECK(result == BZ_OK);
output->resize(stream.total_out_lo32);
return true;
}
static const char* StatusToString(const URLRequestStatus& status) { static const char* StatusToString(const URLRequestStatus& status) {
switch (status.status()) { switch (status.status()) {
case URLRequestStatus::SUCCESS: case URLRequestStatus::SUCCESS:
...@@ -1876,51 +1822,6 @@ void MetricsService::RecordCurrentState(PrefService* pref) { ...@@ -1876,51 +1822,6 @@ void MetricsService::RecordCurrentState(PrefService* pref) {
RecordPluginChanges(pref); RecordPluginChanges(pref);
} }
void MetricsService::RecordCurrentHistograms() {
DCHECK(current_log_);
StatisticsRecorder::Histograms histograms;
StatisticsRecorder::GetHistograms(&histograms);
for (StatisticsRecorder::Histograms::iterator it = histograms.begin();
histograms.end() != it;
++it) {
if ((*it)->flags() & Histogram::kUmaTargetedHistogramFlag)
// TODO(petersont): Only record historgrams if they are not precluded by
// the UMA response data.
// Bug http://code.google.com/p/chromium/issues/detail?id=2739.
RecordHistogram(**it);
}
}
void MetricsService::RecordHistogram(const Histogram& histogram) {
// Get up-to-date snapshot of sample stats.
Histogram::SampleSet snapshot;
histogram.SnapshotSample(&snapshot);
const std::string& histogram_name = histogram.histogram_name();
// Find the already sent stats, or create an empty set.
LoggedSampleMap::iterator it = logged_samples_.find(histogram_name);
Histogram::SampleSet* already_logged;
if (logged_samples_.end() == it) {
// Add new entry
already_logged = &logged_samples_[histogram.histogram_name()];
already_logged->Resize(histogram); // Complete initialization.
} else {
already_logged = &(it->second);
// Deduct any stats we've already logged from our snapshot.
snapshot.Subtract(*already_logged);
}
// snapshot now contains only a delta to what we've already_logged.
if (snapshot.TotalCount() > 0) {
current_log_->RecordHistogramDelta(histogram, snapshot);
// Add new data into our running total.
already_logged->Add(snapshot);
}
}
static bool IsSingleThreaded() { static bool IsSingleThreaded() {
static PlatformThreadId thread_id = 0; static PlatformThreadId thread_id = 0;
if (!thread_id) if (!thread_id)
......
...@@ -21,6 +21,7 @@ ...@@ -21,6 +21,7 @@
#include "base/values.h" #include "base/values.h"
#include "chrome/browser/metrics/metrics_log.h" #include "chrome/browser/metrics/metrics_log.h"
#include "chrome/common/child_process_info.h" #include "chrome/common/child_process_info.h"
#include "chrome/common/metrics_helpers.h"
#include "chrome/common/net/url_fetcher.h" #include "chrome/common/net/url_fetcher.h"
#include "chrome/common/notification_registrar.h" #include "chrome/common/notification_registrar.h"
#include "webkit/glue/plugins/webplugininfo.h" #include "webkit/glue/plugins/webplugininfo.h"
...@@ -70,7 +71,8 @@ struct ChildProcessStats { ...@@ -70,7 +71,8 @@ struct ChildProcessStats {
}; };
class MetricsService : public NotificationObserver, class MetricsService : public NotificationObserver,
public URLFetcher::Delegate { public URLFetcher::Delegate,
public MetricsServiceBase {
public: public:
MetricsService(); MetricsService();
virtual ~MetricsService(); virtual ~MetricsService();
...@@ -150,9 +152,6 @@ class MetricsService : public NotificationObserver, ...@@ -150,9 +152,6 @@ class MetricsService : public NotificationObserver,
SENDING_CURRENT_LOGS, // Sending standard current logs as they acrue. SENDING_CURRENT_LOGS, // Sending standard current logs as they acrue.
}; };
// Maintain a map of histogram names to the sample stats we've sent.
typedef std::map<std::string, Histogram::SampleSet> LoggedSampleMap;
class InitTask; class InitTask;
class InitTaskComplete; class InitTaskComplete;
...@@ -218,7 +217,7 @@ class MetricsService : public NotificationObserver, ...@@ -218,7 +217,7 @@ class MetricsService : public NotificationObserver,
// Called to stop recording user experience metrics. The caller takes // Called to stop recording user experience metrics. The caller takes
// ownership of the resulting MetricsLog object via the log parameter, // ownership of the resulting MetricsLog object via the log parameter,
// or passes in NULL to indicate that the log should simply be deleted. // or passes in NULL to indicate that the log should simply be deleted.
void StopRecording(MetricsLog** log); void StopRecording(MetricsLogBase** log);
// Deletes pending_log_ and current_log_, and pushes their text into the // Deletes pending_log_ and current_log_, and pushes their text into the
// appropriate unsent_log vectors. Called when Chrome shuts down. // appropriate unsent_log vectors. Called when Chrome shuts down.
...@@ -250,10 +249,6 @@ class MetricsService : public NotificationObserver, ...@@ -250,10 +249,6 @@ class MetricsService : public NotificationObserver,
// TryToStartTransmission. // TryToStartTransmission.
bool TransmissionPermitted() const; bool TransmissionPermitted() const;
// Check to see if there is a log that needs to be, or is being, transmitted.
bool pending_log() const {
return pending_log_ || !pending_log_text_.empty();
}
// Check to see if there are any unsent logs from previous sessions. // Check to see if there are any unsent logs from previous sessions.
bool unsent_logs() const { bool unsent_logs() const {
return !unsent_initial_logs_.empty() || !unsent_ongoing_logs_.empty(); return !unsent_initial_logs_.empty() || !unsent_ongoing_logs_.empty();
...@@ -270,11 +265,6 @@ class MetricsService : public NotificationObserver, ...@@ -270,11 +265,6 @@ class MetricsService : public NotificationObserver,
// a compressed copy of the pending log. // a compressed copy of the pending log.
void PrepareFetchWithPendingLog(); void PrepareFetchWithPendingLog();
// Discard pending_log_, and clear pending_log_text_. Called after processing
// of this log is complete.
void DiscardPendingLog();
// Compress the report log in input using bzip2, store the result in output.
bool Bzip2Compress(const std::string& input, std::string* output);
// Implementation of URLFetcher::Delegate. Called after transmission // Implementation of URLFetcher::Delegate. Called after transmission
// completes (either successfully or with failure). // completes (either successfully or with failure).
virtual void OnURLFetchComplete(const URLFetcher* source, virtual void OnURLFetchComplete(const URLFetcher* source,
...@@ -387,13 +377,6 @@ class MetricsService : public NotificationObserver, ...@@ -387,13 +377,6 @@ class MetricsService : public NotificationObserver,
// collecting stats from renderers. // collecting stats from renderers.
void CollectRendererHistograms(); void CollectRendererHistograms();
// Record complete list of histograms into the current log.
// Called when we close a log.
void RecordCurrentHistograms();
// Record a specific histogram .
void RecordHistogram(const Histogram& histogram);
// Logs the initiation of a page load // Logs the initiation of a page load
void LogLoadStarted(); void LogLoadStarted();
...@@ -441,20 +424,9 @@ class MetricsService : public NotificationObserver, ...@@ -441,20 +424,9 @@ class MetricsService : public NotificationObserver,
// The list of plugins which was retrieved on the file thread. // The list of plugins which was retrieved on the file thread.
std::vector<WebPluginInfo> plugins_; std::vector<WebPluginInfo> plugins_;
// A log that we are currently transmiting, or about to try to transmit.
MetricsLog* pending_log_;
// An alternate form of pending_log_. We persistently save this text version
// into prefs if we can't transmit it. As a result, sometimes all we have is
// the text version (recalled from a previous session).
std::string pending_log_text_;
// The outstanding transmission appears as a URL Fetch operation. // The outstanding transmission appears as a URL Fetch operation.
scoped_ptr<URLFetcher> current_fetch_; scoped_ptr<URLFetcher> current_fetch_;
// The log that we are still appending to.
MetricsLog* current_log_;
// The URL for the metrics server. // The URL for the metrics server.
std::wstring server_url_; std::wstring server_url_;
...@@ -496,10 +468,6 @@ class MetricsService : public NotificationObserver, ...@@ -496,10 +468,6 @@ class MetricsService : public NotificationObserver,
// at creation time from the prefs. // at creation time from the prefs.
scoped_ptr<DictionaryValue> profile_dictionary_; scoped_ptr<DictionaryValue> profile_dictionary_;
// For histograms, record what we've already logged (as a sample for each
// histogram) so that we can send only the delta with the next log.
MetricsService::LoggedSampleMap logged_samples_;
// The interval between consecutive log transmissions (to avoid hogging the // The interval between consecutive log transmissions (to avoid hogging the
// outbound network link). This is usually also the duration for which we // outbound network link). This is usually also the duration for which we
// build up a log, but if other unsent-logs from previous sessions exist, we // build up a log, but if other unsent-logs from previous sessions exist, we
......
...@@ -56,6 +56,8 @@ ...@@ -56,6 +56,8 @@
'common/main_function_params.h', 'common/main_function_params.h',
'common/message_router.cc', 'common/message_router.cc',
'common/message_router.h', 'common/message_router.h',
'common/metrics_helpers.cc',
'common/metrics_helpers.h',
'common/nacl_cmd_line.cc', 'common/nacl_cmd_line.cc',
'common/nacl_cmd_line.h', 'common/nacl_cmd_line.h',
'common/nacl_messages.h', 'common/nacl_messages.h',
...@@ -367,6 +369,7 @@ ...@@ -367,6 +369,7 @@
'../app/app.gyp:app_resources', '../app/app.gyp:app_resources',
'../base/base.gyp:base_nacl_win64', '../base/base.gyp:base_nacl_win64',
'../ipc/ipc.gyp:ipc_win64', '../ipc/ipc.gyp:ipc_win64',
'../third_party/libxml/libxml.gyp:libxml',
], ],
'include_dirs': [ 'include_dirs': [
'../third_party/npapi', '../third_party/npapi',
......
This diff is collapsed.
// Copyright (c) 2010 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
// This file defines a set of user experience metrics data recorded by
// the MetricsService. This is the unit of data that is sent to the server.
#ifndef CHROME_COMMON_METRICS_HELPERS_H_
#define CHROME_COMMON_METRICS_HELPERS_H_
#include <map>
#include <string>
#include <vector>
#include "base/basictypes.h"
#include "base/histogram.h"
#include "base/time.h"
#include "chrome/common/page_transition_types.h"
#include "libxml/xmlwriter.h"
class GURL;
class MetricsLog;
// This class provides base functionality for logging metrics data.
class MetricsLogBase {
public:
// Creates a new metrics log
// client_id is the identifier for this profile on this installation
// session_id is an integer that's incremented on each application launch
MetricsLogBase(const std::string& client_id, int session_id,
const std::string& version_string);
virtual ~MetricsLogBase();
// Records a user-initiated action.
void RecordUserAction(const char* key);
enum WindowEventType {
WINDOW_CREATE = 0,
WINDOW_OPEN,
WINDOW_CLOSE,
WINDOW_DESTROY
};
void RecordWindowEvent(WindowEventType type, int window_id, int parent_id);
// Records a page load.
// window_id - the index of the tab in which the load took place
// url - which URL was loaded
// origin - what kind of action initiated the load
// load_time - how long it took to load the page
void RecordLoadEvent(int window_id,
const GURL& url,
PageTransition::Type origin,
int session_index,
base::TimeDelta load_time);
// Record any changes in a given histogram for transmission.
void RecordHistogramDelta(const Histogram& histogram,
const Histogram::SampleSet& snapshot);
// Stop writing to this record and generate the encoded representation.
// None of the Record* methods can be called after this is called.
void CloseLog();
// These methods allow retrieval of the encoded representation of the
// record. They can only be called after CloseLog() has been called.
// GetEncodedLog returns false if buffer_size is less than
// GetEncodedLogSize();
int GetEncodedLogSize();
bool GetEncodedLog(char* buffer, int buffer_size);
// Returns an empty string on failure.
std::string GetEncodedLogString();
// Returns the amount of time in seconds that this log has been in use.
int GetElapsedSeconds();
int num_events() { return num_events_; }
// Creates an MD5 hash of the given value, and returns hash as a byte
// buffer encoded as a std::string.
static std::string CreateHash(const std::string& value);
// Return a base64-encoded MD5 hash of the given string.
static std::string CreateBase64Hash(const std::string& string);
// Get the GMT buildtime for the current binary, expressed in seconds since
// Januray 1, 1970 GMT.
// The value is used to identify when a new build is run, so that previous
// reliability stats, from other builds, can be abandoned.
static int64 GetBuildTime();
// Use |extension| in all uploaded appversions in addition to the standard
// version string.
static void set_version_extension(const std::string& extension) {
version_extension_ = extension;
}
virtual MetricsLog* AsMetricsLog() {
return NULL;
}
protected:
// Returns a string containing the current time.
// Virtual so that it can be overridden for testing.
virtual std::string GetCurrentTimeString();
// Helper class that invokes StartElement from constructor, and EndElement
// from destructor.
//
// Use the macro OPEN_ELEMENT_FOR_SCOPE to help avoid usage problems.
class ScopedElement {
public:
ScopedElement(MetricsLogBase* log, const std::string& name) : log_(log) {
DCHECK(log);
log->StartElement(name.c_str());
}
ScopedElement(MetricsLogBase* log, const char* name) : log_(log) {
DCHECK(log);
log->StartElement(name);
}
~ScopedElement() {
log_->EndElement();
}
private:
MetricsLogBase* log_;
};
friend class ScopedElement;
static const char* WindowEventTypeToString(WindowEventType type);
// Convenience versions of xmlWriter functions
void StartElement(const char* name);
void EndElement();
void WriteAttribute(const std::string& name, const std::string& value);
void WriteIntAttribute(const std::string& name, int value);
void WriteInt64Attribute(const std::string& name, int64 value);
// Write the attributes that are common to every metrics event type.
void WriteCommonEventAttributes();
// An extension that is appended to the appversion in each log.
static std::string version_extension_;
base::Time start_time_;
base::Time end_time_;
std::string client_id_;
std::string session_id_;
// locked_ is true when record has been packed up for sending, and should
// no longer be written to. It is only used for sanity checking and is
// not a real lock.
bool locked_;
xmlBufferPtr buffer_;
xmlTextWriterPtr writer_;
int num_events_; // the number of events recorded in this log
DISALLOW_COPY_AND_ASSIGN(MetricsLogBase);
};
// This class provides base functionality for logging metrics data.
// TODO(ananta)
// Factor out more common code from chrome and chrome frame metrics service
// into this class.
class MetricsServiceBase {
protected:
MetricsServiceBase();
virtual ~MetricsServiceBase();
// Check to see if there is a log that needs to be, or is being, transmitted.
bool pending_log() const {
return pending_log_ || !pending_log_text_.empty();
}
// Compress the report log in input using bzip2, store the result in output.
bool Bzip2Compress(const std::string& input, std::string* output);
// Discard pending_log_, and clear pending_log_text_. Called after processing
// of this log is complete.
void DiscardPendingLog();
// Record complete list of histograms into the current log.
// Called when we close a log.
void RecordCurrentHistograms();
// Record a specific histogram .
void RecordHistogram(const Histogram& histogram);
// A log that we are currently transmiting, or about to try to transmit.
MetricsLogBase* pending_log_;
// An alternate form of pending_log_. We persistently save this text version
// into prefs if we can't transmit it. As a result, sometimes all we have is
// the text version (recalled from a previous session).
std::string pending_log_text_;
// The log that we are still appending to.
MetricsLogBase* current_log_;
// Maintain a map of histogram names to the sample stats we've sent.
typedef std::map<std::string, Histogram::SampleSet> LoggedSampleMap;
// For histograms, record what we've already logged (as a sample for each
// histogram) so that we can send only the delta with the next log.
LoggedSampleMap logged_samples_;
};
#endif // CHROME_COMMON_METRICS_HELPERS_H_
Markdown is supported
0%
or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment