Bug 1472718 - Convert ChromeUtils.requestIOActivity to a Promise - r=baku,valentin

Changes:

- The API now returns a Promise containing a sequence of IOActivityData dictionnaries.
- All the code related to notifications and XPCOM is removed.
- The counters are no longer reset to 0 when the API is called

MozReview-Commit-ID: 7J2EgFqDgf

--HG--
extra : rebase_source : 4e16640a3f52fd7c042687471153971a66158623
This commit is contained in:
Tarek Ziadé 2018-07-06 02:10:33 +02:00
Родитель 7e388f04c4
Коммит 12c531f562
11 изменённых файлов: 141 добавлений и 315 удалений

Просмотреть файл

@ -769,12 +769,20 @@ ChromeUtils::CreateError(const GlobalObject& aGlobal, const nsAString& aMessage,
aRetVal.set(retVal);
}
/* static */ void
ChromeUtils::RequestIOActivity(GlobalObject&)
/* static */ already_AddRefed<Promise>
ChromeUtils::RequestIOActivity(GlobalObject& aGlobal, ErrorResult& aRv)
{
MOZ_ASSERT(XRE_IsParentProcess());
MOZ_ASSERT(Preferences::GetBool(IO_ACTIVITY_ENABLED_PREF, false));
mozilla::Unused << mozilla::net::IOActivityMonitor::NotifyActivities();
nsCOMPtr<nsIGlobalObject> global = do_QueryInterface(aGlobal.GetAsSupports());
MOZ_ASSERT(global);
RefPtr<Promise> domPromise = Promise::Create(global, aRv);
if (NS_WARN_IF(aRv.Failed())) {
return nullptr;
}
MOZ_ASSERT(domPromise);
mozilla::net::IOActivityMonitor::RequestActivities(domPromise);
return domPromise.forget();
}
} // namespace dom

Просмотреть файл

@ -183,7 +183,8 @@ public:
JS::Handle<JSObject*> stack,
JS::MutableHandle<JSObject*> aRetVal, ErrorResult& aRv);
static void RequestIOActivity(GlobalObject& aGlobal);
static already_AddRefed<Promise>
RequestIOActivity(GlobalObject& aGlobal, ErrorResult& aRv);
};
} // namespace dom

Просмотреть файл

