Skip to content

Commit

Permalink
Add navigator.hardwareConcurrency support for linux.
Browse files Browse the repository at this point in the history
b/341774149
  • Loading branch information
aee-google committed Aug 13, 2024
1 parent 9545024 commit be3afa1
Show file tree
Hide file tree
Showing 12 changed files with 198 additions and 0 deletions.
57 changes: 57 additions & 0 deletions cobalt/base/process/process_metrics_helper.cc
Original file line number Diff line number Diff line change
Expand Up @@ -36,6 +36,7 @@ namespace base {
namespace {

static std::atomic<int> clock_ticks_per_s{0};
static std::atomic<int> number_of_configured_processors{0};

ProcessMetricsHelper::ReadCallback GetReadCallback(const FilePath& path) {
return BindOnce(
Expand Down Expand Up @@ -178,4 +179,60 @@ TimeDelta ProcessMetricsHelper::GetCPUUsage(const FilePath& path,
ticks_per_s);
}

// static
int ProcessMetricsHelper::GetNumberOfConfiguredProcessors(
ReadCallback read_callback) {
absl::optional<std::string> contents = std::move(read_callback).Run();
if (!contents.has_value()) {
// Expected for non-Linux platforms.
LOG(WARNING) << "Not supported for platform.";
return -1;
}

auto chunks =
SplitString(*contents, ",", TRIM_WHITESPACE, SPLIT_WANT_NONEMPTY);
int count = 0;
int lowerProcessorNumber = -1;
int upperProcessorNumber = -1;
for (const auto& chunk : chunks) {
auto chunkParts =
SplitString(chunk, "-", TRIM_WHITESPACE, SPLIT_WANT_NONEMPTY);
if (chunkParts.size() == 0 || chunkParts.size() > 2) {
LOG(ERROR) << "Unexpected format of processor count chunks.";
return -2;
}
if (!StringToInt(chunkParts[0], &lowerProcessorNumber)) {
LOG(ERROR) << "Unexpected format of processor count chunks.";
return -3;
}
if (chunkParts.size() == 1) {
count++;
continue;
}
if (!StringToInt(chunkParts[1], &upperProcessorNumber)) {
LOG(ERROR) << "Unexpected format of processor count chunks.";
return -3;
}
if (upperProcessorNumber <= lowerProcessorNumber) {
LOG(ERROR) << "Unexpected format of processor count chunks.";
return -4;
}
count += 1 + upperProcessorNumber - lowerProcessorNumber;
}

return count;
}

// static
int ProcessMetricsHelper::GetNumberOfConfiguredProcessors() {
int stored_value = number_of_configured_processors.load();
if (stored_value != 0) {
return stored_value;
}
int result = GetNumberOfConfiguredProcessors(
GetReadCallback(FilePath("/sys/devices/system/cpu/possible")));
number_of_configured_processors.store(result);
return result;
}

} // namespace base
2 changes: 2 additions & 0 deletions cobalt/base/process/process_metrics_helper.h
Original file line number Diff line number Diff line change
Expand Up @@ -38,6 +38,7 @@ class ProcessMetricsHelper {
static void PopulateClockTicksPerS();
static TimeDelta GetCumulativeCPUUsage();
static Value GetCumulativeCPUUsagePerThread();
static int GetNumberOfConfiguredProcessors();

private:
friend class ProcessMetricsHelperTest;
Expand All @@ -47,6 +48,7 @@ class ProcessMetricsHelper {
static Fields GetProcStatFields(const FilePath&, std::initializer_list<int>);
static TimeDelta GetCPUUsage(ReadCallback, int);
static TimeDelta GetCPUUsage(const FilePath&, int);
static int GetNumberOfConfiguredProcessors(ReadCallback);
};

} // namespace base
Expand Down
23 changes: 23 additions & 0 deletions cobalt/base/process/process_metrics_helper_test.cc
Original file line number Diff line number Diff line change
Expand Up @@ -114,6 +114,17 @@ class ProcessMetricsHelperTest : public testing::Test {
return ProcessMetricsHelper::GetCPUUsage(std::move(stat_callback),
ticks_per_s);
}

int GetNumberOfConfiguredProcessorsWithMockData(const std::string& contents) {
return ProcessMetricsHelper::GetNumberOfConfiguredProcessors(BindOnce(
[](const std::string& contents) -> absl::optional<std::string> {
if (contents.size() == 0) {
return absl::nullopt;
}
return contents;
},
contents));
}
};

ProcessMetricsHelper::ReadCallback GetNulloptCallback() {
Expand Down Expand Up @@ -220,4 +231,16 @@ TEST_F(ProcessMetricsHelperTest, GetCumulativeCPUUsagePerThread) {
thread3.Stop();
}

TEST_F(ProcessMetricsHelperTest, GetNumberOfConfiguredProcessors) {
EXPECT_EQ(-1, GetNumberOfConfiguredProcessorsWithMockData(""));
EXPECT_EQ(-2, GetNumberOfConfiguredProcessorsWithMockData("0-2-3"));
EXPECT_EQ(-3, GetNumberOfConfiguredProcessorsWithMockData("a"));
EXPECT_EQ(-4, GetNumberOfConfiguredProcessorsWithMockData("3-0"));
EXPECT_EQ(1, GetNumberOfConfiguredProcessorsWithMockData("0"));
EXPECT_EQ(96, GetNumberOfConfiguredProcessorsWithMockData("0-95"));
EXPECT_EQ(96,
GetNumberOfConfiguredProcessorsWithMockData("0-5,6,7-12,13,14-95"));
EXPECT_EQ(96, ProcessMetricsHelper::GetNumberOfConfiguredProcessors());
}

} // namespace base
1 change: 1 addition & 0 deletions cobalt/black_box_tests/black_box_tests.py
Original file line number Diff line number Diff line change
Expand Up @@ -74,6 +74,7 @@
# 'h5vcc_watchdog_api_test',
'http_cache',
'javascript_profiler',
'navigator_test',
'performance_resource_timing_test',
'persistent_cookie',
'pointer_event_on_fixed_element_test',
Expand Down
29 changes: 29 additions & 0 deletions cobalt/black_box_tests/testdata/navigator_test.html
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
<!DOCTYPE html>
<!--
Copyright 2024 The Cobalt Authors. All Rights Reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
-->
<html>
<head>
<script src="black_box_js_test_utils.js"></script>
</head>
<body>
<script>
setupFinished();
assertTrue(typeof(navigator.hardwareConcurrency) === 'number');
assertTrue(navigator.hardwareConcurrency >= 1);
onEndTest();
</script>
</body>
</html>
47 changes: 47 additions & 0 deletions cobalt/black_box_tests/tests/navigator_test.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,47 @@
# Copyright 2024 The Cobalt Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Test navigator API."""

from cobalt.black_box_tests import black_box_tests
from cobalt.black_box_tests.threaded_web_server import ThreadedWebServer
import logging

PLATFORMS_SUPPORTED = [
'linux-x64x11',
'linux-x64x11-egl',
'linux-x64x11-gcc-6-3',
'linux-x64x11-skia',
'android-arm',
'android-arm64',
'android-arm64-vulkan',
'android-x86',
'raspi-2',
'raspi-2-skia',
'linux-x64x11-clang-crosstool',
]


class NavigatorTest(black_box_tests.BlackBoxTestCase):

def test_navigator(self):
if self.launcher_params.platform not in PLATFORMS_SUPPORTED:
logging.warning('Blackbox tests disabled for platform:%s',
self.launcher_params.platform)
return

with ThreadedWebServer(binding_address=self.GetBindingAddress()) as server:
url = server.GetURL(file_name='testdata/navigator_test.html')
with self.CreateCobaltRunner(url=url) as runner:
runner.WaitForJSTestsSetup()
self.assertTrue(runner.JSTestsSucceeded())
1 change: 1 addition & 0 deletions cobalt/browser/idl_files.gni
Original file line number Diff line number Diff line change
Expand Up @@ -399,6 +399,7 @@ dependency_idl_files = [
"//cobalt/dom/global_event_handlers.idl",
"//cobalt/dom/html_element_cssom_view.idl",
"//cobalt/dom/mouse_event_cssom_view.idl",
"//cobalt/dom/navigator_concurrent_hardware.idl",
"//cobalt/dom/navigator_licenses.idl",
"//cobalt/dom/navigator_plugins.idl",
"//cobalt/dom/navigator_storage_utils.idl",
Expand Down
6 changes: 6 additions & 0 deletions cobalt/dom/navigator.cc
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@

#include "base/optional.h"
#include "base/trace_event/trace_event.h"
#include "cobalt/base/process/process_metrics_helper.h"
#include "cobalt/dom/captions/system_caption_settings.h"
#include "cobalt/dom/dom_settings.h"
#include "cobalt/dom/embedded_licenses.h" // Generated file.
Expand Down Expand Up @@ -154,6 +155,11 @@ Navigator::Navigator(script::EnvironmentSettings* settings,
new media_capture::MediaDevices(settings, script_value_factory())),
system_caption_settings_(captions) {}

uint64_t Navigator::hardware_concurrency() const {
int count = base::ProcessMetricsHelper::GetNumberOfConfiguredProcessors();
return count <= 0 ? 0 : static_cast<uint64_t>(count);
}

const std::string Navigator::licenses() const {
GeneratedResourceMap resource_map;
DOMEmbeddedResources::GenerateMap(resource_map);
Expand Down
2 changes: 2 additions & 0 deletions cobalt/dom/navigator.h
Original file line number Diff line number Diff line change
Expand Up @@ -47,6 +47,8 @@ class Navigator : public web::NavigatorBase {
Navigator(const Navigator&) = delete;
Navigator& operator=(const Navigator&) = delete;

uint64_t hardware_concurrency() const;

// Web API: NavigatorLicenses
const std::string licenses() const;

Expand Down
1 change: 1 addition & 0 deletions cobalt/dom/navigator.idl
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@

interface Navigator {};

Navigator implements NavigatorConcurrentHardware;
Navigator implements NavigatorID;
Navigator implements NavigatorLanguage;
Navigator implements NavigatorPlugins;
Expand Down
18 changes: 18 additions & 0 deletions cobalt/dom/navigator_concurrent_hardware.idl
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
// Copyright 2024 The Cobalt Authors. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

[NoInterfaceObject]
interface NavigatorConcurrentHardware {
readonly attribute unsigned long long hardwareConcurrency;
};
11 changes: 11 additions & 0 deletions cobalt/dom/navigator_test.cc
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@
#include <string>

#include "base/logging.h"
#include "base/strings/string_number_conversions.h"
#include "cobalt/bindings/testing/utils.h"
#include "cobalt/dom/testing/test_with_javascript.h"
#include "cobalt/web/testing/gtest_workarounds.h"
Expand Down Expand Up @@ -160,5 +161,15 @@ TEST_F(NavigatorTest, NavigatorOnline) {
EXPECT_EQ("true", result);
}

TEST_F(NavigatorTest, NavigatorConcurrentHardware) {
std::string result;
EXPECT_TRUE(EvaluateScript("typeof navigator.hardwareConcurrency", &result));
EXPECT_EQ("number", result);
EXPECT_TRUE(EvaluateScript("navigator.hardwareConcurrency", &result));
int count = -1;
EXPECT_TRUE(base::StringToInt(result, &count));
EXPECT_GE(count, 0);
}

} // namespace dom
} // namespace cobalt

0 comments on commit be3afa1

Please sign in to comment.