-
Notifications
You must be signed in to change notification settings - Fork 116
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Optimistically read from /proc for process stats. #3374
Merged
Merged
Changes from all commits
Commits
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,181 @@ | ||
// 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. | ||
|
||
#include "cobalt/base/process/process_metrics_helper.h" | ||
|
||
#include <atomic> | ||
#include <cmath> | ||
#include <memory> | ||
#include <string> | ||
#include <utility> | ||
#include <vector> | ||
|
||
#include "base/files/file_enumerator.h" | ||
#include "base/files/file_path.h" | ||
#include "base/files/file_util.h" | ||
#include "base/memory/ptr_util.h" | ||
#include "base/process/internal_linux.h" | ||
#include "base/strings/string_number_conversions.h" | ||
#include "base/strings/string_split.h" | ||
#include "base/strings/string_util.h" | ||
#include "base/time/time.h" | ||
|
||
namespace base { | ||
|
||
namespace { | ||
|
||
static std::atomic<int> clock_ticks_per_s{0}; | ||
|
||
ProcessMetricsHelper::ReadCallback GetReadCallback(const FilePath& path) { | ||
return BindOnce( | ||
[](const FilePath& path) -> absl::optional<std::string> { | ||
std::string contents; | ||
if (!ReadFileToString(path, &contents)) return absl::nullopt; | ||
return std::move(contents); | ||
}, | ||
path); | ||
} | ||
|
||
double CalculateCPUUsageSeconds(const std::string& utime_string, | ||
const std::string& stime_string, | ||
int ticks_per_s) { | ||
DCHECK_NE(ticks_per_s, 0); | ||
double utime; | ||
if (!StringToDouble(utime_string, &utime)) return 0.0; | ||
double stime; | ||
if (!StringToDouble(stime_string, &stime)) return 0.0; | ||
return (utime + stime) / static_cast<double>(ticks_per_s); | ||
} | ||
|
||
} // namespace | ||
|
||
// static | ||
int ProcessMetricsHelper::GetClockTicksPerS() { | ||
return clock_ticks_per_s.load(); | ||
} | ||
|
||
// static | ||
int ProcessMetricsHelper::GetClockTicksPerS(ReadCallback uptime_callback, | ||
ReadCallback stat_callback) { | ||
double current_uptime = 0.0; | ||
{ | ||
auto uptime_contents = std::move(uptime_callback).Run(); | ||
if (!uptime_contents) return 0; | ||
auto parts = SplitString(*uptime_contents, " ", TRIM_WHITESPACE, | ||
SPLIT_WANT_NONEMPTY); | ||
if (parts.size() == 0 || !StringToDouble(parts[0], ¤t_uptime) || | ||
current_uptime == 0.0) { | ||
return 0; | ||
} | ||
} | ||
|
||
auto fields = GetProcStatFields(std::move(stat_callback), | ||
{internal::ProcStatsFields::VM_STARTTIME}); | ||
if (fields.size() != 1) return 0; | ||
double process_starttime; | ||
if (!StringToDouble(fields[0], &process_starttime) || | ||
process_starttime == 0.0) | ||
return 0; | ||
double ticks_per_s = process_starttime / current_uptime; | ||
int rounded_up = 10 * static_cast<int>(std::ceil(ticks_per_s / 10.0)); | ||
return rounded_up; | ||
} | ||
|
||
// static | ||
void ProcessMetricsHelper::PopulateClockTicksPerS() { | ||
DCHECK_EQ(clock_ticks_per_s.load(), 0); | ||
clock_ticks_per_s.store( | ||
GetClockTicksPerS(GetReadCallback(FilePath("/proc/uptime")), | ||
GetReadCallback(FilePath("/proc/self/stat")))); | ||
} | ||
|
||
// static | ||
TimeDelta ProcessMetricsHelper::GetCumulativeCPUUsage() { | ||
int ticks_per_s = clock_ticks_per_s.load(); | ||
if (ticks_per_s == 0) return TimeDelta(); | ||
return GetCPUUsage(FilePath("/proc/self"), ticks_per_s); | ||
} | ||
|
||
// static | ||
Value ProcessMetricsHelper::GetCumulativeCPUUsagePerThread() { | ||
int ticks_per_s = clock_ticks_per_s.load(); | ||
if (ticks_per_s == 0) return Value(); | ||
Value::List cpu_per_thread; | ||
FileEnumerator file_enum(FilePath("/proc/self/task"), /*recursive=*/false, | ||
FileEnumerator::DIRECTORIES); | ||
for (FilePath path = file_enum.Next(); !path.empty(); | ||
path = file_enum.Next()) { | ||
Fields fields = | ||
GetProcStatFields(path, {0, internal::ProcStatsFields::VM_COMM, | ||
internal::ProcStatsFields::VM_UTIME, | ||
internal::ProcStatsFields::VM_STIME}); | ||
if (fields.size() != 4) continue; | ||
int id; | ||
if (!StringToInt(fields[0], &id)) continue; | ||
Value::Dict entry = | ||
Value::Dict() | ||
.Set("id", id) | ||
.Set("name", fields[1]) | ||
.Set("utime", fields[2]) | ||
.Set("stime", fields[3]) | ||
.Set("usage_seconds", | ||
CalculateCPUUsageSeconds(fields[2], fields[3], ticks_per_s)); | ||
cpu_per_thread.Append(std::move(entry)); | ||
} | ||
return Value(std::move(cpu_per_thread)); | ||
} | ||
|
||
// static | ||
ProcessMetricsHelper::Fields ProcessMetricsHelper::GetProcStatFields( | ||
aee-google marked this conversation as resolved.
Show resolved
Hide resolved
|
||
ReadCallback read_callback, std::initializer_list<int> indices) { | ||
absl::optional<std::string> contents = std::move(read_callback).Run(); | ||
if (!contents) return Fields(); | ||
|
||
std::vector<std::string> proc_stats; | ||
if (!internal::ParseProcStats(*contents, &proc_stats)) return Fields(); | ||
|
||
Fields fields; | ||
for (int index : indices) { | ||
if (index < 0 || index >= proc_stats.size()) return Fields(); | ||
fields.push_back(std::move(proc_stats[index])); | ||
} | ||
return std::move(fields); | ||
} | ||
|
||
// static | ||
ProcessMetricsHelper::Fields ProcessMetricsHelper::GetProcStatFields( | ||
const FilePath& path, std::initializer_list<int> indices) { | ||
return ProcessMetricsHelper::GetProcStatFields( | ||
GetReadCallback(path.Append("stat")), indices); | ||
} | ||
|
||
// static | ||
TimeDelta ProcessMetricsHelper::GetCPUUsage(ReadCallback read_callback, | ||
int ticks_per_s) { | ||
auto fields = ProcessMetricsHelper::GetProcStatFields( | ||
std::move(read_callback), {internal::ProcStatsFields::VM_UTIME, | ||
internal::ProcStatsFields::VM_STIME}); | ||
if (fields.size() != 2) return TimeDelta(); | ||
return TimeDelta::FromSecondsD( | ||
CalculateCPUUsageSeconds(fields[0], fields[1], ticks_per_s)); | ||
} | ||
|
||
// static | ||
TimeDelta ProcessMetricsHelper::GetCPUUsage(const FilePath& path, | ||
int ticks_per_s) { | ||
return ProcessMetricsHelper::GetCPUUsage(GetReadCallback(path.Append("stat")), | ||
ticks_per_s); | ||
} | ||
|
||
} // namespace base |
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Is the existing logic broken in upstream, or is it not a "hard broken" and its just that the upstream returns the thread name with the parentheses and you changed that for us to leave those out?
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
The pid has an extra space at the end. Everything else is parsed correctly.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
It would be better to keep variable names the same where possible and keep our changes in STARBOARD/USE_COBALT_CUSTOMIZATIONS blocks, the only thing I see changing is comm_start
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
We need the start and end positions for
pid
andcomm
, and we need the start position forstate
.open_parens_idx
was the first occurrence of" (
. This is thepid
end.pid
start position is0
.open_parens_idx
is incremented and thepid
substring is off by 1.Naming the positions we need avoids the modifying the value and using it to represent two different things.
stats_data.substr(start, end - start)
returns the value we want.After the last
") "
, the rest of the fields are space delimited.If I wanted to leave the code mostly the same, I would need to either move the
open_parens_idx++
after getting thepid
or removing the increment and fix howcomm
is retrieved.There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Another option is to parse the
/proc/pid/stat
incobalt/base/process/process_metrics_helper.cc
.There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Unless we upstream this code (the ideal solution) or guard it with ifdefs (an easier immediate solution), someone will eventually try to revert this back to the original code i.e. during an update as right now it looks like a mistaken diff from the upstream. Using the ifdefs we usually use makes it clear to readers that it's a conscious decision instead