@ -350,9 +350,23 @@ partial namespace ChromeUtils {
void requestPerformanceMetrics();
/**
* Request IOActivityMonitor to send a notification containing I/O activity
* Returns a Promise containing a sequence of I/O activities
*/
void requestIOActivity();
[Throws]
Promise<sequence<IOActivityDataDictionary>> requestIOActivity();
};
/**
* Used by requestIOActivity() to return the number of bytes
* that were read (rx) and/or written (tx) for a given location.
*
* Locations can be sockets or files.
*/
dictionary IOActivityDataDictionary {
ByteString location = "";
unsigned long long rx = 0;
unsigned long long tx = 0;
};
/**

Просмотреть файл

@ -10,12 +10,14 @@
#include "nsSocketTransport2.h"
#include "nsSocketTransportService2.h"
#include "nsThreadUtils.h"
#include "mozilla/dom/Promise.h"
#include "mozilla/Services.h"
#include "prerror.h"
#include "prio.h"
#include "prmem.h"
#include <vector>
using namespace mozilla;
using namespace mozilla::net;
mozilla::StaticRefPtr<IOActivityMonitor> gInstance;
@ -277,146 +279,58 @@ nsNetMon_AcceptRead(PRFileDesc *listenSock,
}
//
// Class IOActivityData
//
NS_IMPL_ISUPPORTS(IOActivityData, nsIIOActivityData);
NS_IMETHODIMP
IOActivityData::GetLocation(nsACString& aLocation) {
aLocation = mActivity.location;
return NS_OK;
};
NS_IMETHODIMP
IOActivityData::GetRx(int32_t* aRx) {
*aRx = mActivity.rx;
return NS_OK;
};
NS_IMETHODIMP
IOActivityData::GetTx(int32_t* aTx) {
*aTx = mActivity.tx;
return NS_OK;
};
//
// Class NotifyIOActivity
//
// Runnable that takes the activities per FD and location
// and converts them into IOActivity elements.
//
// These elements get notified.
//
class NotifyIOActivity : public mozilla::Runnable {
public:
static already_AddRefed<nsIRunnable>
Create(Activities& aActivities, const mozilla::MutexAutoLock& aProofOfLock)
{
RefPtr<NotifyIOActivity> runnable = new NotifyIOActivity();
for (auto iter = aActivities.Iter(); !iter.Done(); iter.Next()) {
IOActivity* activity = iter.Data();
if (!activity->Inactive()) {
if (NS_WARN_IF(!runnable->mActivities.AppendElement(*activity, mozilla::fallible))) {
return nullptr;
}
}
}
nsCOMPtr<nsIRunnable> result(runnable);
return result.forget();
}
NS_IMETHODIMP
Run() override
{
MOZ_ASSERT(NS_IsMainThread());
if (mActivities.Length() == 0) {
return NS_OK;
}
nsCOMPtr<nsIObserverService> obs = mozilla::services::GetObserverService();
if (!obs) {
return NS_ERROR_FAILURE;
}
nsCOMPtr<nsIMutableArray> array = do_CreateInstance(NS_ARRAY_CONTRACTID);
if (NS_WARN_IF(!array)) {
return NS_ERROR_FAILURE;
}
for (unsigned long i = 0; i < mActivities.Length(); i++) {
nsCOMPtr<nsIIOActivityData> data = new IOActivityData(mActivities[i]);
nsresult rv = array->AppendElement(data);
if (NS_WARN_IF(NS_FAILED(rv))) {
return rv;
}
}
obs->NotifyObservers(array, NS_IO_ACTIVITY, nullptr);
return NS_OK;
}
private:
explicit NotifyIOActivity()
: mozilla::Runnable("NotifyIOActivity")
{
}
FallibleTArray<IOActivity> mActivities;
};
//
// Class IOActivityMonitor
//
NS_IMPL_ISUPPORTS(IOActivityMonitor, nsITimerCallback, nsINamed)
NS_IMPL_ISUPPORTS(IOActivityMonitor, nsINamed)
IOActivityMonitor::IOActivityMonitor()
: mInterval(PR_INTERVAL_NO_TIMEOUT)
, mLock("IOActivityMonitor::mLock")
: mLock("IOActivityMonitor::mLock")
{
RefPtr<IOActivityMonitor> mon(gInstance);
MOZ_ASSERT(!mon, "multiple IOActivityMonitor instances!");
}
NS_IMETHODIMP
IOActivityMonitor::Notify(nsITimer* aTimer)
{
return NotifyActivities();
}
// static
nsresult
IOActivityMonitor::NotifyActivities()
void
IOActivityMonitor::RequestActivities(dom::Promise* aPromise)
{
MOZ_ASSERT(aPromise);
RefPtr<IOActivityMonitor> mon(gInstance);
if (!IsActive()) {
return NS_ERROR_FAILURE;
aPromise->MaybeReject(NS_ERROR_FAILURE);
return;
}
return mon->NotifyActivities_Internal();
mon->RequestActivitiesInternal(aPromise);
}
nsresult
IOActivityMonitor::NotifyActivities_Internal()
void
IOActivityMonitor::RequestActivitiesInternal(dom::Promise* aPromise)
{
mozilla::MutexAutoLock lock(mLock);
nsCOMPtr<nsIRunnable> ev = NotifyIOActivity::Create(mActivities, lock);
nsresult rv = SystemGroup::EventTargetFor(TaskCategory::Performance)->Dispatch(ev.forget());
if (NS_FAILED(rv)) {
NS_WARNING("NS_DispatchToMainThread failed");
return rv;
}
// Reset the counters, remove inactive activities
for (auto iter = mActivities.Iter(); !iter.Done(); iter.Next()) {
IOActivity* activity = iter.Data();
if (activity->Inactive()) {
iter.Remove();
} else {
activity->Reset();
nsresult result = NS_OK;
FallibleTArray<dom::IOActivityDataDictionary> activities;
{
mozilla::MutexAutoLock lock(mLock);
// Remove inactive activities
for (auto iter = mActivities.Iter(); !iter.Done(); iter.Next()) {
dom::IOActivityDataDictionary* activity = &iter.Data();
if (activity->mRx == 0 && activity->mTx == 0) {
iter.Remove();
} else {
if (NS_WARN_IF(!activities.AppendElement(iter.Data(), fallible))) {
result = NS_ERROR_OUT_OF_MEMORY;
break;
}
}
}
}
return NS_OK;
if (NS_WARN_IF(NS_FAILED(result))) {
aPromise->MaybeReject(result);
return;
}
aPromise->MaybeResolve(activities);
}
// static
@ -434,13 +348,13 @@ IOActivityMonitor::IsActive()
}
nsresult
IOActivityMonitor::Init(int32_t aInterval)
IOActivityMonitor::Init()
{
if (IsActive()) {
return NS_ERROR_ALREADY_INITIALIZED;
}
RefPtr<IOActivityMonitor> mon = new IOActivityMonitor();
nsresult rv = mon->Init_Internal(aInterval);
nsresult rv = mon->InitInternal();
if (NS_SUCCEEDED(rv)) {
gInstance = mon;
}
@ -448,7 +362,7 @@ IOActivityMonitor::Init(int32_t aInterval)
}
nsresult
IOActivityMonitor::Init_Internal(int32_t aInterval)
IOActivityMonitor::InitInternal()
{
// wraps the socket APIs
if (!sNetActivityMonitorLayerMethodsPtr) {
@ -468,20 +382,7 @@ IOActivityMonitor::Init_Internal(int32_t aInterval)
sNetActivityMonitorLayerMethodsPtr = &sNetActivityMonitorLayerMethods;
}
mInterval = aInterval;
// if the interval is 0, the timer is not fired
// and calls are done explicitely via NotifyActivities
if (mInterval == 0) {
return NS_OK;
}
// create and fire the timer
mTimer = NS_NewTimer();
if (!mTimer) {
return NS_ERROR_FAILURE;
}
return mTimer->InitWithCallback(this, mInterval, nsITimer::TYPE_REPEATING_SLACK);
return NS_OK;
}
nsresult
@ -491,16 +392,13 @@ IOActivityMonitor::Shutdown()
if (!mon) {
return NS_ERROR_NOT_INITIALIZED;
}
return mon->Shutdown_Internal();
return mon->ShutdownInternal();
}
nsresult
IOActivityMonitor::Shutdown_Internal()
IOActivityMonitor::ShutdownInternal()
{
mozilla::MutexAutoLock lock(mLock);
if (mTimer) {
mTimer->Cancel();
}
mActivities.Clear();
gInstance = nullptr;
return NS_OK;
@ -561,13 +459,15 @@ IOActivityMonitor::MonitorFile(PRFileDesc *aFd, const char* aPath)
return NS_OK;
}
IOActivity*
IOActivityMonitor::GetActivity(const nsACString& aLocation)
bool
IOActivityMonitor::IncrementActivity(const nsACString& aLocation, uint32_t aRx, uint32_t aTx)
{
mLock.AssertCurrentThreadOwns();
if (auto entry = mActivities.Lookup(aLocation)) {
// already registered
return entry.Data();
entry.Data().mTx += aTx;
entry.Data().mRx += aRx;
return true;
}
// Creating a new IOActivity. Notice that mActivities will
// grow indefinitely, which is OK since we won't have
@ -575,13 +475,15 @@ IOActivityMonitor::GetActivity(const nsACString& aLocation)
// want to assert we have at the most 1000 entries
MOZ_ASSERT(mActivities.Count() < MAX_ACTIVITY_ENTRIES);
// Entries are removed in the timer when they are inactive.
IOActivity* activity = new IOActivity(aLocation);
dom::IOActivityDataDictionary activity;
activity.mLocation.Assign(aLocation);
activity.mTx = aTx;
activity.mRx = aRx;
if (NS_WARN_IF(!mActivities.Put(aLocation, activity, fallible))) {
delete activity;
return nullptr;
return false;
}
return activity;
return true;
}
nsresult
@ -591,7 +493,7 @@ IOActivityMonitor::Write(const nsACString& aLocation, uint32_t aAmount)
if (!mon) {
return NS_ERROR_FAILURE;
}
return mon->Write_Internal(aLocation, aAmount);
return mon->WriteInternal(aLocation, aAmount);
}
nsresult
@ -605,14 +507,12 @@ IOActivityMonitor::Write(PRFileDesc *fd, uint32_t aAmount)
}
nsresult
IOActivityMonitor::Write_Internal(const nsACString& aLocation, uint32_t aAmount)
IOActivityMonitor::WriteInternal(const nsACString& aLocation, uint32_t aAmount)
{
mozilla::MutexAutoLock lock(mLock);
IOActivity* activity = GetActivity(aLocation);
if (!activity) {
if (!IncrementActivity(aLocation, aAmount, 0)) {
return NS_ERROR_FAILURE;
}
activity->tx += aAmount;
return NS_OK;
}
@ -633,17 +533,15 @@ IOActivityMonitor::Read(const nsACString& aLocation, uint32_t aAmount)
if (!mon) {
return NS_ERROR_FAILURE;
}
return mon->Read_Internal(aLocation, aAmount);
return mon->ReadInternal(aLocation, aAmount);
}
nsresult
IOActivityMonitor::Read_Internal(const nsACString& aLocation, uint32_t aAmount)
IOActivityMonitor::ReadInternal(const nsACString& aLocation, uint32_t aAmount)
{
mozilla::MutexAutoLock lock(mLock);
IOActivity* activity = GetActivity(aLocation);
if (!activity) {
if (!IncrementActivity(aLocation, 0, aAmount)) {
return NS_ERROR_FAILURE;
}
activity->rx += aAmount;
return NS_OK;
}

Просмотреть файл

@ -7,88 +7,45 @@
#ifndef IOActivityMonitor_h___
#define IOActivityMonitor_h___
#include "mozilla/dom/ChromeUtilsBinding.h"
#include "nsCOMPtr.h"
#include "nscore.h"
#include "nsClassHashtable.h"
#include "nsDataHashtable.h"
#include "nsHashKeys.h"
#include "nsIIOActivityData.h"
#include "nsISupports.h"
#include "nsITimer.h"
#include "prinrval.h"
#include "prio.h"
#include "private/pprio.h"
#include <stdint.h>
namespace mozilla { namespace net {
namespace mozilla {
namespace dom {
class Promise;
}
namespace net {
#define IO_ACTIVITY_ENABLED_PREF "io.activity.enabled"
#define IO_ACTIVITY_INTERVAL_PREF "io.activity.intervalMilliseconds"
//
// IOActivity keeps track of the amount of data
// sent and received for an FD / Location
//
struct IOActivity {
// the resource location, can be:
// - socket://ip:port
// - file://absolute/path
nsCString location;
typedef nsDataHashtable<nsCStringHashKey, dom::IOActivityDataDictionary> Activities;
// bytes received/read (rx) and sent/written (tx)
uint32_t rx;
uint32_t tx;
explicit IOActivity(const nsACString& aLocation) {
location.Assign(aLocation);
rx = 0;
tx = 0;
}
// Returns true if no data was transferred
bool Inactive() {
return rx == 0 && tx == 0;
}
// Sets the data to zero
void Reset() {
rx = 0;
tx = 0;
}
};
typedef nsClassHashtable<nsCStringHashKey, IOActivity> Activities;
// XPCOM Wrapper for an IOActivity
class IOActivityData final : public nsIIOActivityData
{
public:
NS_DECL_ISUPPORTS
NS_DECL_NSIIOACTIVITYDATA
explicit IOActivityData(IOActivity aActivity)
: mActivity(aActivity) {}
private:
~IOActivityData() = default;
IOActivity mActivity;
};
// IOActivityMonitor has several roles:
// - maintains an IOActivity per resource and updates it
// - sends a dump of the activities to observers that wants
// to get that info, via a timer
// - sends a dump of the activities to a promise via RequestActivities
class IOActivityMonitor final
: public nsITimerCallback
, public nsINamed
: public nsINamed
{
public:
IOActivityMonitor();
NS_DECL_THREADSAFE_ISUPPORTS
NS_DECL_NSITIMERCALLBACK
NS_DECL_NSINAMED
// initializes and destroys the singleton
static nsresult Init(int32_t aInterval);
static nsresult Init();
static nsresult Shutdown();
// collect amounts of data that are written/read by location
@ -101,25 +58,17 @@ public:
static nsresult Write(PRFileDesc *fd, uint32_t aAmount);
static bool IsActive();
// collects activities and notifies observers
// this method can be called manually or via the timer callback
static nsresult NotifyActivities();
static void RequestActivities(dom::Promise* aPromise);
private:
virtual ~IOActivityMonitor() = default;
nsresult Init_Internal(int32_t aInterval);
nsresult Shutdown_Internal();
IOActivity* GetActivity(const nsACString& location);
nsresult Write_Internal(const nsACString& location, uint32_t aAmount);
nsresult Read_Internal(const nsACString& location, uint32_t aAmount);
nsresult NotifyActivities_Internal();
~IOActivityMonitor() = default;
nsresult InitInternal();
nsresult ShutdownInternal();
bool IncrementActivity(const nsACString& location, uint32_t aRx, uint32_t aTx);
nsresult WriteInternal(const nsACString& location, uint32_t aAmount);
nsresult ReadInternal(const nsACString& location, uint32_t aAmount);
void RequestActivitiesInternal(dom::Promise* aPromise);
Activities mActivities;
// timer used to send notifications
uint32_t mInterval;
nsCOMPtr<nsITimer> mTimer;
// protects mActivities accesses
Mutex mLock;
};

Просмотреть файл

@ -52,7 +52,6 @@ XPIDL_SOURCES += [
'nsIIncrementalStreamLoader.idl',
'nsIInputStreamChannel.idl',
'nsIInputStreamPump.idl',
'nsIIOActivityData.idl',
'nsIIOService.idl',
'nsILoadContextInfo.idl',
'nsILoadGroup.idl',

Просмотреть файл

@ -1,19 +0,0 @@
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
#include "nsISupports.idl"
/**
* Keep tracks of the bytes that are sent (tx) and received (rx)
* into a socket identified by its file descriptor (fd)
* for a given host & port.
*/
[scriptable, builtinclass, uuid(30d5f743-939e-46c6-808a-7ea07c77028e)]
interface nsIIOActivityData : nsISupports
{
readonly attribute AUTF8String location;
readonly attribute long rx;
readonly attribute long tx;
};

