Commit 282196be authored by Tim Volodine's avatar Tim Volodine Committed by Commit Bot

Reland "Move AwMetricsServiceClient logic into components for reuse by WebLayer"

This reverts commit 5d840711.

Reason for revert:
the previous breakage and revert was due to an internal patch not having rolled into chromium. It has now, so relanding this CL.
(crbug.com/1046775)

Original change's description:
> Revert "Move AwMetricsServiceClient logic into components for reuse by WebLayer"
> 
> This reverts commit 43e5153c.
> 
> Reason for revert:
> broke some build bots, see https://bugs.chromium.org/p/chromium/issues/detail?id=1046775
> 
> https://ci.chromium.org/p/chrome/builders/ci/arm64-builder-rel/20782
> 
> 
> Original change's description:
> > Move AwMetricsServiceClient logic into components for reuse by WebLayer
> > 
> > The corresponding WebLayer changes are in a follow on CL. The TBR is for
> > the new DEP file which needs content/public/browser.
> > 
> > TBR=jam@chromium.org
> > 
> > Bug: 1025781
> > Change-Id: Ie895ba7246761416d52c98ae3d4b241fed62fa45
> > Reviewed-on: https://chromium-review.googlesource.com/c/chromium/src/+/1926505
> > Commit-Queue: Alex Clarke <alexclarke@chromium.org>
> > Reviewed-by: Bo <boliu@chromium.org>
> > Reviewed-by: Nate Fischer <ntfschr@chromium.org>
> > Reviewed-by: Alexei Svitkine <asvitkine@chromium.org>
> > Cr-Commit-Position: refs/heads/master@{#736313}
> 
> TBR=jam@chromium.org,boliu@chromium.org,asvitkine@chromium.org,blundell@chromium.org,alexclarke@chromium.org,tobiasjs@chromium.org,ntfschr@chromium.org
> 
> Change-Id: I2e52f5da2c62f769cedbcaa4671f1a0ebe193be5
> No-Presubmit: true
> No-Tree-Checks: true
> No-Try: true
> Bug: 1025781
> Reviewed-on: https://chromium-review.googlesource.com/c/chromium/src/+/2028047
> Reviewed-by: Tim Volodine <timvolodine@chromium.org>
> Commit-Queue: Tim Volodine <timvolodine@chromium.org>
> Cr-Commit-Position: refs/heads/master@{#736366}

TBR=jam@chromium.org,boliu@chromium.org,asvitkine@chromium.org,blundell@chromium.org,timvolodine@chromium.org,alexclarke@chromium.org,tobiasjs@chromium.org,ntfschr@chromium.org

Change-Id: I24cbdc73208dcc78040ca1e5a2904cf0d06c6e52
No-Presubmit: true
No-Tree-Checks: true
No-Try: true
Bug: 1025781
Reviewed-on: https://chromium-review.googlesource.com/c/chromium/src/+/2028127Reviewed-by: default avatarTim Volodine <timvolodine@chromium.org>
Commit-Queue: Tim Volodine <timvolodine@chromium.org>
Cr-Commit-Position: refs/heads/master@{#736373}
parent 47fc1dff
......@@ -336,7 +336,6 @@ generate_jni("browser_jni_headers") {
"java/src/org/chromium/android_webview/gfx/AwPicture.java",
"java/src/org/chromium/android_webview/gfx/JavaBrowserViewRendererHelper.java",
"java/src/org/chromium/android_webview/gfx/RootBeginFrameSourceWebView.java",
"java/src/org/chromium/android_webview/metrics/AwMetricsLogUploader.java",
"java/src/org/chromium/android_webview/metrics/AwMetricsServiceClient.java",
"java/src/org/chromium/android_webview/permission/AwPermissionRequest.java",
"java/src/org/chromium/android_webview/safe_browsing/AwSafeBrowsingConfigHelper.java",
......@@ -430,7 +429,6 @@ android_library("browser_java") {
"java/src/org/chromium/android_webview/gfx/AwPicture.java",
"java/src/org/chromium/android_webview/gfx/JavaBrowserViewRendererHelper.java",
"java/src/org/chromium/android_webview/gfx/RootBeginFrameSourceWebView.java",
"java/src/org/chromium/android_webview/metrics/AwMetricsLogUploader.java",
"java/src/org/chromium/android_webview/metrics/AwMetricsServiceClient.java",
"java/src/org/chromium/android_webview/permission/AwGeolocationCallback.java",
"java/src/org/chromium/android_webview/permission/AwPermissionRequest.java",
......@@ -510,6 +508,7 @@ android_library("common_platform_services_java") {
deps = [
"//base:base_java",
"//components/embedder_support/android/metrics:java",
"//third_party/android_deps:androidx_annotation_annotation_java",
]
......
......@@ -206,6 +206,7 @@ source_set("browser") {
"//components/crash/content/app",
"//components/crash/content/browser",
"//components/embedder_support/android:web_contents_delegate",
"//components/embedder_support/android/metrics",
"//components/google/core/common",
"//components/heap_profiling",
"//components/metrics",
......
......@@ -16,6 +16,7 @@ include_rules = [
"+components/crash/content/browser",
"+components/crash/core",
"+components/download/public/common",
"+components/embedder_support/android/metrics",
"+components/heap_profiling",
"+components/keyed_service/core",
"+components/minidump_uploader",
......
......@@ -14,7 +14,6 @@
#include "android_webview/browser/aw_content_browser_client.h"
#include "android_webview/browser/aw_web_ui_controller_factory.h"
#include "android_webview/browser/metrics/aw_metrics_service_client.h"
#include "android_webview/browser/metrics/memory_metrics_logger.h"
#include "android_webview/browser/network_service/aw_network_change_notifier_factory.h"
#include "android_webview/common/aw_descriptors.h"
#include "android_webview/common/aw_paths.h"
......@@ -33,6 +32,7 @@
#include "base/message_loop/message_pump_type.h"
#include "base/path_service.h"
#include "components/crash/content/browser/child_exit_observer_android.h"
#include "components/embedder_support/android/metrics/memory_metrics_logger.h"
#include "components/heap_profiling/supervisor.h"
#include "components/services/heap_profiling/public/cpp/settings.h"
#include "components/user_prefs/user_prefs.h"
......@@ -124,7 +124,7 @@ void AwBrowserMainParts::PreMainMessageLoopRun() {
content::WebUIControllerFactory::RegisterFactory(
AwWebUIControllerFactory::GetInstance());
content::RenderFrameHost::AllowInjectingJavaScript();
metrics_logger_ = std::make_unique<MemoryMetricsLogger>();
metrics_logger_ = std::make_unique<metrics::MemoryMetricsLogger>();
}
bool AwBrowserMainParts::MainMessageLoopRun(int* result_code) {
......
......@@ -13,11 +13,14 @@
#include "base/task/single_thread_task_executor.h"
#include "content/public/browser/browser_main_parts.h"
namespace metrics {
class MemoryMetricsLogger;
}
namespace android_webview {
class AwBrowserProcess;
class AwContentBrowserClient;
class MemoryMetricsLogger;
class AwBrowserMainParts : public content::BrowserMainParts {
public:
......@@ -37,7 +40,7 @@ class AwBrowserMainParts : public content::BrowserMainParts {
AwContentBrowserClient* browser_client_;
std::unique_ptr<MemoryMetricsLogger> metrics_logger_;
std::unique_ptr<metrics::MemoryMetricsLogger> metrics_logger_;
std::unique_ptr<AwBrowserProcess> browser_process_;
......
......@@ -76,7 +76,6 @@ const char* const kPersistentPrefsWhitelist[] = {
prefs::kRestartsWithStaleSeed,
};
// Shows notifications which correspond to PersistentPrefStore's reading errors.
void HandleReadError(PersistentPrefStore::PrefReadError error) {}
base::FilePath GetPrefStorePath() {
......
......@@ -4,19 +4,16 @@
source_set("metrics") {
sources = [
"aw_metrics_log_uploader.cc",
"aw_metrics_log_uploader.h",
"aw_metrics_service_client.cc",
"aw_metrics_service_client.h",
"aw_stability_metrics_provider.cc",
"aw_stability_metrics_provider.h",
"memory_metrics_logger.cc",
"memory_metrics_logger.h",
]
deps = [
"//android_webview:browser_jni_headers",
"//android_webview/common",
"//base",
"//components/embedder_support/android/metrics",
"//components/metrics",
"//components/metrics:gpu",
"//components/metrics:net",
......@@ -25,6 +22,5 @@ source_set("metrics") {
"//components/version_info",
"//components/version_info/android:channel_getter",
"//content/public/browser",
"//services/resource_coordinator/public/cpp/memory_instrumentation:browser",
]
}
// Copyright 2017 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.
#ifndef ANDROID_WEBVIEW_BROWSER_METRICS_AW_METRICS_LOG_UPLOADER_H_
#define ANDROID_WEBVIEW_BROWSER_METRICS_AW_METRICS_LOG_UPLOADER_H_
#include <jni.h>
#include <string>
#include "components/metrics/metrics_log_uploader.h"
namespace android_webview {
// Uploads UMA logs for WebView using the platform logging mechanism.
class AwMetricsLogUploader : public ::metrics::MetricsLogUploader {
public:
explicit AwMetricsLogUploader(
const ::metrics::MetricsLogUploader::UploadCallback& on_upload_complete);
~AwMetricsLogUploader() override;
// ::metrics::MetricsLogUploader:
// Note: |log_hash| and |log_signature| are only used by the normal UMA
// server. WebView uses the platform logging mechanism instead of the normal
// UMA server, so |log_hash| and |log_signature| aren't used.
void UploadLog(const std::string& compressed_log_data,
const std::string& log_hash,
const std::string& log_signature,
const metrics::ReportingInfo& reporting_info) override;
private:
const metrics::MetricsLogUploader::UploadCallback on_upload_complete_;
DISALLOW_COPY_AND_ASSIGN(AwMetricsLogUploader);
};
} // namespace android_webview
#endif // ANDROID_WEBVIEW_BROWSER_METRICS_AW_METRICS_LOG_UPLOADER_H_
......@@ -13,19 +13,13 @@
#include "base/no_destructor.h"
#include "base/sequence_checker.h"
#include "base/time/time.h"
#include "components/embedder_support/android/metrics/android_metrics_service_client.h"
#include "components/metrics/enabled_state_provider.h"
#include "components/metrics/metrics_log_uploader.h"
#include "components/metrics/metrics_service_client.h"
#include "content/public/browser/notification_observer.h"
#include "content/public/browser/notification_registrar.h"
class PrefRegistrySimple;
class PrefService;
namespace metrics {
class MetricsStateManager;
}
namespace android_webview {
// These values are persisted to logs. Entries should not be renumbered and
......@@ -93,9 +87,8 @@ enum class BackfillInstallDate {
// the client ID (generating a new ID if there was none). If this client is in
// the sample, it then calls MetricsService::Start(). If consent was not
// granted, MaybeStartMetrics() instead clears the client ID, if any.
class AwMetricsServiceClient : public metrics::MetricsServiceClient,
public metrics::EnabledStateProvider,
public content::NotificationObserver {
class AwMetricsServiceClient : public ::metrics::AndroidMetricsServiceClient {
friend class base::NoDestructor<AwMetricsServiceClient>;
public:
......@@ -104,103 +97,23 @@ class AwMetricsServiceClient : public metrics::MetricsServiceClient,
AwMetricsServiceClient();
~AwMetricsServiceClient() override;
// Registers local state prefs used by this class.
static void RegisterPrefs(PrefRegistrySimple* registry);
void Initialize(PrefService* pref_service);
void SetHaveMetricsConsent(bool user_consent, bool app_consent);
void SetFastStartupForTesting(bool fast_startup_for_testing);
void SetUploadIntervalForTesting(const base::TimeDelta& upload_interval);
std::unique_ptr<const base::FieldTrial::EntropyProvider>
CreateLowEntropyProvider();
// metrics::EnabledStateProvider
bool IsConsentGiven() const override;
bool IsReportingEnabled() const override;
// metrics::MetricsServiceClient
metrics::MetricsService* GetMetricsService() override;
void SetMetricsClientId(const std::string& client_id) override;
int32_t GetProduct() override;
std::string GetApplicationLocale() override;
bool GetBrand(std::string* brand_code) override;
metrics::SystemProfileProto::Channel GetChannel() override;
std::string GetVersionString() override;
void CollectFinalMetricsForLog(base::OnceClosure done_callback) override;
std::unique_ptr<metrics::MetricsLogUploader> CreateUploader(
const GURL& server_url,
const GURL& insecure_server_url,
base::StringPiece mime_type,
metrics::MetricsLogUploader::MetricServiceType service_type,
const metrics::MetricsLogUploader::UploadCallback& on_upload_complete)
override;
base::TimeDelta GetStandardUploadInterval() override;
bool ShouldStartUpFastForTesting() const override;
// Gets the embedding app's package name if it's OK to log. Otherwise, this
// returns the empty string.
std::string GetAppPackageName() override;
// content::NotificationObserver
void Observe(int type,
const content::NotificationSource& source,
const content::NotificationDetails& details) override;
protected:
// Returns the metrics sampling rate, to be used by IsInSample(). This is a
// double in the non-inclusive range (0.00, 1.00). Virtual for testing.
virtual double GetSampleRate();
// Determines if the client is within the random sample of clients for which
// we log metrics. If this returns false, AwMetricsServiceClient should
// indicate reporting is disabled. Sampling is due to storage/bandwidth
// considerations. Virtual for testing.
virtual bool IsInSample();
// Prefer calling the IsInSample() which takes no arguments. Virtual for
// testing.
virtual bool IsInSample(uint32_t value);
// Determines if the embedder app is the type of app for which we may log the
// package name. If this returns false, GetAppPackageName() must return empty
// string. Virtual for testing.
virtual bool CanRecordPackageNameForAppType();
// Determines if this client falls within the group for which it's acceptable
// to include the embedding app's package name. If this returns false,
// GetAppPackageName() must return the empty string (for
// privacy/fingerprintability reasons). Virtual for testing.
virtual bool IsInPackageNameSample();
// Prefer calling the IsInPackageNameSample() which takes no arguments.
// Virtual for testing.
virtual bool IsInPackageNameSample(uint32_t value);
// metrics::AndroidMetricsServiceClient:
void InitInternal() override;
void OnMetricsStart() override;
double GetSampleRate() override;
double GetPackageNameLimitRate() override;
bool ShouldWakeMetricsService() override;
void RegisterAdditionalMetricsProviders(
metrics::MetricsService* service) override;
bool CanRecordPackageNameForAppType() override;
std::string GetAppPackageNameInternal() override;
private:
void MaybeStartMetrics();
void RegisterForNotifications();
std::unique_ptr<metrics::MetricsStateManager> metrics_state_manager_;
std::unique_ptr<metrics::MetricsService> metrics_service_;
content::NotificationRegistrar registrar_;
PrefService* pref_service_ = nullptr;
bool init_finished_ = false;
bool set_consent_finished_ = false;
bool user_consent_ = false;
bool app_consent_ = false;
bool is_in_sample_ = false;
bool is_in_package_name_sample_ = false;
bool fast_startup_for_testing_ = false;
// When non-zero, this overrides the default value in
// GetStandardUploadInterval().
base::TimeDelta overridden_upload_interval_;
// AwMetricsServiceClient may be created before the UI thread is promoted to
// BrowserThread::UI. Use |sequence_checker_| to enforce that the
// AwMetricsServiceClient is used on a single thread.
base::SequenceChecker sequence_checker_;
DISALLOW_COPY_AND_ASSIGN(AwMetricsServiceClient);
};
......
include_rules = [
"+components/background_task_scheduler/android/java",
"+components/embedder_support/android/metrics/java",
"+components/minidump_uploader/android/java",
"-android_webview/glue",
......
......@@ -11,7 +11,9 @@ import android.os.HandlerThread;
import androidx.annotation.NonNull;
import org.chromium.base.Callback;
import org.chromium.base.Consumer;
import org.chromium.base.ThreadUtils;
import org.chromium.components.metrics.AndroidMetricsLogUploader;
/**
* This class manages platform-specific services. (i.e. Google Services) The platform
......@@ -27,7 +29,14 @@ public abstract class PlatformServiceBridge {
private static Handler sHandler;
private static final Object sHandlerLock = new Object();
protected PlatformServiceBridge() {}
protected PlatformServiceBridge() {
AndroidMetricsLogUploader.setUploader(new Consumer<byte[]>() {
@Override
public void accept(byte[] data) {
logMetrics(data);
}
});
}
@SuppressWarnings("unused")
public static PlatformServiceBridge getInstance() {
......
// Copyright 2017 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.
package org.chromium.android_webview.metrics;
import org.chromium.android_webview.common.PlatformServiceBridge;
import org.chromium.base.annotations.CalledByNative;
import org.chromium.base.annotations.JNINamespace;
/**
* Passes UMA logs from native to PlatformServiceBridge.
*/
@JNINamespace("android_webview")
public class AwMetricsLogUploader {
@CalledByNative
public static void uploadLog(byte[] data) {
// This relies on WebViewChromiumFactoryProvider having already created the
// PlatformServiceBridge. This is guaranteed because metrics won't start until the
// PlatformServiceBridge.queryMetricsSetting() callback fires.
PlatformServiceBridge.getInstance().logMetrics(data);
}
}
......@@ -350,10 +350,9 @@ source_set("webview_instrumentation_test_native_jni_impl") {
deps = [
":webview_instrumentation_test_native_jni",
"//android_webview/browser",
"//android_webview/browser/metrics",
"//base",
"//base/test:test_support",
"//components/embedder_support/android/metrics",
]
}
......
include_rules = [
"+components/embedder_support/android/metrics",
"+components/policy/android/javatests",
"-content/public/android/java",
"+content/public/android/java/src/org/chromium/content_public",
......
......@@ -4,17 +4,18 @@
#include "android_webview/test/webview_instrumentation_test_native_jni/MemoryMetricsLoggerUtils_jni.h"
#include "android_webview/browser/metrics/memory_metrics_logger.h"
#include "base/run_loop.h"
#include "base/test/bind_test_util.h"
#include "base/test/task_environment.h"
#include "base/test/test_timeouts.h"
#include "components/embedder_support/android/metrics/memory_metrics_logger.h"
namespace android_webview {
// static
jboolean JNI_MemoryMetricsLoggerUtils_ForceRecordHistograms(JNIEnv* env) {
auto* memory_metrics_logger = MemoryMetricsLogger::GetInstanceForTesting();
auto* memory_metrics_logger =
::metrics::MemoryMetricsLogger::GetInstanceForTesting();
if (!memory_metrics_logger)
return false;
......
......@@ -311,6 +311,7 @@ test("components_unittests") {
"//components/crash/android:java",
"//components/crash/android:unit_tests",
"//components/download/internal/common:internal_java",
"//components/embedder_support/android/metrics:unit_tests",
"//components/gcm_driver/instance_id:test_support",
"//components/gcm_driver/instance_id/android:instance_id_driver_java",
"//components/gcm_driver/instance_id/android:instance_id_driver_test_support_java",
......
Collection of Android libraries that provides embedders with
typical implementations of interfaces of content layer.
typical implementations of content and component layer interfaces.
# Copyright 2020 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.
import("//build/config/android/config.gni")
import("//build/config/android/rules.gni")
assert(is_android, "This component can only be depended on for android builds")
# Intended for content embedders such as WebView & WebLayer.
static_library("metrics") {
sources = [
"android_metrics_log_uploader.cc",
"android_metrics_log_uploader.h",
"android_metrics_service_client.cc",
"android_metrics_service_client.h",
"memory_metrics_logger.cc",
"memory_metrics_logger.h",
]
deps = [
":jni",
"//components/metrics",
"//components/metrics:net",
"//components/metrics:ui",
"//components/prefs",
"//content/public/browser",
"//services/resource_coordinator/public/cpp/memory_instrumentation:browser",
]
}
android_library("java") {
sources = [
"java/src/org/chromium/components/metrics/AndroidMetricsLogUploader.java",
]
deps = [
"//base:base_java",
"//base:jni_java",
]
annotation_processor_deps = [ "//base/android/jni_generator:jni_processor" ]
}
generate_jni("jni") {
sources = [
"java/src/org/chromium/components/metrics/AndroidMetricsLogUploader.java",
]
}
source_set("unit_tests") {
testonly = true
sources = [ "android_metrics_service_client_unittest.cc" ]
deps = [
":metrics",
"//base/test:test_support",
"//components/metrics",
"//components/prefs:test_support",
"//testing/gtest",
]
}
include_rules = [
"+components/metrics",
"+components/prefs",
"+content/public/browser",
"+services/resource_coordinator/public/cpp/memory_instrumentation",
]
file://base/metrics/OWNERS
ntfschr@chromium.org
# COMPONENT: Internals>Metrics
# TEAM: chromium-dev@chromium.org
// Copyright 2017 The Chromium Authors. All rights reserved.
// Copyright 2020 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.
#include "android_webview/browser/metrics/aw_metrics_log_uploader.h"
#include "components/embedder_support/android/metrics/android_metrics_log_uploader.h"
#include "android_webview/browser_jni_headers/AwMetricsLogUploader_jni.h"
#include "base/android/jni_array.h"
#include "components/embedder_support/android/metrics/jni/AndroidMetricsLogUploader_jni.h"
#include "components/metrics/log_decoder.h"
using base::android::ScopedJavaLocalRef;
using base::android::ToJavaByteArray;
namespace android_webview {
namespace metrics {
AwMetricsLogUploader::AwMetricsLogUploader(
const metrics::MetricsLogUploader::UploadCallback& on_upload_complete)
AndroidMetricsLogUploader::AndroidMetricsLogUploader(
const MetricsLogUploader::UploadCallback& on_upload_complete)
: on_upload_complete_(on_upload_complete) {}
AwMetricsLogUploader::~AwMetricsLogUploader() {}
AndroidMetricsLogUploader::~AndroidMetricsLogUploader() = default;
void AwMetricsLogUploader::UploadLog(
void AndroidMetricsLogUploader::UploadLog(
const std::string& compressed_log_data,
const std::string& /*log_hash*/,
const std::string& /*log_signature*/,
const metrics::ReportingInfo& reporting_info) {
// WebView uses the platform logging mechanism instead of the normal UMA
const ReportingInfo& reporting_info) {
// This uploader uses the platform logging mechanism instead of the normal UMA
// server. The platform mechanism does its own compression, so undo the
// previous compression.
std::string log_data;
if (!metrics::DecodeLogData(compressed_log_data, &log_data)) {
if (!DecodeLogData(compressed_log_data, &log_data)) {
// If the log is corrupt, pretend the server rejected it (HTTP Bad Request).
on_upload_complete_.Run(400, 0, true);
return;
......@@ -37,7 +37,7 @@ void AwMetricsLogUploader::UploadLog(
JNIEnv* env = base::android::AttachCurrentThread();
ScopedJavaLocalRef<jbyteArray> java_data = ToJavaByteArray(
env, reinterpret_cast<const uint8_t*>(log_data.data()), log_data.size());
Java_AwMetricsLogUploader_uploadLog(env, java_data);
Java_AndroidMetricsLogUploader_uploadLog(env, java_data);
// The platform mechanism doesn't provide a response code or any way to handle
// failures, so we have nothing to pass to on_upload_complete. Just pass 200
......@@ -45,4 +45,4 @@ void AwMetricsLogUploader::UploadLog(
on_upload_complete_.Run(200, 0, true);
}
} // namespace android_webview
} // namespace metrics
// Copyright 2020 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.
#ifndef COMPONENTS_EMBEDDER_SUPPORT_ANDROID_METRICS_ANDROID_METRICS_LOG_UPLOADER_H_
#define COMPONENTS_EMBEDDER_SUPPORT_ANDROID_METRICS_ANDROID_METRICS_LOG_UPLOADER_H_
#include <string>
#include "components/metrics/metrics_log_uploader.h"
namespace metrics {
// Uploads UMA logs using the platform logging mechanism.
class AndroidMetricsLogUploader : public MetricsLogUploader {
public:
explicit AndroidMetricsLogUploader(
const MetricsLogUploader::UploadCallback& on_upload_complete);
~AndroidMetricsLogUploader() override;
AndroidMetricsLogUploader(const AndroidMetricsLogUploader&) = delete;
AndroidMetricsLogUploader& operator=(const AndroidMetricsLogUploader&) =
delete;
// MetricsLogUploader:
// Note: |log_hash| and |log_signature| are only used by the normal UMA
// server. This uploader uses a Java logging mechanism that ignores these
// fields.
void UploadLog(const std::string& compressed_log_data,
const std::string& log_hash,
const std::string& log_signature,
const ReportingInfo& reporting_info) override;
private:
const MetricsLogUploader::UploadCallback on_upload_complete_;
};
} // namespace metrics
#endif // COMPONENTS_EMBEDDER_SUPPORT_ANDROID_METRICS_ANDROID_METRICS_LOG_UPLOADER_H_
// Copyright 2020 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.
#ifndef COMPONENTS_EMBEDDER_SUPPORT_ANDROID_METRICS_ANDROID_METRICS_SERVICE_CLIENT_H_
#define COMPONENTS_EMBEDDER_SUPPORT_ANDROID_METRICS_ANDROID_METRICS_SERVICE_CLIENT_H_
#include <memory>
#include <string>
#include "base/metrics/field_trial.h"
#include "base/sequence_checker.h"
#include "base/time/time.h"
#include "components/metrics/enabled_state_provider.h"
#include "components/metrics/metrics_log_uploader.h"
#include "components/metrics/metrics_service_client.h"
#include "content/public/browser/notification_observer.h"
#include "content/public/browser/notification_registrar.h"
class PrefRegistrySimple;
class PrefService;
namespace metrics {
class MetricsStateManager;
// AndroidMetricsServiceClient is a singleton which manages metrics collection
// intended for use by WebView & WebLayer.
//
// Metrics should be enabled iff all these conditions are met:
// - The user has not opted out.
// - The app has not opted out.
// - This client is in the 10% sample (controlled by client ID hash).
// The first two are recorded in |user_consent_| and |app_consent_|, which are
// set by SetHaveMetricsConsent(). The last is recorded in |is_in_sample_|.
//
// Metrics are pseudonymously identified by a randomly-generated "client ID".
// AndroidMetricsServiceClient stores this in prefs, written to the app's data
// directory. There's a different such directory for each user, for each app,
// on each device. So the ID should be unique per (device, app, user) tuple.
//
// In order to be transparent about not associating an ID with an opted out user
// or app, the client ID should only be created and retained when neither the
// user nor the app have opted out. Otherwise, the presence of the ID could give
// the impression that metrics were being collected.
//
// AndroidMetricsServiceClient metrics set up happens like so:
//
// startup
// │
// ├────────────┐
// │ ▼
// │ query for consent
// ▼ │
// Initialize() │
// │ ▼
// │ SetHaveMetricsConsent()
// │ │
// │ ┌──────────┘
// ▼ ▼
// MaybeStartMetrics()
// │
// ▼
// MetricsService::Start()
//
// All the named functions in this diagram happen on the UI thread. Querying GMS
// happens in the background, and the result is posted back to the UI thread, to
// SetHaveMetricsConsent(). Querying GMS is slow, so SetHaveMetricsConsent()
// typically happens after Initialize(), but it may happen before.
//
// Each path sets a flag, |init_finished_| or |set_consent_finished_|, to show
// that path has finished, and then calls MaybeStartMetrics(). When
// MaybeStartMetrics() is called the first time, it sees only one flag is true,
// and does nothing. When MaybeStartMetrics() is called the second time, it
// decides whether to start metrics.
//
// If consent was granted, MaybeStartMetrics() determines sampling by hashing
// the client ID (generating a new ID if there was none). If this client is in
// the sample, it then calls MetricsService::Start(). If consent was not
// granted, MaybeStartMetrics() instead clears the client ID, if any.
class AndroidMetricsServiceClient : public MetricsServiceClient,
public EnabledStateProvider,
public content::NotificationObserver {
public:
AndroidMetricsServiceClient();
~AndroidMetricsServiceClient() override;
AndroidMetricsServiceClient(const AndroidMetricsServiceClient&) = delete;
AndroidMetricsServiceClient& operator=(const AndroidMetricsServiceClient&) =
delete;
static void RegisterPrefs(PrefRegistrySimple* registry);
void Initialize(PrefService* pref_service);
void SetHaveMetricsConsent(bool user_consent, bool app_consent);
void SetFastStartupForTesting(bool fast_startup_for_testing);
void SetUploadIntervalForTesting(const base::TimeDelta& upload_interval);
std::unique_ptr<const base::FieldTrial::EntropyProvider>
CreateLowEntropyProvider();
// EnabledStateProvider
bool IsConsentGiven() const override;
bool IsReportingEnabled() const override;
// MetricsServiceClient
MetricsService* GetMetricsService() override;
void SetMetricsClientId(const std::string& client_id) override;
std::string GetApplicationLocale() override;
bool GetBrand(std::string* brand_code) override;
void CollectFinalMetricsForLog(
const base::OnceClosure done_callback) override;
std::unique_ptr<MetricsLogUploader> CreateUploader(
const GURL& server_url,
const GURL& insecure_server_url,
base::StringPiece mime_type,
MetricsLogUploader::MetricServiceType service_type,
const MetricsLogUploader::UploadCallback& on_upload_complete) override;
base::TimeDelta GetStandardUploadInterval() override;
bool ShouldStartUpFastForTesting() const override;
// Gets the embedding app's package name if it's OK to log. Otherwise, this
// returns the empty string.
std::string GetAppPackageName() override;
// content::NotificationObserver
void Observe(int type,
const content::NotificationSource& source,
const content::NotificationDetails& details) override;
protected:
// Called by Initialize() to allow embedder specific initialization.
virtual void InitInternal() = 0;
// Called by MaybeStartMetrics() to allow embedder specific initialization.
virtual void OnMetricsStart() = 0;
// Returns the metrics sampling rate, to be used by IsInSample(). This is a
// double in the non-inclusive range (0.00, 1.00). Virtual for testing.
virtual double GetSampleRate() = 0;
// Determines if the client is within the random sample of clients for which
// we log metrics. If this returns false, MetricsServiceClient should
// indicate reporting is disabled. Sampling is due to storage/bandwidth
// considerations. Virtual for testing.
virtual bool IsInSample();
// Prefer calling the IsInSample() which takes no arguments. Virtual for
// testing.
virtual bool IsInSample(uint32_t value);
// Determines if the embedder app is the type of app for which we may log the
// package name. If this returns false, GetAppPackageName() must return empty
// string. Virtual for testing.
virtual bool CanRecordPackageNameForAppType() = 0;
// Determines if this client falls within the group for which it's acceptable
// to include the embedding app's package name. If this returns false,
// GetAppPackageName() must return the empty string (for
// privacy/fingerprintability reasons). Virtual for testing.
virtual bool IsInPackageNameSample();
// Prefer calling the IsInPackageNameSample() which takes no arguments.
// Virtual for testing.
virtual bool IsInPackageNameSample(uint32_t value);
// Caps the rate at which we upload package names. This is privacy sensitive.
virtual double GetPackageNameLimitRate() = 0;
// Whether or not MetricsService::OnApplicationNotIdle should be called for
// notifications.
virtual bool ShouldWakeMetricsService() = 0;
// Called by CreateMetricsService, allows the embedder to register additional
// MetricsProviders.
virtual void RegisterAdditionalMetricsProviders(MetricsService* service) = 0;
// Returns the embedding application's package name.
virtual std::string GetAppPackageNameInternal() = 0;
void EnsureOnValidSequence() const {
DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
}
PrefService* pref_service() const { return pref_service_; }
private:
void MaybeStartMetrics();
void RegisterForNotifications();
std::unique_ptr<MetricsService> CreateMetricsService(
MetricsStateManager* state_manager,
AndroidMetricsServiceClient* client,
PrefService* prefs);
std::unique_ptr<MetricsStateManager> metrics_state_manager_;
std::unique_ptr<MetricsService> metrics_service_;
content::NotificationRegistrar registrar_;
PrefService* pref_service_ = nullptr;
bool init_finished_ = false;
bool set_consent_finished_ = false;
bool user_consent_ = false;
bool app_consent_ = false;
bool is_in_sample_ = false;
bool fast_startup_for_testing_ = false;
// When non-zero, this overrides the default value in
// GetStandardUploadInterval().
base::TimeDelta overridden_upload_interval_;
// MetricsServiceClient may be created before the UI thread is promoted to
// BrowserThread::UI. Use |sequence_checker_| to enforce that the
// MetricsServiceClient is used on a single thread.
SEQUENCE_CHECKER(sequence_checker_);
};
} // namespace metrics
#endif // COMPONENTS_EMBEDDER_SUPPORT_ANDROID_METRICS_ANDROID_METRICS_SERVICE_CLIENT_H_
// Copyright 2020 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.
package org.chromium.components.metrics;
import org.chromium.base.Consumer;
import org.chromium.base.annotations.CalledByNative;
import org.chromium.base.annotations.JNINamespace;
/**
* Passes UMA logs from native to a java uploader.
*/
@JNINamespace("metrics")
public class AndroidMetricsLogUploader {
private static volatile Consumer<byte[]> sUploader;
/**
* Configures the consumer of logs data submitted via uploadLog, should be called once during
* start up.
*
* @param uploader The consumer of logs data submitted via uploadLog.
*/
public static void setUploader(Consumer<byte[]> uploader) {
sUploader = uploader;
}
@CalledByNative
public static void uploadLog(byte[] data) {
final Consumer<byte[]> uploader = sUploader;
if (uploader != null) {
uploader.accept(data);
}
}
}
// Copyright 2019 The Chromium Authors. All rights reserved.
// Copyright 2020 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.
#include "android_webview/browser/metrics/memory_metrics_logger.h"
#include "components/embedder_support/android/metrics/memory_metrics_logger.h"
#include "base/bind.h"
#include "base/bind_helpers.h"
......@@ -20,7 +20,7 @@
using memory_instrumentation::GetPrivateFootprintHistogramName;
using memory_instrumentation::HistogramProcessType;
namespace android_webview {
namespace metrics {
namespace {
MemoryMetricsLogger* g_instance = nullptr;
......@@ -56,6 +56,8 @@ void RecordMemoryMetricsImpl(
}
// WebView only supports the browser and possibly renderer process.
// TODO(weblayer-team): refactor to allow the embedder to record GPU
// metrics.
case memory_instrumentation::mojom::ProcessType::GPU:
FALLTHROUGH;
case memory_instrumentation::mojom::ProcessType::ARC:
......@@ -146,4 +148,4 @@ void MemoryMetricsLogger::RecordMemoryMetrics(scoped_refptr<State> state,
RecordMemoryMetricsAfterDelay(state);
}
} // namespace android_webview
} // namespace metrics
// Copyright 2019 The Chromium Authors. All rights reserved.
// Copyright 2020 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.
#ifndef ANDROID_WEBVIEW_BROWSER_METRICS_MEMORY_METRICS_LOGGER_H_
#define ANDROID_WEBVIEW_BROWSER_METRICS_MEMORY_METRICS_LOGGER_H_
#include <jni.h>
#include <memory>
#ifndef COMPONENTS_EMBEDDER_SUPPORT_ANDROID_METRICS_MEMORY_METRICS_LOGGER_H_
#define COMPONENTS_EMBEDDER_SUPPORT_ANDROID_METRICS_MEMORY_METRICS_LOGGER_H_
#include "base/callback_forward.h"
#include "base/macros.h"
#include "base/memory/scoped_refptr.h"
namespace android_webview {
namespace metrics {
// MemoryMetricsLogger is responsible for logging the memory related heartbeat
// metrics. MemoryMetricsLogger logs metrics at certain intervals for as long
......@@ -26,11 +22,8 @@ class MemoryMetricsLogger {
MemoryMetricsLogger();
~MemoryMetricsLogger();
private:
struct State;
friend jboolean JNI_MemoryMetricsLoggerUtils_ForceRecordHistograms(
JNIEnv* env);
MemoryMetricsLogger(const MemoryMetricsLogger&) = delete;
MemoryMetricsLogger& operator=(const MemoryMetricsLogger&) = delete;
// Returns the single instance, if one was created.
static MemoryMetricsLogger* GetInstanceForTesting();
......@@ -40,6 +33,9 @@ class MemoryMetricsLogger {
// TaskRunner.
void ScheduleRecordForTesting(RecordCallback done_callback);
private:
struct State;
// Called on the task runner to record metrics after a delay.
static void RecordMemoryMetricsAfterDelay(scoped_refptr<State> state);
......@@ -50,10 +46,8 @@ class MemoryMetricsLogger {
RecordCallback done_callback);
scoped_refptr<State> state_;
DISALLOW_COPY_AND_ASSIGN(MemoryMetricsLogger);
};
} // namespace android_webview
} // namespace metrics
#endif // ANDROID_WEBVIEW_BROWSER_METRICS_MEMORY_METRICS_LOGGER_H_
#endif // COMPONENTS_EMBEDDER_SUPPORT_ANDROID_METRICS_MEMORY_METRICS_LOGGER_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