-
Notifications
You must be signed in to change notification settings - Fork 167
Expand file tree
/
Copy pathTotalProcessorCount.cs
More file actions
201 lines (168 loc) · 6.88 KB
/
Copy pathTotalProcessorCount.cs
File metadata and controls
201 lines (168 loc) · 6.88 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
// <copyright file="TotalProcessorCount.cs" company="Datadog">
// Unless explicitly stated otherwise all files in this repository are licensed under the Apache 2 License.
// This product includes software developed at Datadog (https://www.datadoghq.com/). Copyright 2017 Datadog, Inc.
// </copyright>
#if NET6_0_OR_GREATER
#nullable enable
using System;
using System.IO;
using System.Runtime.InteropServices;
using Datadog.Trace.Logging;
using Datadog.Trace.SourceGenerators;
namespace Datadog.Trace.RuntimeMetrics;
internal static class TotalProcessorCount
{
private static readonly Lazy<int?> LazyValue = new(GetTotalProcessorCount);
private static readonly IDatadogLogger Log = DatadogLogging.GetLoggerFor(typeof(TotalProcessorCount));
/// <summary>
/// Gets the total number of logical processors on the host machine. Differs from
/// <see cref="Environment.ProcessorCount"/> (which includes cgroup/container CPU limits
/// and process affinity). Mirrors the GC's own GCToOSInterface::GetTotalProcessorCount()
/// </summary>
public static int? Value => LazyValue.Value;
[TestingAndPrivateOnly]
internal static int? GetTotalProcessorCount()
{
if (OperatingSystem.IsWindows())
{
return WindowsProcessorCount.GetTotalProcessorCount();
}
if (OperatingSystem.IsLinux())
{
return LinuxProcessorCount.GetTotalProcessorCount();
}
if (OperatingSystem.IsMacOS())
{
return MacOsProcessorCount.GetTotalProcessorCount();
}
return null;
}
internal static class WindowsProcessorCount
{
private const ushort AllProcessorGroups = 0xFFFF;
[DllImport("kernel32.dll", SetLastError = true)]
private static extern int GetActiveProcessorCount(ushort groupNumber);
/// <summary>
/// Gets the total number of logical processors on a Windows host via <c>GetActiveProcessorCount</c>,
/// counting active processors across all processor groups and ignoring process affinity and Job Object
/// CPU limits (the container-CPU-cap mechanism on Windows).
/// </summary>
internal static int? GetTotalProcessorCount()
{
var result = GetActiveProcessorCount(AllProcessorGroups);
if (result > 0)
{
return result;
}
var error = Marshal.GetLastWin32Error();
Log.Warning(
"GetActiveProcessorCount failed when getting total machine processor count. ErrorCode={ErrorCode}",
property: error);
return null;
}
}
internal static class LinuxProcessorCount
{
private const string OnlineCpusPath = "/sys/devices/system/cpu/online";
/// <summary>
/// Gets the total number of logical processors on a Linux host by reading the online-CPU range
/// reported by the kernel, the same source <c>sysconf(_SC_NPROCESSORS_ONLN)</c> itself reads, and unaffected
/// by cgroup CPU quotas. Avoids P/Invoking into libc, which fails to resolve on musl-based images (e.g. Alpine).
/// </summary>
internal static int? GetTotalProcessorCount()
{
try
{
var contents = File.ReadAllText(OnlineCpusPath);
return TryParseOnlineCpuRanges(contents.AsSpan());
}
catch (Exception ex)
{
Log.Warning(ex, "Error reading {Path} to determine total machine processor count", OnlineCpusPath);
return null;
}
}
// Parses the Linux cpu-list-format (see Documentation/admin-guide/kernel-parameters.txt)
// comma-separated list of either a single CPU index ("0") or an inclusive range ("0-7"), e.g. "0-3,8-11".
[TestingAndPrivateOnly]
internal static int? TryParseOnlineCpuRanges(ReadOnlySpan<char> contents)
{
var trimmed = contents.Trim();
if (trimmed.IsEmpty)
{
return null;
}
var count = 0;
var remaining = trimmed;
while (!remaining.IsEmpty)
{
var commaIndex = remaining.IndexOf(',');
var token = commaIndex < 0 ? remaining : remaining[..commaIndex];
if (!TryParseToken(token, out var tokenCount))
{
return null;
}
count += tokenCount;
if (commaIndex < 0)
{
break;
}
remaining = remaining[(commaIndex + 1)..];
if (remaining.IsEmpty)
{
// trailing comma with no following token
return null;
}
}
return count > 0 ? count : null;
static bool TryParseToken(ReadOnlySpan<char> token, out int tokenCount)
{
tokenCount = 0;
var dashIndex = token.IndexOf('-');
if (dashIndex < 0)
{
if (!int.TryParse(token, out var single) || single < 0)
{
return false;
}
tokenCount = 1;
return true;
}
var startSpan = token[..dashIndex];
var endSpan = token[(dashIndex + 1)..];
if (!int.TryParse(startSpan, out var start) || start < 0 ||
!int.TryParse(endSpan, out var end) || end < start)
{
return false;
}
tokenCount = end - start + 1;
return true;
}
}
}
internal static class MacOsProcessorCount
{
private const string LogicalCpuName = "hw.logicalcpu";
[DllImport("libSystem.dylib", EntryPoint = "sysctlbyname", CharSet = CharSet.Ansi, SetLastError = true)]
private static extern int SysCtlByName(string name, out int oldp, ref IntPtr oldlenp, IntPtr newp, IntPtr newlen);
/// <summary>
/// Gets the total number of logical processors on a macOS host via <c>sysctlbyname("hw.logicalcpu", ...)</c>,
/// the standard, stable way to query total logical CPUs on macOS.
/// </summary>
internal static int? GetTotalProcessorCount()
{
var size = new IntPtr(sizeof(int));
var result = SysCtlByName(LogicalCpuName, out var value, ref size, IntPtr.Zero, IntPtr.Zero);
if (result == 0 && value > 0)
{
return value;
}
var error = Marshal.GetLastWin32Error();
Log.Warning(
"sysctlbyname failed when getting total machine processor count. ErrorCode={ErrorCode}",
property: error);
return null;
}
}
}
#endif