Просмотреть файл

@ -1448,7 +1448,7 @@ nsSocketTransportService::Observe(nsISupports *subject,
if (!Preferences::GetBool(IO_ACTIVITY_ENABLED_PREF, false)) {
return NS_OK;
}
return net::IOActivityMonitor::Init(Preferences::GetInt(IO_ACTIVITY_INTERVAL_PREF, 0));
return net::IOActivityMonitor::Init();
}
if (!strcmp(topic, "last-pb-context-exited")) {

Просмотреть файл

@ -1,6 +1,7 @@
[DEFAULT]
support-files =
dummy.html
ioactivity.html
[browser_about_cache.js]
[browser_NetUtil.js]

Просмотреть файл

@ -4,80 +4,44 @@
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
const TEST_URL = "http://example.com/browser/dom/tests/browser/dummy.html";
const ROOT_URL = getRootDirectory(gTestPath).replace("chrome://mochitests/content/",
"https://example.com/");
const TEST_URL = "about:license";
const TEST_URL2 = ROOT_URL + "ioactivity.html";
var gotSocket = false;
var gotFile = false;
var gotSqlite = false;
var gotEmptyData = false;
var networkActivity = function(subject, topic, value) {
subject.QueryInterface(Ci.nsIMutableArray);
let enumerator = subject.enumerate();
while (enumerator.hasMoreElements()) {
let data = enumerator.getNext();
data = data.QueryInterface(Ci.nsIIOActivityData);
function processResults(results) {
for (let data of results) {
console.log(data.location);
gotEmptyData = data.rx == 0 && data.tx == 0 && !gotEmptyData
gotSocket = data.location.startsWith("socket://127.0.0.1:") || gotSocket;
gotFile = data.location.endsWith(".js") || gotFile;
gotFile = data.location.endsWith("aboutLicense.css") || gotFile;
gotSqlite = data.location.endsWith("places.sqlite") || gotSqlite;
}
};
function startObserver() {
gotSocket = gotFile = gotSqlite = gotEmptyData = false;
Services.obs.addObserver(networkActivity, "io-activity");
// why do I have to do this ??
add_task(async function testRequestIOActivity() {
await SpecialPowers.pushPrefEnv({
"set": [
["io.activity.enabled", true],
]
});
waitForExplicitFinish();
Services.obs.notifyObservers(null, "profile-initial-state", null);
}
// this test activates the timer and checks the results as they come in
add_task(async function testWithTimer() {
await SpecialPowers.pushPrefEnv({
"set": [
["io.activity.enabled", true],
["io.activity.intervalMilliseconds", 50]
]
});
waitForExplicitFinish();
startObserver();
await BrowserTestUtils.withNewTab({ gBrowser, url: "http://example.com" },
async function(browser) {
// wait until we get the events back
await BrowserTestUtils.waitForCondition(() => {
return gotSocket && gotFile && gotSqlite && !gotEmptyData;
}, "wait for events to come in", 500);
ok(gotSocket, "A socket was used");
ok(gotFile, "A file was used");
ok(gotSqlite, "A sqlite DB was used");
ok(!gotEmptyData, "Every I/O event had data");
});
});
// this test manually triggers notifications via ChromeUtils.requestIOActivity()
add_task(async function testWithManualCall() {
await SpecialPowers.pushPrefEnv({
"set": [
["io.activity.enabled", true],
]
});
waitForExplicitFinish();
startObserver();
await BrowserTestUtils.withNewTab({ gBrowser, url: "http://example.com" },
async function(browser) {
// wait until we get the events back
await BrowserTestUtils.waitForCondition(() => {
ChromeUtils.requestIOActivity();
return gotSocket && gotFile && gotSqlite && !gotEmptyData;
}, "wait for events to come in", 500);
await BrowserTestUtils.withNewTab(TEST_URL, async function(browser) {
await BrowserTestUtils.withNewTab(TEST_URL2, async function(browser) {
let results = await ChromeUtils.requestIOActivity();
processResults(results);
ok(gotSocket, "A socket was used");
ok(gotFile, "A file was used");
ok(gotSqlite, "A sqlite DB was used");
ok(!gotEmptyData, "Every I/O event had data");
});
});
});

Просмотреть файл

@ -0,0 +1,11 @@
<!DOCTYPE html>
<head>
<meta http-equiv="content-type" content="text/html; charset=utf-8">
</head>
<html>
<body>
<p>IOActivity Test Page</p>
</body>
</html>