-
Notifications
You must be signed in to change notification settings - Fork 849
Add Kubernetes based Resource Monitoring #6748
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
Merged
amadeuszl
merged 29 commits into
dotnet:main
from
amadeuszl:users/alechniak/kuberenetes-metadata
Nov 21, 2025
Merged
Changes from all commits
Commits
Show all changes
29 commits
Select commit
Hold shift + click to select a range
be94825
Draft
amadeuszl bb36737
Draft
amadeuszl 6024134
Merge branch 'main' into users/alechniak/kuberenetes-metadata
amadeuszl 785a2f0
Add ResourceQuotasProvider
amadeuszl 95e1a3c
Fix public API surface, remove Quotas provider component
amadeuszl cfc4861
Switch layering of the abstractions to support Kubernetes metadata
amadeuszl 27fd482
Merge branch 'main' into users/alechniak/kuberenetes-metadata
amadeuszl 632636f
Fix namespace
amadeuszl 4faae5b
Remove ClusterMetadata
amadeuszl d49ab90
Add Linux changes
amadeuszl 727159a
Add abstractions project
amadeuszl 02517e4
Merge branch 'dotnet:main' into users/alechniak/kuberenetes-metadata
amadeuszl 8057769
Merge branch 'users/alechniak/kuberenetes-metadata' of https://github…
amadeuszl ced4716
Add changes after API Review
amadeuszl 66bf3ca
Add changes after API Review pt.2
amadeuszl 67c3553
Merge branch 'main' into users/alechniak/kuberenetes-metadata
amadeuszl 87b81cf
Fixes
amadeuszl cd8bf74
Add reading memory min and low for cgroupsv2
amadeuszl 296f896
Add unit tests
amadeuszl 01f2f4d
Fix typos
amadeuszl fb94614
Address PR comments and fix lint issues
amadeuszl d9158c0
Fix flaky test
amadeuszl 9e4eb2b
Merge branch 'main' into users/alechniak/kuberenetes-metadata
amadeuszl e5aa589
Fix tests verified files
amadeuszl 10a3ef2
Merge branch 'main' into users/alechniak/kuberenetes-metadata
amadeuszl 5be7619
Fix tests, switch to experimental
amadeuszl 282f9d0
Fix errors
amadeuszl b34b2fd
Fix more errors
amadeuszl 9443ab5
Remove TestUtilities reference
amadeuszl 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
57 changes: 57 additions & 0 deletions
57
...ries/Microsoft.Extensions.Diagnostics.ResourceMonitoring.Kubernetes/KubernetesMetadata.cs
This file contains hidden or 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,57 @@ | ||
| // Licensed to the .NET Foundation under one or more agreements. | ||
| // The .NET Foundation licenses this file to you under the MIT license. | ||
|
|
||
| using System; | ||
| using System.Globalization; | ||
|
|
||
| namespace Microsoft.Extensions.Diagnostics.ResourceMonitoring.Kubernetes; | ||
|
|
||
| internal sealed class KubernetesMetadata | ||
| { | ||
| /// <summary> | ||
| /// Gets or sets the resource memory limit the container is allowed to use in bytes. | ||
| /// </summary> | ||
| public ulong LimitsMemory { get; set; } | ||
|
|
||
| /// <summary> | ||
| /// Gets or sets the resource CPU limit the container is allowed to use in millicores. | ||
| /// </summary> | ||
| public ulong LimitsCpu { get; set; } | ||
|
|
||
| /// <summary> | ||
| /// Gets or sets the resource memory request the container is allowed to use in bytes. | ||
| /// </summary> | ||
| public ulong RequestsMemory { get; set; } | ||
|
|
||
| /// <summary> | ||
| /// Gets or sets the resource CPU request the container is allowed to use in millicores. | ||
| /// </summary> | ||
| public ulong RequestsCpu { get; set; } | ||
|
|
||
| public static KubernetesMetadata FromEnvironmentVariables(string environmentVariablePrefix) | ||
| { | ||
| return new KubernetesMetadata | ||
| { | ||
| LimitsMemory = GetEnvironmentVariableAsUInt64($"{environmentVariablePrefix}LIMITS_MEMORY"), | ||
| LimitsCpu = GetEnvironmentVariableAsUInt64($"{environmentVariablePrefix}LIMITS_CPU"), | ||
| RequestsMemory = GetEnvironmentVariableAsUInt64($"{environmentVariablePrefix}REQUESTS_MEMORY"), | ||
| RequestsCpu = GetEnvironmentVariableAsUInt64($"{environmentVariablePrefix}REQUESTS_CPU"), | ||
| }; | ||
| } | ||
|
|
||
| private static ulong GetEnvironmentVariableAsUInt64(string variableName) | ||
| { | ||
| var value = Environment.GetEnvironmentVariable(variableName); | ||
| if (string.IsNullOrWhiteSpace(value)) | ||
| { | ||
| return 0; | ||
| } | ||
|
|
||
| if (!ulong.TryParse(value, NumberStyles.None, CultureInfo.InvariantCulture, out ulong result)) | ||
| { | ||
| throw new InvalidOperationException($"Environment variable '{variableName}' contains invalid value '{value}'. Expected a non-negative integer."); | ||
| } | ||
|
|
||
| return result; | ||
| } | ||
| } |
46 changes: 46 additions & 0 deletions
46
...t.Extensions.Diagnostics.ResourceMonitoring.Kubernetes/KubernetesResourceQuotaProvider.cs
This file contains hidden or 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,46 @@ | ||
| // Licensed to the .NET Foundation under one or more agreements. | ||
| // The .NET Foundation licenses this file to you under the MIT license. | ||
|
|
||
| using Microsoft.Shared.Diagnostics; | ||
|
|
||
| namespace Microsoft.Extensions.Diagnostics.ResourceMonitoring.Kubernetes; | ||
|
|
||
| internal sealed class KubernetesResourceQuotaProvider : ResourceQuotaProvider | ||
| { | ||
| private const double MillicoresPerCore = 1000.0; | ||
| private KubernetesMetadata _kubernetesMetadata; | ||
|
|
||
| public KubernetesResourceQuotaProvider(KubernetesMetadata kubernetesMetadata) | ||
| { | ||
| _ = Throw.IfNull(kubernetesMetadata); | ||
| _kubernetesMetadata = kubernetesMetadata; | ||
| } | ||
|
|
||
| public override ResourceQuota GetResourceQuota() | ||
| { | ||
| ResourceQuota quota = new() | ||
| { | ||
| BaselineCpuInCores = ConvertMillicoreToCpuUnit(_kubernetesMetadata.RequestsCpu), | ||
| MaxCpuInCores = ConvertMillicoreToCpuUnit(_kubernetesMetadata.LimitsCpu), | ||
| BaselineMemoryInBytes = _kubernetesMetadata.RequestsMemory, | ||
| MaxMemoryInBytes = _kubernetesMetadata.LimitsMemory, | ||
| }; | ||
|
|
||
| if (quota.BaselineCpuInCores <= 0.0) | ||
| { | ||
| quota.BaselineCpuInCores = quota.MaxCpuInCores; | ||
| } | ||
|
|
||
| if (quota.BaselineMemoryInBytes == 0) | ||
| { | ||
| quota.BaselineMemoryInBytes = quota.MaxMemoryInBytes; | ||
| } | ||
|
|
||
| return quota; | ||
evgenyfedorov2 marked this conversation as resolved.
Show resolved
Hide resolved
|
||
| } | ||
|
|
||
| private static double ConvertMillicoreToCpuUnit(ulong millicores) | ||
| { | ||
| return millicores / MillicoresPerCore; | ||
| } | ||
| } | ||
45 changes: 45 additions & 0 deletions
45
...stics.ResourceMonitoring.Kubernetes/KubernetesResourceQuotaServiceCollectionExtensions.cs
This file contains hidden or 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,45 @@ | ||
| // Licensed to the .NET Foundation under one or more agreements. | ||
| // The .NET Foundation licenses this file to you under the MIT license. | ||
|
|
||
| using Microsoft.Extensions.DependencyInjection.Extensions; | ||
| using Microsoft.Extensions.Diagnostics.ResourceMonitoring; | ||
| using Microsoft.Extensions.Diagnostics.ResourceMonitoring.Kubernetes; | ||
|
|
||
| namespace Microsoft.Extensions.DependencyInjection; | ||
|
|
||
| /// <summary> | ||
| /// Lets you configure and register Kubernetes resource monitoring components. | ||
| /// </summary> | ||
| public static class KubernetesResourceQuotaServiceCollectionExtensions | ||
| { | ||
| /// <summary> | ||
| /// Configures and adds an Kubernetes resource monitoring components to a service collection altogether with necessary basic resource monitoring components. | ||
| /// </summary> | ||
| /// <param name="services">The dependency injection container to add the Kubernetes resource monitoring to.</param> | ||
| /// <param name="environmentVariablePrefix">Optional value of prefix used to read environment variables in the container.</param> | ||
| /// <returns>The value of <paramref name="services" />.</returns> | ||
| /// <remarks> | ||
| /// <para> | ||
| /// If you have configured your Kubernetes container with Downward API to add environment variable <c>MYCLUSTER_LIMITS_CPU</c> with CPU limits, | ||
| /// then you should pass <c>MYCLUSTER_</c> to <paramref name="environmentVariablePrefix"/> parameter. Environment variables will be read during DI Container resolution. | ||
| /// </para> | ||
| /// <para> | ||
| /// <strong>Important:</strong> Do not call <see cref="ResourceMonitoringServiceCollectionExtensions.AddResourceMonitoring(IServiceCollection)"/> | ||
| /// if you are using this method, as it already includes all necessary resource monitoring components and registers a Kubernetes-specific | ||
| /// <see cref="ResourceQuotaProvider"/> implementation. Calling both methods may result in conflicting service registrations. | ||
| /// </para> | ||
| /// </remarks> | ||
| public static IServiceCollection AddKubernetesResourceMonitoring( | ||
| this IServiceCollection services, | ||
| string? environmentVariablePrefix = default) | ||
| { | ||
| services.TryAddSingleton<ResourceQuotaProvider>(sp => | ||
| { | ||
| return new KubernetesResourceQuotaProvider(KubernetesMetadata.FromEnvironmentVariables(environmentVariablePrefix ?? string.Empty)); | ||
| }); | ||
|
|
||
| _ = services.AddResourceMonitoring(); | ||
|
|
||
| return services; | ||
| } | ||
| } |
29 changes: 29 additions & 0 deletions
29
...nitoring.Kubernetes/Microsoft.Extensions.Diagnostics.ResourceMonitoring.Kubernetes.csproj
This file contains hidden or 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,29 @@ | ||
| <Project Sdk="Microsoft.NET.Sdk"> | ||
| <PropertyGroup> | ||
| <RootNamespace>Microsoft.Extensions.Diagnostics.ResourceMonitoring.Kubernetes</RootNamespace> | ||
| <Description>Provides Kubernetes data for measurements of processor and memory usage.</Description> | ||
| <Workstream>ResourceMonitoring</Workstream> | ||
| <NoWarn Condition="'$(TargetFramework)' == 'net462'">$(NoWarn);CS0436</NoWarn> | ||
| </PropertyGroup> | ||
|
|
||
| <PropertyGroup> | ||
| <InjectExperimentalAttributeOnLegacy>true</InjectExperimentalAttributeOnLegacy> | ||
| <InjectSharedInstruments>true</InjectSharedInstruments> | ||
| </PropertyGroup> | ||
|
|
||
| <PropertyGroup> | ||
| <Stage>dev</Stage> | ||
| <StageDevDiagnosticId>EXTEXP0016</StageDevDiagnosticId> | ||
| <MinCodeCoverage>99</MinCodeCoverage> | ||
| <MinMutationScore>90</MinMutationScore> | ||
| </PropertyGroup> | ||
|
|
||
| <ItemGroup> | ||
| <ProjectReference Include="..\Microsoft.Extensions.Diagnostics.ResourceMonitoring\Microsoft.Extensions.Diagnostics.ResourceMonitoring.csproj" /> | ||
| </ItemGroup> | ||
|
|
||
| <ItemGroup> | ||
| <InternalsVisibleToDynamicProxyGenAssembly2 Include="*" /> | ||
| <InternalsVisibleToTest Include="$(AssemblyName).Tests" /> | ||
| </ItemGroup> | ||
| </Project> |
Empty file.
24 changes: 24 additions & 0 deletions
24
...raries/Microsoft.Extensions.Diagnostics.ResourceMonitoring.Kubernetes/README.md
This file contains hidden or 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,24 @@ | ||
| # Microsoft.Extensions.Diagnostics.ResourceMonitoring.Kubernetes | ||
|
|
||
| Registers `ResourceQuota` implementation specific to Kubernetes. | ||
|
|
||
| ## Install the package | ||
|
|
||
| From the command-line: | ||
|
|
||
| ```console | ||
| dotnet add package Microsoft.Extensions.Diagnostics.ResourceMonitoring.Kubernetes | ||
| ``` | ||
|
|
||
| Or directly in the C# project file: | ||
|
|
||
| ```xml | ||
| <ItemGroup> | ||
| <PackageReference Include="Microsoft.Extensions.Diagnostics.ResourceMonitoring.Kubernetes" Version="[CURRENTVERSION]" /> | ||
| </ItemGroup> | ||
| ``` | ||
|
|
||
|
|
||
| ## Feedback & Contributing | ||
|
|
||
| We welcome feedback and contributions in [our GitHub repo](https://github.com/dotnet/extensions). |
This file contains hidden or 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
44 changes: 44 additions & 0 deletions
44
...s/Microsoft.Extensions.Diagnostics.ResourceMonitoring/Linux/LinuxResourceQuotaProvider.cs
This file contains hidden or 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,44 @@ | ||
| // Licensed to the .NET Foundation under one or more agreements. | ||
| // The .NET Foundation licenses this file to you under the MIT license. | ||
|
|
||
| using Microsoft.Extensions.Options; | ||
|
|
||
| namespace Microsoft.Extensions.Diagnostics.ResourceMonitoring.Linux; | ||
|
|
||
| internal sealed class LinuxResourceQuotaProvider : ResourceQuotaProvider | ||
| { | ||
| private readonly ILinuxUtilizationParser _parser; | ||
| private bool _useLinuxCalculationV2; | ||
|
|
||
| public LinuxResourceQuotaProvider(ILinuxUtilizationParser parser, IOptions<ResourceMonitoringOptions> options) | ||
| { | ||
| _parser = parser; | ||
| _useLinuxCalculationV2 = options.Value.UseLinuxCalculationV2; | ||
| } | ||
|
|
||
| public override ResourceQuota GetResourceQuota() | ||
| { | ||
| var resourceQuota = new ResourceQuota(); | ||
| if (_useLinuxCalculationV2) | ||
| { | ||
| resourceQuota.MaxCpuInCores = _parser.GetCgroupLimitV2(); | ||
| resourceQuota.BaselineCpuInCores = _parser.GetCgroupRequestCpuV2(); | ||
| } | ||
| else | ||
| { | ||
| resourceQuota.MaxCpuInCores = _parser.GetCgroupLimitedCpus(); | ||
| resourceQuota.BaselineCpuInCores = _parser.GetCgroupRequestCpu(); | ||
| } | ||
|
|
||
| resourceQuota.MaxMemoryInBytes = _parser.GetAvailableMemoryInBytes(); | ||
| resourceQuota.BaselineMemoryInBytes = _parser.GetMinMemoryInBytes(); | ||
|
|
||
| if (resourceQuota.BaselineMemoryInBytes == 0) | ||
| { | ||
| resourceQuota.BaselineMemoryInBytes = resourceQuota.MaxMemoryInBytes; | ||
| } | ||
|
|
||
| return resourceQuota; | ||
| } | ||
| } | ||
|
|
This file contains hidden or 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 hidden or 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
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.
Uh oh!
There was an error while loading. Please reload this page.